# HG changeset patch # User duke # Date 1499265757 -7200 # Node ID 11d2418bf7c18ab869a8c0e1598a1ace34d3658a # Parent 62c548002ecb672a256add536b53f47ae27af916# Parent b91d80edba0f27b699ccf7b2ccda10c5558ca738 Merge diff -r 62c548002ecb -r 11d2418bf7c1 .hgtags-top-repo --- a/.hgtags-top-repo Fri Oct 10 13:29:11 2008 -0700 +++ b/.hgtags-top-repo Wed Jul 05 16:42:37 2017 +0200 @@ -11,3 +11,4 @@ 46a989ab932992b2084b946eeb322fa99b9fee6c jdk7-b34 143c1abedb7d3095eff0f9ee5fec9bf48e3490fc jdk7-b35 4b4f5fea8d7d0743f0c30d91fcd9bf9d96e5d2ad jdk7-b36 +744554f5a3290e11c71cd2ddb1aff49e431f9ed0 jdk7-b37 diff -r 62c548002ecb -r 11d2418bf7c1 corba/.hgtags --- a/corba/.hgtags Fri Oct 10 13:29:11 2008 -0700 +++ b/corba/.hgtags Wed Jul 05 16:42:37 2017 +0200 @@ -11,3 +11,4 @@ 0a812b9824e5d17b073765d1505594b49ff88a10 jdk7-b34 3867c4d14a5bfdbb37c97b4874ccb0ee5343111c jdk7-b35 0723891eb8d1c27e67c54163af0b4cea05a4e036 jdk7-b36 +59d5848bdedebe91cc2753acce78911bcb4a66db jdk7-b37 diff -r 62c548002ecb -r 11d2418bf7c1 corba/make/common/Defs-windows.gmk --- a/corba/make/common/Defs-windows.gmk Fri Oct 10 13:29:11 2008 -0700 +++ b/corba/make/common/Defs-windows.gmk Wed Jul 05 16:42:37 2017 +0200 @@ -58,11 +58,24 @@ # The following DLL's are considered MS runtime libraries and should # not to be REBASEd, see deploy/make/common/Release.gmk. -# msvcrt.dll, msvcr71.dll: Microsoft runtimes +# msvcrt.dll, msvcrnn.dll [msvcr71 or msvcr80 or msvcr90] : Microsoft runtimes MS_RUNTIME_LIBRARIES = msvcrt.dll +MSVCRNN_DLL = ifeq ($(ARCH_DATA_MODEL), 32) ifeq ($(COMPILER_VERSION), VS2003) - MS_RUNTIME_LIBRARIES += msvcr71.dll + MSVCRNN_DLL = msvcr71.dll + MSVCPNN_DLL = msvcp71.dll + MS_RUNTIME_LIBRARIES += $(MSVCRNN_DLL) + endif + ifeq ($(COMPILER_VERSION), VS2005) + MSVCRNN_DLL = msvcr80.dll + MSVCPNN_DLL = msvcp80.dll + MS_RUNTIME_LIBRARIES += $(MSVCRNN_DLL) + endif + ifeq ($(COMPILER_VERSION), VS2008) + MSVCRNN_DLL = msvcr90.dll + MSVCPNN_DLL = msvcp90.dll + MS_RUNTIME_LIBRARIES += $(MSVCRNN_DLL) endif endif @@ -148,6 +161,20 @@ CC_LOWER_OPT = -O1 endif endif + ifeq ($(COMPILER_VERSION), VS2008) + # Automatic precompiled header option to use (if COMPILE_APPROACH=batch) + AUTOMATIC_PCH_OPTION = + GX_OPTION = -EHsc + ifeq ($(ARCH_DATA_MODEL), 32) + CC_HIGHEST_OPT = -O2 + CC_HIGHER_OPT = -O1 + CC_LOWER_OPT = -O1 + else + CC_HIGHEST_OPT = -O2 + CC_HIGHER_OPT = -O1 + CC_LOWER_OPT = -O1 + endif + endif CC_NO_OPT = -Od else # CC_VERSION # GCC not supported, but left for historical reference... @@ -179,7 +206,7 @@ # -MTd Use static debug version (better than -MDd, no runtime issues) # -D_DEBUG Change use of malloc/free/etc to use special debug ones (-MTd) # -# NOTE: We also will use /D _STATIC_CPPLIB so we don't need msvcp71.dll +# NOTE: We also will use /D _STATIC_CPPLIB so we don't need msvcpnn.dll # ifeq ($(MS_RUNTIME_STATIC),true) MS_RUNTIME_OPTION=-MT @@ -217,7 +244,7 @@ # -YX -Fp/.../foobar.pch Use precompiled headers (try someday?) # -nologo Don't print out startup message # /D _STATIC_CPPLIB - # Use static link for the C++ runtime (so msvcp71.dll not needed) + # Use static link for the C++ runtime (so msvcpnn.dll not needed) # CFLAGS_COMMON += -Zi -nologo CFLAGS_OPT = $(POPT) diff -r 62c548002ecb -r 11d2418bf7c1 corba/make/common/shared/Compiler-msvc.gmk --- a/corba/make/common/shared/Compiler-msvc.gmk Fri Oct 10 13:29:11 2008 -0700 +++ b/corba/make/common/shared/Compiler-msvc.gmk Wed Jul 05 16:42:37 2017 +0200 @@ -47,24 +47,17 @@ # unset any GNU Make settings of MFLAGS and MAKEFLAGS which may mess up nmake NMAKE = MFLAGS= MAKEFLAGS= $(COMPILER_PATH)nmake -nologo + # Compiler version and type (Always get word after "Version") + CC_VER := $(shell $(CC) 2>&1 | $(HEAD) -n 1 | $(SED) 's/.*\(Version.*\)/\1/' | $(NAWK) '{print $$2}') + # SDK-64 and MSVC6 put REBASE.EXE in a different places - go figure... ifeq ($(ARCH_DATA_MODEL), 32) - CC_VER := $(shell $(CC) 2>&1 | $(HEAD) -n 1 | $(NAWK) '{print $$8}') LINK_VER := $(shell $(LINK) | $(HEAD) -n 1 | $(NAWK) '{print $$6}') - CC_TYPE := $(shell $(CC) 2>&1 | $(HEAD) -n 1 | $(NAWK) '{print $$5}') CC_MAJORVER :=$(call MajorVersion,$(CC_VER)) - REQUIRED_CCTYPE = Optimizing - REQUIRED_CC_VER = 13.10.3077 - REQUIRED_LINK_VER = 7.10.3077 - ifeq ($(CC_MAJORVER), 12) - # This should be: CC_VER=12.00.8168 LINK_VER=6.00.8447 - COMPILER_NAME=Visual C++ 6.0 Professional + VC6-SP 3 - COMPILER_VERSION=VC6 - REBASE = $(COMPILER_PATH)rebase - MTL = $(COMPILER_PATH)midl - endif ifeq ($(CC_MAJORVER), 13) # This should be: CC_VER=13.10.3077 LINK_VER=7.10.3077 + REQUIRED_CC_VER = 13.10.3077 + REQUIRED_LINK_VER = 7.10.3077 COMPILER_NAME=Visual Studio .NET 2003 Professional C++ COMPILER_VERSION=VS2003 REBASE = $(COMPILER_PATH)../../Common7/Tools/Bin/rebase @@ -74,9 +67,10 @@ endif endif ifeq ($(CC_MAJORVER), 14) - # This should be: CC_VER=14.00.0000 LINK_VER=8.00.0000 - # NOTE: This compiler has not been tried yet on 32bit systems - COMPILER_NAME=Visual Studio .NET 2005 + # This should be: CC_VER=14.00.50727.42 LINK_VER=8.00.50727.42 + REQUIRED_CC_VER = 14.00.50727.42 + REQUIRED_LINK_VER = 8.00.50727.42 + COMPILER_NAME=Visual Studio 8 COMPILER_VERSION=VS2005 REBASE = $(COMPILER_PATH)../../Common8/Tools/Bin/rebase MTL = $(COMPILER_PATH)../../Common8/Tools/Bin/midl @@ -84,10 +78,22 @@ COMPILER_PATH := $(error COMPILER_PATH cannot be empty here) endif endif + ifeq ($(CC_MAJORVER), 15) + # This should be: CC_VER=15.00.21022.08 LINK_VER=9.00.21022.08 + REQUIRED_CC_VER = 15.00.21022.08 + REQUIRED_LINK_VER = 9.00.21022.08 + COMPILER_NAME=Visual Studio 9 + COMPILER_VERSION=VS2008 + #rebase and midl moved out of Visual Studio into the SDK: + REBASE = $(MSDEVTOOLS_PATH)/rebase + MTL = $(MSDEVTOOLS_PATH)/midl.exe + ifndef COMPILER_PATH + COMPILER_PATH := $(error COMPILER_PATH cannot be empty here) + endif + endif else - CC_VER := $(shell $(CC) 2>&1 | $(HEAD) -n 1 | $(NAWK) '{print $$7}') + # else ARCH_DATA_MODEL is 64 LINK_VER := $(shell $(LINK) | $(HEAD) -n 1 | $(NAWK) '{print $$6}') - CC_TYPE := $(shell $(CC) 2>&1 | $(HEAD) -n 1 | $(NAWK) '{print $$4}') CC_MAJORVER :=$(call MajorVersion,$(CC_VER)) CC_MINORVER :=$(call MinorVersion,$(CC_VER)) CC_MICROVER :=$(call MicroVersion,$(CC_VER)) diff -r 62c548002ecb -r 11d2418bf7c1 hotspot/.hgtags --- a/hotspot/.hgtags Fri Oct 10 13:29:11 2008 -0700 +++ b/hotspot/.hgtags Wed Jul 05 16:42:37 2017 +0200 @@ -11,3 +11,4 @@ 5251a9cd8eb8743eee647365bee1c8afdc131556 jdk7-b34 5fa96a5a7e76da7c8dad12486293a0456c2c116c jdk7-b35 e91159f921a58af3698e6479ea1fc5818da66d09 jdk7-b36 +9ee9cf798b59e7d51f8c0a686959f313867a55d6 jdk7-b37 diff -r 62c548002ecb -r 11d2418bf7c1 jaxp/.hgtags --- a/jaxp/.hgtags Fri Oct 10 13:29:11 2008 -0700 +++ b/jaxp/.hgtags Wed Jul 05 16:42:37 2017 +0200 @@ -11,3 +11,4 @@ 01facdf8cabdeaaf68cca037aef56cc5f074897f jdk7-b34 eac46d1eb7f0935ba04f1c7929ec15423fd0309e jdk7-b35 c84ca638db42a8b6b227b4e3b63bca192c5ca634 jdk7-b36 +af49591bc486d82aa04b832257de0d18adc9af52 jdk7-b37 diff -r 62c548002ecb -r 11d2418bf7c1 jaxws/.hgtags --- a/jaxws/.hgtags Fri Oct 10 13:29:11 2008 -0700 +++ b/jaxws/.hgtags Wed Jul 05 16:42:37 2017 +0200 @@ -11,3 +11,4 @@ 7a9f629cd957e3169a1a769f763fe060d078785c jdk7-b34 b0f01c2508b690dd225298edfec70b5e8b8dc367 jdk7-b35 f60187f44a0d62906a5e2f6bd0989b5b24c1ca1e jdk7-b36 +a2a6f9edf761934faf59ea60d7fe7178371302cd jdk7-b37 diff -r 62c548002ecb -r 11d2418bf7c1 jdk/.hgtags --- a/jdk/.hgtags Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/.hgtags Wed Jul 05 16:42:37 2017 +0200 @@ -11,3 +11,4 @@ 434055a0716ee44bca712ebca02fc04b20e6e288 jdk7-b34 cf4894b78ceb966326e93bf221db0c2d14d59218 jdk7-b35 134fd1a656ea85acd1f97f6700f75029b9b472a0 jdk7-b36 +14f50aee4989b75934d385c56a83da0c23d2f68b jdk7-b37 diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/com/sun/Makefile --- a/jdk/make/com/sun/Makefile Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/com/sun/Makefile Wed Jul 05 16:42:37 2017 +0200 @@ -41,7 +41,7 @@ # Omit mirror since it's built with the apt tool. SUBDIRS = $(SCRIPT_SUBDIR) image security crypto/provider jndi jmx \ java inputmethods org xml rowset net/httpserver net/ssl demo \ - tools jarsigner tracing + tools jarsigner tracing servicetag all build clean clobber:: $(SUBDIRS-loop) diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/com/sun/servicetag/Makefile --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/make/com/sun/servicetag/Makefile Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,80 @@ +# Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Sun designates this +# particular file as subject to the "Classpath" exception as provided +# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. + +BUILDDIR = ../../.. +PACKAGE = com.sun.servicetag +PRODUCT = sun +include $(BUILDDIR)/common/Defs.gmk + +# +# Files to compile +# +AUTO_FILES_JAVA_DIRS = com/sun/servicetag + +# +# Rules +# +include $(BUILDDIR)/common/Classes.gmk + +SERVICETAG_LIBDIR = $(LIBDIR)/servicetag +SERVICETAG_RESOURCES_DIR = $(CLASSDESTDIR)/com/sun/servicetag/resources +FILES_copy = $(SERVICETAG_RESOURCES_DIR)/product_registration.xsd \ + $(SERVICETAG_RESOURCES_DIR)/register.html \ + $(SERVICETAG_RESOURCES_DIR)/register_ja.html \ + $(SERVICETAG_RESOURCES_DIR)/register_zh_CN.html \ + $(SERVICETAG_LIBDIR)/jdk_header.png + +# Add all properties files to the FILES_copy list +SWORDFISH_properties := $(shell \ + $(CD) $(SHARE_SRC)/classes/com/sun/servicetag/resources; \ + $(FIND) . -name 'javase_*_swordfish.properties' -print ; \ + ) +FILES_copy += $(shell \ + for f in $(SWORDFISH_properties) ; do \ + echo $(SERVICETAG_RESOURCES_DIR)/$$f ; \ + done \ +) + + +# +#OTHER_JAVACFLAGS += -Xlint:unchecked + +build: install-servicetag-lib copy-files + +copy-files: $(FILES_copy) + +$(CLASSBINDIR)/%: $(SHARE_SRC)/classes/% + $(install-file) + +$(SERVICETAG_LIBDIR)/jdk_header.png: $(SHARE_SRC)/classes/com/sun/servicetag/resources/jdk_header.png + $(install-file) + $(CHMOD) 444 $@ + +install-servicetag-lib: + @$(RM) -rf $(SERVICETAG_LIBDIR) + $(MKDIR) $(SERVICETAG_LIBDIR) + +clean clobber:: + @$(RM) $(FILES_copy) + +.PHONY: copy-files diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/java/java/FILES_java.gmk --- a/jdk/make/java/java/FILES_java.gmk Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/java/java/FILES_java.gmk Wed Jul 05 16:42:37 2017 +0200 @@ -209,6 +209,7 @@ sun/util/TimeZoneNameUtility.java \ sun/util/calendar/ZoneInfo.java \ sun/util/calendar/ZoneInfoFile.java \ + sun/util/calendar/TzIDOldMapping.java \ java/util/TooManyListenersException.java \ java/util/Comparator.java \ java/util/Collections.java \ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/javax/swing/Makefile --- a/jdk/make/javax/swing/Makefile Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/javax/swing/Makefile Wed Jul 05 16:42:37 2017 +0200 @@ -33,7 +33,7 @@ # Files # include FILES.gmk -AUTO_FILES_JAVA_DIRS = javax/swing sun/swing +AUTO_FILES_JAVA_DIRS = javax/swing sun/swing com/sun/java/swing AUTO_JAVA_PRUNE = plaf SUBDIRS = html32dtd plaf diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/javazic/tzdata/VERSION --- a/jdk/make/sun/javazic/tzdata/VERSION Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/javazic/tzdata/VERSION Wed Jul 05 16:42:37 2017 +0200 @@ -21,4 +21,4 @@ # CA 95054 USA or visit www.sun.com if you need additional information or # have any questions. # -tzdata2007h +tzdata2008e diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/javazic/tzdata/africa --- a/jdk/make/sun/javazic/tzdata/africa Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/javazic/tzdata/africa Wed Jul 05 16:42:37 2017 +0200 @@ -409,9 +409,63 @@ 0:00 - GMT # Mauritius + +# From Steffen Thorsen (2008-06-25): +# Mauritius plans to observe DST from 2008-11-01 to 2009-03-31 on a trial +# basis.... +# It seems that Mauritius observed daylight saving time from 1982-10-10 to +# 1983-03-20 as well, but that was not successful.... +# http://www.timeanddate.com/news/time/mauritius-daylight-saving-time.html + +# From Alex Krivenyshev (2008-06-25): +# http://economicdevelopment.gov.mu/portal/site/Mainhomepage/menuitem.a42b24128104d9845dabddd154508a0c/?content_id=0a7cee8b5d69a110VgnVCM1000000a04a8c0RCRD + +# From Arthur David Olson (2008-06-30): +# The www.timeanddate.com article cited by Steffen Thorsen notes that "A +# final decision has yet to be made on the times that daylight saving +# would begin and end on these dates." As a place holder, use midnight. + +# From Paul Eggert (2008-06-30): +# Follow Thorsen on DST in 1982/1983, instead of Shanks & Pottenger. + +# From Steffen Thorsen (2008-07-10): +# According to +# +# http://www.lexpress.mu/display_article.php?news_id=111216 +# +# (in French), Mauritius will start and end their DST a few days earlier +# than previously announced (2008-11-01 to 2009-03-31). The new start +# date is 2008-10-26 at 02:00 and the new end date is 2009-03-27 (no time +# given, but it is probably at either 2 or 3 wall clock time). +# +# A little strange though, since the article says that they moved the date +# to align itself with Europe and USA which also change time on that date, +# but that means they have not paid attention to what happened in +# USA/Canada last year (DST ends first Sunday in November). I also wonder +# why that they end on a Friday, instead of aligning with Europe which +# changes two days later. + +# From Alex Krivenyshev (2008-07-11): +# Seems that English language article "The revival of daylight saving +# time: Energy conservation?"-# No. 16578 (07/11/2008) was originally +# published on Monday, June 30, 2008... +# +# I guess that article in French "Le gouvernement avance l'introduction +# de l'heure d'ete" stating that DST in Mauritius starting on October 26 +# and ending on March 27, 2009 is the most recent one. +# ... +# +# http://www.worldtimezone.com/dst_news/dst_news_mauritius02.html +# + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Mauritius 1982 only - Oct 10 0:00 1:00 S +Rule Mauritius 1983 only - Mar 21 0:00 0 - +Rule Mauritius 2008 only - Oct 26 2:00s 1:00 S +Rule Mauritius 2009 only - Mar 27 2:00s 0 - # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Indian/Mauritius 3:50:00 - LMT 1907 # Port Louis - 4:00 - MUT # Mauritius Time + 4:00 Mauritius MU%sT # Mauritius Time # Agalega Is, Rodriguez # no information; probably like Indian/Mauritius @@ -422,6 +476,77 @@ # Morocco # See the `europe' file for Spanish Morocco (Africa/Ceuta). + +# From Alex Krivenyshev (2008-05-09): +# Here is an article that Morocco plan to introduce Daylight Saving Time between +# 1 June, 2008 and 27 September, 2008. +# +# "... Morocco is to save energy by adjusting its clock during summer so it will +# be one hour ahead of GMT between 1 June and 27 September, according to +# Communication Minister and Gov ernment Spokesman, Khalid Naciri...." +# +# +# http://www.worldtimezone.net/dst_news/dst_news_morocco01.html +# +# OR +# +# http://en.afrik.com/news11892.html +# + +# From Alex Krivenyshev (2008-05-09): +# The Morocco time change can be confirmed on Morocco web site Maghreb Arabe Presse: +# +# http://www.map.ma/eng/sections/box3/morocco_shifts_to_da/view +# +# +# Morocco shifts to daylight time on June 1st through September 27, Govt. +# spokesman. + +# From Patrice Scattolin (2008-05-09): +# According to this article: +# +# http://www.avmaroc.com/actualite/heure-dete-comment-a127896.html +# +# (and republished here: +# +# http://www.actu.ma/heure-dete-comment_i127896_0.html +# +# ) +# the changes occurs at midnight: +# +# saturday night may 31st at midnight (which in french is to be +# intrepreted as the night between saturday and sunday) +# sunday night the 28th at midnight +# +# Seeing that the 28th is monday, I am guessing that she intends to say +# the midnight of the 28th which is the midnight between sunday and +# monday, which jives with other sources that say that it's inclusive +# june1st to sept 27th. +# +# The decision was taken by decree *2-08-224 *but I can't find the decree +# published on the web. +# +# It's also confirmed here: +# +# http://www.maroc.ma/NR/exeres/FACF141F-D910-44B0-B7FA-6E03733425D1.htm +# +# on a government portal as being between june 1st and sept 27th (not yet +# posted in english). +# +# The following google query will generate many relevant hits: +# +# http://www.google.com/search?hl=en&q=Conseil+de+gouvernement+maroc+heure+avance&btnG=Search +# + +# From Alex Krivenyshev (2008-05-09): +# Is Western Sahara (part which administrated by Morocco) going to follow +# Morocco DST changes? Any information? What about other part of +# Western Sahara - under administration of POLISARIO Front (also named +# SADR Saharawi Arab Democratic Republic)? + +# From Arthur David Olson (2008-05-09): +# XXX--guess that it is only Morocco for now; guess only 2008 for now. + # RULE NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Morocco 1939 only - Sep 12 0:00 1:00 S Rule Morocco 1939 only - Nov 19 0:00 0 - @@ -438,11 +563,13 @@ Rule Morocco 1977 only - Sep 28 0:00 0 - Rule Morocco 1978 only - Jun 1 0:00 1:00 S Rule Morocco 1978 only - Aug 4 0:00 0 - +Rule Morocco 2008 only - Jun 1 0:00 1:00 S +Rule Morocco 2008 only - Sep 28 0:00 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 1:00 - CET 1986 - 0:00 - WET + 0:00 Morocco WE%sT # Western Sahara Zone Africa/El_Aaiun -0:52:48 - LMT 1934 Jan -1:00 - WAT 1976 Apr 14 diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/javazic/tzdata/asia --- a/jdk/make/sun/javazic/tzdata/asia Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/javazic/tzdata/asia Wed Jul 05 16:42:37 2017 +0200 @@ -251,6 +251,28 @@ # (could be true), for the moment I am assuming that those two # counties are mistakes in the astro.com data. +# From Paul Eggert (2008-02-11): +# I just now checked Google News for western news sources that talk +# about China's single time zone, and couldn't find anything before 1986 +# talking about China being in one time zone. (That article was: Jim +# Mann, "A clumsy embrace for another western custom: China on daylight +# time--sort of", Los Angeles Times, 1986-05-05. By the way, this +# article confirms the tz database's data claiming that China began +# observing daylight saving time in 1986. +# +# From Thomas S. Mullaney (2008-02-11): +# I think you're combining two subjects that need to treated +# separately: daylight savings (which, you're correct, wasn't +# implemented until the 1980s) and the unified time zone centered near +# Beijing (which was implemented in 1949). Briefly, there was also a +# "Lhasa Time" in Tibet and "Urumqi Time" in Xinjiang. The first was +# ceased, and the second eventually recognized (again, in the 1980s). +# +# From Paul Eggert (2008-06-30): +# There seems to be a good chance China switched to a single time zone in 1949 +# rather than in 1980 as Shanks & Pottenger have it, but we don't have a +# reliable documentary source saying so yet, so for now we still go with +# Shanks & Pottenger. # Zone NAME GMTOFF RULES FORMAT [UNTIL] # Changbai Time ("Long-white Time", Long-white = Heilongjiang area) @@ -468,13 +490,13 @@ # India # Zone NAME GMTOFF RULES FORMAT [UNTIL] -Zone Asia/Calcutta 5:53:28 - LMT 1880 # Kolkata +Zone Asia/Kolkata 5:53:28 - LMT 1880 # Kolkata 5:53:20 - HMT 1941 Oct # Howrah Mean Time? 6:30 - BURT 1942 May 15 # Burma Time 5:30 - IST 1942 Sep 5:30 1:00 IST 1945 Oct 15 5:30 - IST -# The following are like Asia/Calcutta: +# The following are like Asia/Kolkata: # Andaman Is # Lakshadweep (Laccadive, Minicoy and Amindivi Is) # Nicobar Is @@ -599,6 +621,15 @@ # daylight saving time ... # http://uk.reuters.com/article/oilRpt/idUKBLA65048420070916 # +# From Roozbeh Pournader (2007-11-05): +# This is quoted from Official Gazette of the Islamic Republic of +# Iran, Volume 63, Number 18242, dated Tuesday 1386/6/24 +# [2007-10-16]. I am doing the best translation I can:... +# The official time of the country will be moved forward for one hour +# on the 24 hours of the first day of the month of Farvardin and will +# be changed back to its previous state on the 24 hours of the +# thirtieth day of Shahrivar. +# # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Iran 1978 1980 - Mar 21 0:00 1:00 D Rule Iran 1978 only - Oct 21 0:00 0 S @@ -673,6 +704,21 @@ # # So we'll ignore the Economist's claim. +# From Steffen Thorsen (2008-03-10): +# The cabinet in Iraq abolished DST last week, according to the following +# news sources (in Arabic): +# +# http://www.aljeeran.net/wesima_articles/news-20080305-98602.html +# +# +# http://www.aswataliraq.info/look/article.tpl?id=2047&IdLanguage=17&IdPublication=4&NrArticle=71743&NrIssue=1&NrSection=10 +# +# +# We have published a short article in English about the change: +# +# http://www.timeanddate.com/news/time/iraq-dumps-daylight-saving.html +# + # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Iraq 1982 only - May 1 0:00 1:00 D Rule Iraq 1982 1984 - Oct 1 0:00 0 S @@ -683,8 +729,8 @@ # IATA SSIM (1991/1996) says Apr 1 12:01am UTC; guess the `:01' is a typo. # Shanks & Pottenger say Iraq did not observe DST 1992/1997; ignore this. # -Rule Iraq 1991 max - Apr 1 3:00s 1:00 D -Rule Iraq 1991 max - Oct 1 3:00s 0 S +Rule Iraq 1991 2007 - Apr 1 3:00s 1:00 D +Rule Iraq 1991 2007 - Oct 1 3:00s 0 S # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Asia/Baghdad 2:57:40 - LMT 1890 2:57:36 - BMT 1918 # Baghdad Mean Time? @@ -1374,6 +1420,42 @@ # They decided not to adopt daylight-saving time.... # http://www.mongolnews.mn/index.php?module=unuudur&sec=view&id=15742 +# From Deborah Goldsmith (2008-03-30): +# We received a bug report claiming that the tz database UTC offset for +# Asia/Choibalsan (GMT+09:00) is incorrect, and that it should be GMT +# +08:00 instead. Different sources appear to disagree with the tz +# database on this, e.g.: +# +# +# http://www.timeanddate.com/worldclock/city.html?n=1026 +# +# +# http://www.worldtimeserver.com/current_time_in_MN.aspx +# +# +# both say GMT+08:00. + +# From Steffen Thorsen (2008-03-31): +# eznis airways, which operates several domestic flights, has a flight +# schedule here: +# +# http://www.eznis.com/Container.jsp?id=112 +# +# (click the English flag for English) +# +# There it appears that flights between Choibalsan and Ulaanbatar arrive +# about 1:35 - 1:50 hours later in local clock time, no matter the +# direction, while Ulaanbaatar-Khvod takes 2 hours in the Eastern +# direction and 3:35 back, which indicates that Ulaanbatar and Khvod are +# in different time zones (like we know about), while Choibalsan and +# Ulaanbatar are in the same time zone (correction needed). + +# From Arthur David Olson (2008-05-19): +# Assume that Choibalsan is indeed offset by 8:00. +# XXX--in the absence of better information, assume that transition +# was at the start of 2008-03-31 (the day of Steffen Thorsen's report); +# this is almost surely wrong. + # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Mongol 1983 1984 - Apr 1 0:00 1:00 S Rule Mongol 1983 only - Oct 1 0:00 0 - @@ -1409,7 +1491,8 @@ Zone Asia/Choibalsan 7:38:00 - LMT 1905 Aug 7:00 - ULAT 1978 8:00 - ULAT 1983 Apr - 9:00 Mongol CHO%sT # Choibalsan Time + 9:00 Mongol CHO%sT 2008 Mar 31 # Choibalsan Time + 8:00 Mongol CHO%sT # Nepal # Zone NAME GMTOFF RULES FORMAT [UNTIL] @@ -1459,10 +1542,32 @@ # The minister told a news conference that the experiment had rather # shown 8 per cent higher consumption of electricity. +# From Alex Krivenyshev (2008-05-15): +# +# Here is an article that Pakistan plan to introduce Daylight Saving Time +# on June 1, 2008 for 3 months. +# +# "... The federal cabinet on Wednesday announced a new conservation plan to help +# reduce load shedding by approving the closure of commercial centres at 9pm and +# moving clocks forward by one hour for the next three months. +# ...." +# +# +# http://www.worldtimezone.net/dst_news/dst_news_pakistan01.html +# +# OR +# +# http://www.dailytimes.com.pk/default.asp?page=2008%5C05%5C15%5Cstory_15-5-2008_pg1_4 +# + +# From Arthur David Olson (2008-05-19): +# XXX--midnight transitions is a guess; 2008 only is a guess. # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Pakistan 2002 only - Apr Sun>=2 0:01 1:00 S Rule Pakistan 2002 only - Oct Sun>=2 0:01 0 - +Rule Pakistan 2008 only - Jun 1 0:00 1:00 S +Rule Pakistan 2008 only - Sep 1 0:00 0 - # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Asia/Karachi 4:28:12 - LMT 1907 5:30 - IST 1942 Sep @@ -1700,7 +1805,7 @@ # kept their clocks set five and a half hours ahead of Greenwich Mean # Time (GMT), in line with neighbor India. # From Paul Eggert (2006-04-18): -# People who live in regions under Tamil control can use TZ='Asia/Calcutta', +# People who live in regions under Tamil control can use [TZ='Asia/Kolkata'], # as that zone has agreed with the Tamil areas since our cutoff date of 1970. # From K Sethu (2006-04-25): @@ -1790,10 +1895,62 @@ # From Paul Eggert (2007-03-29): # Today the AP reported "Syria will switch to summertime at midnight Thursday." # http://www.iht.com/articles/ap/2007/03/29/africa/ME-GEN-Syria-Time-Change.php -# For lack of better info, assume the rule changed to "last Friday in March" -# this year. -Rule Syria 2007 max - Mar lastFri 0:00 1:00 S -Rule Syria 2007 max - Oct 1 0:00 0 - +Rule Syria 2007 only - Mar lastFri 0:00 1:00 S +# From Jesper Norgard (2007-10-27): +# The sister center ICARDA of my work CIMMYT is confirming that Syria DST will +# not take place 1.st November at 0:00 o'clock but 1.st November at 24:00 or +# rather Midnight between Thursday and Friday. This does make more sence than +# having it between Wednesday and Thursday (two workdays in Syria) since the +# weekend in Syria is not Saturday and Sunday, but Friday and Saturday. So now +# it is implemented at midnight of the last workday before weekend... +# +# From Steffen Thorsen (2007-10-27): +# Jesper Norgaard Welen wrote: +# +# > "Winter local time in Syria will be observed at midnight of Thursday 1 +# > November 2007, and the clock will be put back 1 hour." +# +# I found confirmation on this in this gov.sy-article (Arabic): +# http://wehda.alwehda.gov.sy/_print_veiw.asp?FileName=12521710520070926111247 +# +# which using Google's translate tools says: +# Council of Ministers also approved the commencement of work on +# identifying the winter time as of Friday, 2/11/2007 where the 60th +# minute delay at midnight Thursday 1/11/2007. +Rule Syria 2007 only - Nov Fri>=1 0:00 0 - + +# From Stephen Colebourne (2008-03-17): +# For everyone's info, I saw an IATA time zone change for [Syria] for +# this month (March 2008) in the last day or so...This is the data IATA +# are now using: +# Country Time Standard --- DST Start --- --- DST End --- DST +# Name Zone Variation Time Date Time Date +# Variation +# Syrian Arab +# Republic SY +0200 2200 03APR08 2100 30SEP08 +0300 +# 2200 02APR09 2100 30SEP09 +0300 +# 2200 01APR10 2100 30SEP10 +0300 + +# From Arthur David Olson (2008-03-17): +# Here's a link to English-language coverage by the Syrian Arab News +# Agency (SANA)... +# +# http://www.sana.sy/eng/21/2008/03/11/165173.htm +# ...which reads (in part) "The Cabinet approved the suggestion of the +# Ministry of Electricity to begin daylight savings time on Friday April +# 4th, advancing clocks one hour ahead on midnight of Thursday April 3rd." +# Since Syria is two hours east of UTC, the 2200 and 2100 transition times +# shown above match up with midnight in Syria. + +# From Arthur David Olson (2008-03-18): +# My buest guess at a Syrian rule is "the Friday nearest April 1"; +# coding that involves either using a "Mar Fri>=29" construct that old time zone +# compilers can't handle or having multiple Rules (a la Israel). +# For now, use "Apr Fri>=1", and go with IATA on a uniform Sep 30 end. + +Rule Syria 2008 max - Apr Fri>=1 0:00 1:00 S +Rule Syria 2008 max - Oct 1 0:00 0 - + # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Asia/Damascus 2:25:12 - LMT 1920 # Dimashq 2:00 Syria EE%sT @@ -1847,13 +2004,13 @@ # Vietnam -# From Paul Eggert (1993-11-18): -# Saigon's official name is Thanh-Pho Ho Chi Minh, but it's too long. -# We'll stick with the traditional name for now. +# From Arthur David Olson (2008-03-18): +# The English-language name of Vietnam's most populous city is "Ho Chi Min City"; +# we use Ho_Chi_Minh below to avoid a name of more than 14 characters. # From Shanks & Pottenger: # Zone NAME GMTOFF RULES FORMAT [UNTIL] -Zone Asia/Saigon 7:06:40 - LMT 1906 Jun 9 +Zone Asia/Ho_Chi_Minh 7:06:40 - LMT 1906 Jun 9 7:06:20 - SMT 1911 Mar 11 0:01 # Saigon MT? 7:00 - ICT 1912 May 8:00 - ICT 1931 May diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/javazic/tzdata/australasia --- a/jdk/make/sun/javazic/tzdata/australasia Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/javazic/tzdata/australasia Wed Jul 05 16:42:37 2017 +0200 @@ -1368,7 +1368,7 @@ # * Tonga will introduce DST in November # # I was given this link by John Letts: -# +# # http://news.bbc.co.uk/hi/english/world/asia-pacific/newsid_424000/424764.stm # # @@ -1378,7 +1378,7 @@ # (12 + 1 hour DST). # From Arthur David Olson (1999-09-20): -# According to # http://www.tongaonline.com/news/sept1799.html # : # "Daylight Savings Time will take effect on Oct. 2 through April 15, 2000 diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/javazic/tzdata/backward --- a/jdk/make/sun/javazic/tzdata/backward Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/javazic/tzdata/backward Wed Jul 05 16:42:37 2017 +0200 @@ -46,12 +46,15 @@ Link Asia/Ashgabat Asia/Ashkhabad Link Asia/Chongqing Asia/Chungking Link Asia/Dhaka Asia/Dacca +Link Asia/Kolkata Asia/Calcutta Link Asia/Macau Asia/Macao Link Asia/Jerusalem Asia/Tel_Aviv +Link Asia/Ho_Chi_Minh Asia/Saigon Link Asia/Thimphu Asia/Thimbu Link Asia/Makassar Asia/Ujung_Pandang Link Asia/Ulaanbaatar Asia/Ulan_Bator Link Atlantic/Faroe Atlantic/Faeroe +Link Europe/Oslo Atlantic/Jan_Mayen Link Australia/Sydney Australia/ACT Link Australia/Sydney Australia/Canberra Link Australia/Lord_Howe Australia/LHI diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/javazic/tzdata/europe --- a/jdk/make/sun/javazic/tzdata/europe Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/javazic/tzdata/europe Wed Jul 05 16:42:37 2017 +0200 @@ -479,7 +479,7 @@ Rule EU 1981 max - Mar lastSun 1:00u 1:00 S Rule EU 1996 max - Oct lastSun 1:00u 0 - # The most recent directive covers the years starting in 2002. See: -# # Directive 2000/84/EC of the European Parliament and of the Council # of 19 January 2001 on summer-time arrangements. # @@ -502,9 +502,48 @@ Rule C-Eur 1942 only - Nov 2 2:00s 0 - Rule C-Eur 1943 only - Mar 29 2:00s 1:00 S Rule C-Eur 1943 only - Oct 4 2:00s 0 - -Rule C-Eur 1944 only - Apr 3 2:00s 1:00 S +Rule C-Eur 1944 1945 - Apr Mon>=1 2:00s 1:00 S # Whitman gives 1944 Oct 7; go with Shanks & Pottenger. Rule C-Eur 1944 only - Oct 2 2:00s 0 - +# From Jesper Norgaard Welen (2008-07-13): +# +# I found what is probably a typo of 2:00 which should perhaps be 2:00s +# in the C-Eur rule from tz database version 2008d (this part was +# corrected in version 2008d). The circumstancial evidence is simply the +# tz database itself, as seen below: +# +# Zone Europe/Paris 0:09:21 - LMT 1891 Mar 15 0:01 +# 0:00 France WE%sT 1945 Sep 16 3:00 +# +# Zone Europe/Monaco 0:29:32 - LMT 1891 Mar 15 +# 0:00 France WE%sT 1945 Sep 16 3:00 +# +# Zone Europe/Belgrade 1:22:00 - LMT 1884 +# 1:00 1:00 CEST 1945 Sep 16 2:00s +# +# Rule France 1945 only - Sep 16 3:00 0 - +# Rule Belgium 1945 only - Sep 16 2:00s 0 - +# Rule Neth 1945 only - Sep 16 2:00s 0 - +# +# The rule line to be changed is: +# +# Rule C-Eur 1945 only - Sep 16 2:00 0 - +# +# It seems that Paris, Monaco, Rule France, Rule Belgium all agree on +# 2:00 standard time, e.g. 3:00 local time. However there are no +# countries that use C-Eur rules in September 1945, so the only items +# affected are apparently these ficticious zones that translates acronyms +# CET and MET: +# +# Zone CET 1:00 C-Eur CE%sT +# Zone MET 1:00 C-Eur ME%sT +# +# It this is right then the corrected version would look like: +# +# Rule C-Eur 1945 only - Sep 16 2:00s 0 - +# +# A small step for mankind though 8-) +Rule C-Eur 1945 only - Sep 16 2:00s 0 - Rule C-Eur 1977 1980 - Apr Sun>=1 2:00s 1:00 S Rule C-Eur 1977 only - Sep lastSun 2:00s 0 - Rule C-Eur 1978 only - Oct 1 2:00s 0 - @@ -747,7 +786,8 @@ Zone Europe/Sofia 1:33:16 - LMT 1880 1:56:56 - IMT 1894 Nov 30 # Istanbul MT? 2:00 - EET 1942 Nov 2 3:00 - 1:00 C-Eur CE%sT 1945 Apr 2 3:00 + 1:00 C-Eur CE%sT 1945 + 1:00 - CET 1945 Apr 2 3:00 2:00 - EET 1979 Mar 31 23:00 2:00 Bulg EE%sT 1982 Sep 26 2:00 2:00 C-Eur EE%sT 1991 @@ -1115,33 +1155,40 @@ # [See tz-link.htm for the URL.] # From Joerg Schilling (2002-10-23): -# In 1945, Berlin was switched to Moscow Summer time (GMT+4) by +# In 1945, Berlin was switched to Moscow Summer time (GMT+4) by +# # General [Nikolai] Bersarin. # From Paul Eggert (2003-03-08): # +# http://www.parlament-berlin.de/pds-fraktion.nsf/727459127c8b66ee8525662300459099/defc77cb784f180ac1256c2b0030274b/$FILE/bersarint.pdf +# # says that Bersarin issued an order to use Moscow time on May 20. # However, Moscow did not observe daylight saving in 1945, so # this was equivalent to CEMT (GMT+3), not GMT+4. # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S -Rule Germany 1945 only - Apr 2 2:00s 1:00 S -Rule Germany 1945 only - May 24 2:00 2:00 M # Midsummer -Rule Germany 1945 only - Sep 24 3:00 1:00 S -Rule Germany 1945 only - Nov 18 2:00s 0 - Rule Germany 1946 only - Apr 14 2:00s 1:00 S Rule Germany 1946 only - Oct 7 2:00s 0 - Rule Germany 1947 1949 - Oct Sun>=1 2:00s 0 - -Rule Germany 1947 only - Apr 6 2:00s 1:00 S +# http://www.ptb.de/de/org/4/44/441/salt.htm says the following transition +# occurred at 3:00 MEZ, not the 2:00 MEZ given in Shanks & Pottenger. +# Go with the PTB. +Rule Germany 1947 only - Apr 6 3:00s 1:00 S Rule Germany 1947 only - May 11 2:00s 2:00 M Rule Germany 1947 only - Jun 29 3:00 1:00 S Rule Germany 1948 only - Apr 18 2:00s 1:00 S Rule Germany 1949 only - Apr 10 2:00s 1:00 S + +Rule SovietZone 1945 only - May 24 2:00 2:00 M # Midsummer +Rule SovietZone 1945 only - Sep 24 3:00 1:00 S +Rule SovietZone 1945 only - Nov 18 2:00s 0 - + # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Europe/Berlin 0:53:28 - LMT 1893 Apr - 1:00 C-Eur CE%sT 1945 Apr 2 2:00 + 1:00 C-Eur CE%sT 1945 May 24 2:00 + 1:00 SovietZone CE%sT 1946 1:00 Germany CE%sT 1980 1:00 EU CE%sT @@ -1218,7 +1265,7 @@ Zone Europe/Budapest 1:16:20 - LMT 1890 Oct 1:00 C-Eur CE%sT 1918 1:00 Hungary CE%sT 1941 Apr 6 2:00 - 1:00 C-Eur CE%sT 1945 May 1 23:00 + 1:00 C-Eur CE%sT 1945 1:00 Hungary CE%sT 1980 Sep 28 2:00s 1:00 EU CE%sT @@ -1736,7 +1783,6 @@ # come up with more definitive info about the timekeeping during the # war years it's probably best just do do the following for now: Link Europe/Oslo Arctic/Longyearbyen -Link Europe/Oslo Atlantic/Jan_Mayen # Poland # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S @@ -2136,7 +2182,8 @@ # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Europe/Belgrade 1:22:00 - LMT 1884 1:00 - CET 1941 Apr 18 23:00 - 1:00 C-Eur CE%sT 1945 May 8 2:00s + 1:00 C-Eur CE%sT 1945 + 1:00 - CET 1945 May 8 2:00s 1:00 1:00 CEST 1945 Sep 16 2:00s # Metod Kozelj reports that the legal date of # transition to EU rules was 1982-11-27, for all of Yugoslavia at the time. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/javazic/tzdata/iso3166.tab --- a/jdk/make/sun/javazic/tzdata/iso3166.tab Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/javazic/tzdata/iso3166.tab Wed Jul 05 16:42:37 2017 +0200 @@ -28,7 +28,7 @@ # # This file contains a table with the following columns: # 1. ISO 3166-1 alpha-2 country code, current as of -# ISO 3166-1 Newsletter No. V-12 (2006-09-26). See: +# ISO 3166-1 Newsletter VI-1 (2007-09-21). See: # # ISO 3166 Maintenance agency (ISO 3166/MA) # . @@ -69,6 +69,7 @@ BH Bahrain BI Burundi BJ Benin +BL St Barthelemy BM Bermuda BN Brunei BO Bolivia @@ -181,6 +182,7 @@ MC Monaco MD Moldova ME Montenegro +MF St Martin (French part) MG Madagascar MH Marshall Islands MK Macedonia diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/javazic/tzdata/leapseconds --- a/jdk/make/sun/javazic/tzdata/leapseconds Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/javazic/tzdata/leapseconds Wed Jul 05 16:42:37 2017 +0200 @@ -66,8 +66,10 @@ Leap 1997 Jun 30 23:59:60 + S Leap 1998 Dec 31 23:59:60 + S Leap 2005 Dec 31 23:59:60 + S +Leap 2008 Dec 31 23:59:60 + S # INTERNATIONAL EARTH ROTATION AND REFERENCE SYSTEMS SERVICE (IERS) +# # SERVICE INTERNATIONAL DE LA ROTATION TERRESTRE ET DES SYSTEMES DE REFERENCE # # SERVICE DE LA ROTATION TERRESTRE @@ -75,30 +77,38 @@ # 61, Av. de l'Observatoire 75014 PARIS (France) # Tel. : 33 (0) 1 40 51 22 26 # FAX : 33 (0) 1 40 51 22 91 -# Internet : services.iers@obspm.fr +# e-mail : services.iers@obspm.fr +# http://hpiers.obspm.fr/eop-pc # -# Paris, 28 June 2007 +# Paris, 4 July 2008 # -# Bulletin C 34 +# Bulletin C 36 # # To authorities responsible # for the measurement and # distribution of time # -# INFORMATION ON UTC - TAI +# UTC TIME STEP +# on the 1st of January 2009 +# +# A positive leap second will be introduced at the end of December 2008. +# The sequence of dates of the UTC second markers will be: # -# NO positive leap second will be introduced at the end of December 2007. -# The difference between Coordinated Universal Time UTC and the -# International Atomic Time TAI is : +# 2008 December 31, 23h 59m 59s +# 2008 December 31, 23h 59m 60s +# 2009 January 1, 0h 0m 0s # -# from 2006 January 1, 0h UTC, until further notice : UTC-TAI = -33 s +# The difference between UTC and the International Atomic Time TAI is: +# +# from 2006 January 1, 0h UTC, to 2009 January 1 0h UTC : UTC-TAI = - 33s +# from 2009 January 1, 0h UTC, until further notice : UTC-TAI = - 34s # # Leap seconds can be introduced in UTC at the end of the months of December -# or June, depending on the evolution of UT1-TAI. Bulletin C is mailed every -# six months, either to announce a time step in UTC, or to confirm that there +# or June, depending on the evolution of UT1-TAI. Bulletin C is mailed every +# six months, either to announce a time step in UTC or to confirm that there # will be no time step at the next possible date. # # Daniel GAMBIS -# Director +# Head # Earth Orientation Center of IERS # Observatoire de Paris, France diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/javazic/tzdata/northamerica --- a/jdk/make/sun/javazic/tzdata/northamerica Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/javazic/tzdata/northamerica Wed Jul 05 16:42:37 2017 +0200 @@ -2098,8 +2098,8 @@ # http://www.jonesbahamas.com/?c=45&a=10412 # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S -Rule Bahamas 1964 2006 - Oct lastSun 2:00 0 S -Rule Bahamas 1964 1986 - Apr lastSun 2:00 1:00 D +Rule Bahamas 1964 1975 - Oct lastSun 2:00 0 S +Rule Bahamas 1964 1975 - Apr lastSun 2:00 1:00 D # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone America/Nassau -5:09:24 - LMT 1912 Mar 2 -5:00 Bahamas E%sT 1976 @@ -2209,6 +2209,69 @@ # says Cuban clocks will advance at midnight on March 10. # For lack of better information, assume Cuba will use US rules, # except that it switches at midnight standard time as usual. +# +# From Steffen Thorsen (2007-10-25): +# Carlos Alberto Fonseca Arauz informed me that Cuba will end DST one week +# earlier - on the last Sunday of October, just like in 2006. +# +# He supplied these references: +# +# http://www.prensalatina.com.mx/article.asp?ID=%7B4CC32C1B-A9F7-42FB-8A07-8631AFC923AF%7D&language=ES +# http://actualidad.terra.es/sociedad/articulo/cuba_llama_ahorrar_energia_cambio_1957044.htm +# +# From Alex Kryvenishev (2007-10-25): +# Here is also article from Granma (Cuba): +# +# [Regira] el Horario Normal desde el [proximo] domingo 28 de octubre +# http://www.granma.cubaweb.cu/2007/10/24/nacional/artic07.html +# +# http://www.worldtimezone.com/dst_news/dst_news_cuba03.html + +# From Arthur David Olson (2008-03-09): +# I'm in Maryland which is now observing United States Eastern Daylight +# Time. At 9:44 local time I used RealPlayer to listen to +# +# http://media.enet.cu/radioreloj +# , a Cuban information station, and heard +# the time announced as "ocho cuarenta y cuatro" ("eight forty-four"), +# indicating that Cuba is still on standard time. + +# From Steffen Thorsen (2008-03-12): +# It seems that Cuba will start DST on Sunday, 2007-03-16... +# It was announced yesterday, according to this source (in Spanish): +# +# http://www.nnc.cubaweb.cu/marzo-2008/cien-1-11-3-08.htm +# +# +# Some more background information is posted here: +# +# http://www.timeanddate.com/news/time/cuba-starts-dst-march-16.html +# +# +# The article also says that Cuba has been observing DST since 1963, +# while Shanks (and tzdata) has 1965 as the first date (except in the +# 1940's). Many other web pages in Cuba also claim that it has been +# observed since 1963, but with the exception of 1970 - an exception +# which is not present in tzdata/Shanks. So there is a chance we need to +# change some historic records as well. +# +# One example: +# +# http://www.radiohc.cu/espanol/noticias/mar07/11mar/hor.htm +# + +# From Jesper Norgaard Welen (2008-03-13): +# The Cuban time change has just been confirmed on the most authoritative +# web site, the Granma. Please check out +# +# http://www.granma.cubaweb.cu/2008/03/13/nacional/artic10.html +# +# +# Basically as expected after Steffen Thorsens information, the change +# will take place midnight between Saturday and Sunday. + +# From Arthur David Olson (2008-03-12): +# Assume Sun>=15 (third Sunday) going forward. # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Cuba 1928 only - Jun 10 0:00 1:00 D @@ -2240,9 +2303,9 @@ Rule Cuba 1998 1999 - Mar lastSun 0:00s 1:00 D Rule Cuba 1998 2003 - Oct lastSun 0:00s 0 S Rule Cuba 2000 2006 - Apr Sun>=1 0:00s 1:00 D -Rule Cuba 2006 only - Oct lastSun 0:00s 0 S -Rule Cuba 2007 max - Mar Sun>=8 0:00s 1:00 D -Rule Cuba 2007 max - Nov Sun>=1 0:00s 0 S +Rule Cuba 2006 max - Oct lastSun 0:00s 0 S +Rule Cuba 2007 only - Mar Sun>=8 0:00s 1:00 D +Rule Cuba 2008 max - Mar Sun>=15 0:00s 1:00 D # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone America/Havana -5:29:28 - LMT 1890 @@ -2309,6 +2372,10 @@ # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone America/Guadeloupe -4:06:08 - LMT 1911 Jun 8 # Pointe a Pitre -4:00 - AST +# St Barthelemy +Link America/Guadeloupe America/St_Barthelemy +# St Martin (French part) +Link America/Guadeloupe America/Marigot # Guatemala # diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/javazic/tzdata/southamerica --- a/jdk/make/sun/javazic/tzdata/southamerica Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/javazic/tzdata/southamerica Wed Jul 05 16:42:37 2017 +0200 @@ -127,7 +127,11 @@ # which did not result in the switch of a time zone, as they stayed 9 hours # from the International Date Line. Rule Arg 1999 only - Oct Sun>=1 0:00 1:00 S -Rule Arg 2000 only - Mar Sun>=1 0:00 0 - +# From Paul Eggert (2007-12-28): +# DST was set to expire on March 5, not March 3, but since it was converted +# to standard time on March 3 it's more convenient for us to pretend that +# it ended on March 3. +Rule Arg 2000 only - Mar 3 0:00 0 - # # From Peter Gradelski via Steffen Thorsen (2000-03-01): # We just checked with our Sao Paulo office and they say the government of @@ -162,6 +166,30 @@ # This kind of things had always been done this way in Argentina. # We are still -03:00 all year round in all of the country. # +# From Steffen Thorsen (2007-12-21): +# A user (Leonardo Chaim) reported that Argentina will adopt DST.... +# all of the country (all Zone-entries) are affected. News reports like +# http://www.lanacion.com.ar/opinion/nota.asp?nota_id=973037 indicate +# that Argentina will use DST next year as well, from October to +# March, although exact rules are not given. +# +# From Jesper Norgaard Welen (2007-12-26) +# The last hurdle of Argentina DST is over, the proposal was approved in +# the lower chamber too (Deputados) with a vote 192 for and 2 against. +# By the way thanks to Mariano Absatz and Daniel Mario Vega for the link to +# the original scanned proposal, where the dates and the zero hours are +# clear and unambiguous...This is the article about final approval: +# +# http://www.lanacion.com.ar/politica/nota.asp?nota_id=973996 +# +# +# From Paul Eggert (2007-12-22): +# For dates after mid-2008, the following rules are my guesses and +# are quite possibly wrong, but are more likely than no DST at all. +Rule Arg 2007 only - Dec 30 0:00 1:00 S +Rule Arg 2008 max - Mar Sun>=15 0:00 0 - +Rule Arg 2008 max - Oct Sun>=1 0:00 1:00 S + # From Mariano Absatz (2004-05-21): # Today it was officially published that the Province of Mendoza is changing # its timezone this winter... starting tomorrow night.... @@ -222,10 +250,80 @@ # http://www.sanjuan.gov.ar/prensa/archivo/000426.html # http://www.sanjuan.gov.ar/prensa/archivo/000441.html +# From Alex Krivenyshev (2008-01-17): +# Here are articles that Argentina Province San Luis is planning to end DST +# as earlier as upcoming Monday January 21, 2008 or February 2008: +# +# Provincia argentina retrasa reloj y marca diferencia con resto del pais +# (Argentine Province delayed clock and mark difference with the rest of the +# country) +# +# http://cl.invertia.com/noticias/noticia.aspx?idNoticia=200801171849_EFE_ET4373&idtel +# +# +# Es inminente que en San Luis atrasen una hora los relojes +# (It is imminent in San Luis clocks one hour delay) +# +# http://www.lagaceta.com.ar/vernotae.asp?id_nota=253414 +# +# +# +# http://www.worldtimezone.net/dst_news/dst_news_argentina02.html +# + +# From Jesper Norgaard Welen (2008-01-18): +# The page of the San Luis provincial government +# +# http://www.sanluis.gov.ar/notas.asp?idCanal=0&id=22812 +# +# confirms what Alex Krivenyshev has earlier sent to the tz +# emailing list about that San Luis plans to return to standard +# time much earlier than the rest of the country. It also +# confirms that upon request the provinces San Juan and Mendoza +# refused to follow San Luis in this change. +# +# The change is supposed to take place Monday the 21.st at 0:00 +# hours. As far as I understand it if this goes ahead, we need +# a new timezone for San Luis (although there are also documented +# independent changes in the southamerica file of San Luis in +# 1990 and 1991 which has not been confirmed). + +# From Jesper Norgaard Welen (2008-01-25): +# Unfortunately the below page has become defunct, about the San Luis +# time change. Perhaps because it now is part of a group of pages "Most +# important pages of 2008." +# +# You can use +# +# http://www.sanluis.gov.ar/notas.asp?idCanal=8141&id=22834 +# +# instead it seems. Or use "Buscador" from the main page of the San Luis +# government, and fill in "huso" and click OK, and you will get 3 pages +# from which the first one is identical to the above. + +# From Mariano Absatz (2008-01-28): +# I can confirm that the Province of San Luis (and so far only that +# province) decided to go back to UTC-3 effective midnight Jan 20th 2008 +# (that is, Monday 21st at 0:00 is the time the clocks were delayed back +# 1 hour), and they intend to keep UTC-3 as their timezone all year round +# (that is, unless they change their mind any minute now). +# +# So we'll have to add yet another city to 'southamerica' (I think San +# Luis city is the mos populated city in the Province, so it'd be +# America/Argentina/San_Luis... of course I can't remember if San Luis's +# history of particular changes goes along with Mendoza or San Juan :-( +# (I only remember not being able to collect hard facts about San Luis +# back in 2004, when these provinces changed to UTC-4 for a few days, I +# mailed them personally and never got an answer). + +# From Paul Eggert (2008-06-30): # Unless otherwise specified, data are from Shanks & Pottenger through 1992, # from the IATA otherwise. As noted below, Shanks & Pottenger say that -# America/Cordoba split into 6 subregions during 1991/1992, but we -# haven't verified this yet so for now we'll keep it a single region. +# America/Cordoba split into 6 subregions during 1991/1992, one of which +# was America/San_Luis, but we haven't verified this yet so for now we'll +# keep America/Cordoba a single region rather than splitting it into the +# other 5 subregions. + # # Zone NAME GMTOFF RULES FORMAT [UNTIL] # @@ -236,18 +334,16 @@ -4:00 Arg AR%sT 1969 Oct 5 -3:00 Arg AR%sT 1999 Oct 3 -4:00 Arg AR%sT 2000 Mar 3 - -3:00 - ART + -3:00 Arg AR%sT # # Santa Fe (SF), Entre Rios (ER), Corrientes (CN), Misiones (MN), Chaco (CC), # Formosa (FM), Salta (SA), Santiago del Estero (SE), Cordoba (CB), -# San Luis (SL), La Pampa (LP), Neuquen (NQ), Rio Negro (RN) +# La Pampa (LP), Neuquen (NQ), Rio Negro (RN) # # Shanks & Pottenger also make the following claims, which we haven't verified: # - Formosa switched to -3:00 on 1991-01-07. # - Misiones switched to -3:00 on 1990-12-29. # - Chaco switched to -3:00 on 1991-01-04. -# - San Luis switched to -4:00 on 1990-03-14, then to -3:00 on 1990-10-15, -# then to -4:00 on 1991-03-01, then to -3:00 on 1991-06-01. # - Santiago del Estero switched to -4:00 on 1991-04-01, # then to -3:00 on 1991-04-26. # @@ -259,7 +355,7 @@ -4:00 - WART 1991 Oct 20 -3:00 Arg AR%sT 1999 Oct 3 -4:00 Arg AR%sT 2000 Mar 3 - -3:00 - ART + -3:00 Arg AR%sT # # Tucuman (TM) Zone America/Argentina/Tucuman -4:20:52 - LMT 1894 Oct 31 @@ -272,7 +368,7 @@ -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 Jun 1 -4:00 - WART 2004 Jun 13 - -3:00 - ART + -3:00 Arg AR%sT # # La Rioja (LR) Zone America/Argentina/La_Rioja -4:27:24 - LMT 1894 Oct 31 @@ -285,7 +381,7 @@ -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 Jun 1 -4:00 - WART 2004 Jun 20 - -3:00 - ART + -3:00 Arg AR%sT # # San Juan (SJ) Zone America/Argentina/San_Juan -4:34:04 - LMT 1894 Oct 31 @@ -298,7 +394,7 @@ -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 May 31 -4:00 - WART 2004 Jul 25 - -3:00 - ART + -3:00 Arg AR%sT # # Jujuy (JY) Zone America/Argentina/Jujuy -4:21:12 - LMT 1894 Oct 31 @@ -312,7 +408,7 @@ -3:00 1:00 ARST 1992 -3:00 Arg AR%sT 1999 Oct 3 -4:00 Arg AR%sT 2000 Mar 3 - -3:00 - ART + -3:00 Arg AR%sT # # Catamarca (CT), Chubut (CH) Zone America/Argentina/Catamarca -4:23:08 - LMT 1894 Oct 31 @@ -325,7 +421,7 @@ -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 Jun 1 -4:00 - WART 2004 Jun 20 - -3:00 - ART + -3:00 Arg AR%sT # # Mendoza (MZ) Zone America/Argentina/Mendoza -4:35:16 - LMT 1894 Oct 31 @@ -342,6 +438,23 @@ -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 May 23 -4:00 - WART 2004 Sep 26 + -3:00 Arg AR%sT +# +# San Luis (SL) +Zone America/Argentina/San_Luis -4:25:24 - LMT 1894 Oct 31 + -4:16:48 - CMT 1920 May + -4:00 - ART 1930 Dec + -4:00 Arg AR%sT 1969 Oct 5 + -3:00 Arg AR%sT 1990 + -3:00 1:00 ARST 1990 Mar 14 + -4:00 - WART 1990 Oct 15 + -4:00 1:00 WARST 1991 Mar 1 + -4:00 - WART 1991 Jun 1 + -3:00 - ART 1999 Oct 3 + -4:00 1:00 WARST 2000 Mar 3 + -3:00 - ART 2004 May 31 + -4:00 - WART 2004 Jul 25 + -3:00 Arg AR%sT 2008 Jan 21 -3:00 - ART # # Santa Cruz (SC) @@ -353,7 +466,7 @@ -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 Jun 1 -4:00 - WART 2004 Jun 20 - -3:00 - ART + -3:00 Arg AR%sT # # Tierra del Fuego, Antartida e Islas del Atlantico Sur (TF) Zone America/Argentina/Ushuaia -4:33:12 - LMT 1894 Oct 31 @@ -364,7 +477,7 @@ -4:00 Arg AR%sT 2000 Mar 3 -3:00 - ART 2004 May 30 -4:00 - WART 2004 Jun 20 - -3:00 - ART + -3:00 Arg AR%sT # Aruba # Zone NAME GMTOFF RULES FORMAT [UNTIL] @@ -450,6 +563,50 @@ # Brazil will start DST on 2007-10-14 00:00 and end on 2008-02-17 00:00: # http://www.mme.gov.br/site/news/detail.do;jsessionid=BBA06811AFCAAC28F0285210913513DA?newsId=13975 +# From Paul Schulze (2008-06-24): +# ...by law number 11.662 of April 24, 2008 (published in the "Diario +# Oficial da Uniao"...) in Brazil there are changes in the timezones, +# effective today (00:00am at June 24, 2008) as follows: +# +# a) The timezone UTC+5 is e[x]tinguished, with all the Acre state and the +# part of the Amazonas state that had this timezone now being put to the +# timezone UTC+4 +# b) The whole Para state now is put at timezone UTC+3, instead of just +# part of it, as was before. +# +# This change follows a proposal of senator Tiao Viana of Acre state, that +# proposed it due to concerns about open television channels displaying +# programs inappropriate to youths in the states that had the timezone +# UTC+5 too early in the night. In the occasion, some more corrections +# were proposed, trying to unify the timezones of any given state. This +# change modifies timezone rules defined in decree 2.784 of 18 June, +# 1913. + +# From Rodrigo Severo (2008-06-24): +# Just correcting the URL: +# +# https://www.in.gov.br/imprensa/visualiza/index.jsp?jornal=3Ddo&secao=3D1&pagina=3D1&data=3D25/04/2008 +# +# +# As a result of the above Decree I believe the America/Rio_Branco +# timezone shall be modified from UTC-5 to UTC-4 and a new timezone shall +# be created to represent the the west side of the Para State. I +# suggest this new timezone be called Santarem as the most +# important/populated city in the affected area. +# +# This new timezone would be the same as the Rio_Branco timezone up to +# the 2008/06/24 change which would be to UTC-3 instead of UTC-4. + +# From Alex Krivenyshev (2008-06-24): +# This is a quick reference page for New and Old Brazil Time Zones map. +# +# http://www.worldtimezone.com/brazil-time-new-old.php +# +# +# - 4 time zones replaced by 3 time zones-eliminating time zone UTC- 05 +# (state Acre and the part of the Amazonas will be UTC/GMT- 04) - western +# part of Par state is moving to one timezone UTC- 03 (from UTC -04). + # From Paul Eggert (2002-10-10): # The official decrees referenced below are mostly taken from # @@ -572,13 +729,13 @@ Rule Brazil 2000 2001 - Oct Sun>=8 0:00 1:00 S Rule Brazil 2001 2006 - Feb Sun>=15 0:00 0 - # Decree 4,399 (2002-10-01) repeals DST in AL, CE, MA, PB, PE, PI, RN, SE. -# +# 4,399 Rule Brazil 2002 only - Nov 3 0:00 1:00 S # Decree 4,844 (2003-09-24; corrected 2003-09-26) repeals DST in BA, MT, TO. -# +# 4,844 Rule Brazil 2003 only - Oct 19 0:00 1:00 S # Decree 5,223 (2004-10-01) reestablishes DST in MT. -# +# 5,223 Rule Brazil 2004 only - Nov 2 0:00 1:00 S # Decree 5,539 (2005-09-19), # adopted by the same states as before. @@ -587,9 +744,8 @@ # adopted by the same states as before. Rule Brazil 2006 only - Nov 5 0:00 1:00 S Rule Brazil 2007 only - Feb 25 0:00 0 - -# (Decree number not yet known) -# http://www.brasil.gov.br/noticias/ultimas_noticias/horario_verao070920/ -# (2007-09-20) after a heads-up from Steffen Thorsen: +# Decree 6,212 (2007-09-26), +# adopted by the same states as before. Rule Brazil 2007 max - Oct Sun>=8 0:00 1:00 S Rule Brazil 2008 max - Feb Sun>=15 0:00 0 - # The latest ruleset listed above says that the following states observe DST: @@ -597,7 +753,6 @@ # For dates after mid-2008, the above rules with TO="max" are guesses # and are quite possibly wrong, but are more likely than no DST at all. - # Zone NAME GMTOFF RULES FORMAT [UNTIL] # # Fernando de Noronha (administratively part of PE) @@ -623,6 +778,13 @@ -3:00 Brazil BR%sT 1988 Sep 12 -3:00 - BRT # +# west Para (PA) +# West Para includes Altamira, Oribidos, Prainha, Oriximina, and Santarem. +Zone America/Santarem -3:38:48 - LMT 1914 + -4:00 Brazil AM%sT 1988 Sep 12 + -4:00 - AMT 2008 Jun 24 00:00 + -3:00 - BRT +# # Maranhao (MA), Piaui (PI), Ceara (CE), Rio Grande do Norte (RN), # Paraiba (PB) Zone America/Fortaleza -2:34:00 - LMT 1914 @@ -685,8 +847,7 @@ -4:00 - AMT 2004 Oct 1 -4:00 Brazil AM%sT # -# west Para (PA), Rondonia (RO) -# West Para includes Altamira, Oribidos, Prainha, Oriximina, and Santarem. +# Rondonia (RO) Zone America/Porto_Velho -4:15:36 - LMT 1914 -4:00 Brazil AM%sT 1988 Sep 12 -4:00 - AMT @@ -713,13 +874,14 @@ -5:00 Brazil AC%sT 1988 Sep 12 -5:00 - ACT 1993 Sep 28 -5:00 Brazil AC%sT 1994 Sep 22 - -5:00 - ACT + -5:00 - ACT 2008 Jun 24 00:00 + -4:00 - AMT # # Acre (AC) Zone America/Rio_Branco -4:31:12 - LMT 1914 -5:00 Brazil AC%sT 1988 Sep 12 - -5:00 - ACT - + -5:00 - ACT 2008 Jun 24 00:00 + -4:00 - AMT # Chile @@ -753,6 +915,26 @@ # America/Santiago. The pre-1980 Pacific/Easter data are dubious, # but we have no other source. +# From German Poo-Caaman~o (2008-03-03): +# Due to drought, Chile extends Daylight Time in three weeks. This +# is one-time change (Saturday 3/29 at 24:00 for America/Santiago +# and Saturday 3/29 at 22:00 for Pacific/Easter) +# The Supreme Decree is located at +# +# http://www.shoa.cl/servicios/supremo316.pdf +# +# and the instructions for 2008 are located in: +# +# http://www.horaoficial.cl/cambio.htm +# . + +# From Jose Miguel Garrido (2008-03-05): +# ... +# You could see the announces of the change on +# +# http://www.shoa.cl/noticias/2008/04hora/hora.htm +# . + # 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 - @@ -783,7 +965,11 @@ 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 2000 max - Mar Sun>=9 3:00u 0 - +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 max - Mar Sun>=9 3:00u 0 - # IATA SSIM anomalies: (1992-02) says 1992-03-14; # (1996-09) says 1998-03-08. Ignore these. # Zone NAME GMTOFF RULES FORMAT [UNTIL] @@ -1129,19 +1315,17 @@ # Venezuela # -# From Kiraz Janicke (2007-09-25), in -# http://www.venezuelanalysis.com/analysis/2645: -# The proposal ... involves turning the clock back half an hour from -# +4.00 Greenwich Mean Time (GMT), to +4.30GMT, the time zone -# Venezuela had until December 31, 1964, when the current time zone -# was adopted. The change was due to take place on September 17 and -# then on September 24, but has since been postponed until December -# 31, to allow for compliance with international organizations, such -# as the International Office of Weights and Measures. +# From John Stainforth (2007-11-28): +# ... the change for Venezuela originally expected for 2007-12-31 has +# been brought forward to 2007-12-09. The official announcement was +# published today in the "Gaceta Oficial de la Republica Bolivariana +# de Venezuela, numero 38.819" (official document for all laws or +# resolution publication) +# http://www.globovision.com/news.php?nid=72208 # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone America/Caracas -4:27:44 - LMT 1890 -4:27:40 - CMT 1912 Feb 12 # Caracas Mean Time? -4:30 - VET 1965 # Venezuela Time - -4:00 - VET 2008 + -4:00 - VET 2007 Dec 9 03:00 -4:30 - VET diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/javazic/tzdata/zone.tab --- a/jdk/make/sun/javazic/tzdata/zone.tab Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/javazic/tzdata/zone.tab Wed Jul 05 16:42:37 2017 +0200 @@ -64,7 +64,8 @@ AQ -6640+14001 Antarctica/DumontDUrville Dumont-d'Urville Station, Terre Adelie AQ -690022+0393524 Antarctica/Syowa Syowa Station, E Ongul I AR -3436-05827 America/Argentina/Buenos_Aires Buenos Aires (BA, CF) -AR -3124-06411 America/Argentina/Cordoba most locations (CB, CC, CN, ER, FM, LP, MN, NQ, RN, SA, SE, SF, SL) +AR -3124-06411 America/Argentina/Cordoba most locations (CB, CC, CN, ER, FM, LP, MN, NQ, RN, SA, SE, SF) +AR -3319-06621 America/Argentina/San_Luis San Luis (SL) AR -2411-06518 America/Argentina/Jujuy Jujuy (JY) AR -2649-06513 America/Argentina/Tucuman Tucuman (TM) AR -2828-06547 America/Argentina/Catamarca Catamarca (CT), Chubut (CH) @@ -99,6 +100,7 @@ BH +2623+05035 Asia/Bahrain BI -0323+02922 Africa/Bujumbura BJ +0629+00237 Africa/Porto-Novo +BL +1753-06251 America/St_Barthelemy BM +3217-06446 Atlantic/Bermuda BN +0456+11455 Asia/Brunei BO -1630-06809 America/La_Paz @@ -112,7 +114,8 @@ BR -2332-04637 America/Sao_Paulo S & SE Brazil (GO, DF, MG, ES, RJ, SP, PR, SC, RS) BR -2027-05437 America/Campo_Grande Mato Grosso do Sul BR -1535-05605 America/Cuiaba Mato Grosso -BR -0846-06354 America/Porto_Velho W Para, Rondonia +BR -0226-05452 America/Santarem W Para +BR -0846-06354 America/Porto_Velho Rondonia BR +0249-06040 America/Boa_Vista Roraima BR -0308-06001 America/Manaus E Amazonas BR -0640-06952 America/Eirunepe W Amazonas @@ -230,7 +233,7 @@ IE +5320-00615 Europe/Dublin IL +3146+03514 Asia/Jerusalem IM +5409-00428 Europe/Isle_of_Man -IN +2232+08822 Asia/Calcutta +IN +2232+08822 Asia/Kolkata IO -0720+07225 Indian/Chagos IQ +3321+04425 Asia/Baghdad IR +3540+05126 Asia/Tehran @@ -272,6 +275,7 @@ MC +4342+00723 Europe/Monaco MD +4700+02850 Europe/Chisinau ME +4226+01916 Europe/Podgorica +MF +1804-06305 America/Marigot MG -1855+04731 Indian/Antananarivo MH +0709+17112 Pacific/Majuro most locations MH +0905+16720 Pacific/Kwajalein Kwajalein @@ -361,8 +365,7 @@ SG +0117+10351 Asia/Singapore SH -1555-00542 Atlantic/St_Helena SI +4603+01431 Europe/Ljubljana -SJ +7800+01600 Arctic/Longyearbyen Svalbard -SJ +7059-00805 Atlantic/Jan_Mayen Jan Mayen +SJ +7800+01600 Arctic/Longyearbyen SK +4809+01707 Europe/Bratislava SL +0830-01315 Africa/Freetown SM +4355+01228 Europe/San_Marino @@ -432,7 +435,7 @@ VE +1030-06656 America/Caracas VG +1827-06437 America/Tortola VI +1821-06456 America/St_Thomas -VN +1045+10640 Asia/Saigon +VN +1045+10640 Asia/Ho_Chi_Minh VU -1740+16825 Pacific/Efate WF -1318-17610 Pacific/Wallis WS -1350-17144 Pacific/Apia diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/net/spi/Makefile --- a/jdk/make/sun/net/spi/Makefile Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/net/spi/Makefile Wed Jul 05 16:42:37 2017 +0200 @@ -23,10 +23,6 @@ # have any questions. # -# -# Makefile for building com/sun -# - BUILDDIR = ../../.. include $(BUILDDIR)/common/Defs.gmk diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/net/spi/nameservice/Makefile --- a/jdk/make/sun/net/spi/nameservice/Makefile Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/net/spi/nameservice/Makefile Wed Jul 05 16:42:37 2017 +0200 @@ -23,10 +23,6 @@ # have any questions. # -# -# Makefile for building com/sun -# - BUILDDIR = ../../../.. include $(BUILDDIR)/common/Defs.gmk diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/sun/net/spi/nameservice/dns/Makefile --- a/jdk/make/sun/net/spi/nameservice/dns/Makefile Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/sun/net/spi/nameservice/dns/Makefile Wed Jul 05 16:42:37 2017 +0200 @@ -24,7 +24,7 @@ # # -# Makefile for building JNDI service provider toolkit +# Makefile for building JNDI DNS name service provider # BUILDDIR = ../../../../.. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/tools/Makefile --- a/jdk/make/tools/Makefile Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/make/tools/Makefile Wed Jul 05 16:42:37 2017 +0200 @@ -32,7 +32,6 @@ SUBDIRS = \ addjsum \ - auto_multi \ buildmetaindex \ commentchecker \ compile_font_config \ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/tools/auto_multi/Makefile --- a/jdk/make/tools/auto_multi/Makefile Fri Oct 10 13:29:11 2008 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,43 +0,0 @@ -# -# Copyright 1998-2005 Sun Microsystems, Inc. All Rights Reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. Sun designates this -# particular file as subject to the "Classpath" exception as provided -# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, -# CA 95054 USA or visit www.sun.com if you need additional information or -# have any questions. -# - -# -# Makefile for building the automulti tool -# - -BUILDDIR = ../.. -PACKAGE = build.tools.automulti -PRODUCT = tools -PROGRAM = automulti -include $(BUILDDIR)/common/Defs.gmk - -BUILDTOOL_SOURCE_ROOT = $(BUILDDIR)/tools/src -BUILDTOOL_MAIN = $(PKGDIR)/AutoMulti.java - -# -# Build tool jar rules. -# -include $(BUILDDIR)/common/BuildToolJar.gmk - diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/tools/src/build/tools/automulti/AutoMulti.java --- a/jdk/make/tools/src/build/tools/automulti/AutoMulti.java Fri Oct 10 13:29:11 2008 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,458 +0,0 @@ -/* - * Copyright 1998-2001 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package build.tools.automulti; - -import java.lang.reflect.*; -import java.util.*; -import java.io.*; - -/** - * Automatically generates the Multiplexing UI classes - * for Swing. - *

- * To use, type 'java AutoMulti ' where - * is the directory containing the source for Swing's UI classes and - * is the package prefix to use before ".swing.plaf.multi". - * For example: - * - *

- * cd TEST
- * ../../../../build/solaris-sparc/bin/java AutoMulti ../../../../src/share/classes/javax/swing/plaf javax
- * 
- * - * AutoMulti will scour the plaf directory for *UI.java files and - * generate Multi*UI.java files that do the multiplexing thing. - *

- * NOTE: This tool depends upon the existence of and on the - * compiled classes from being somewhere in the class path. - * - * @author Willie Walker - */ -public class AutoMulti { - static String importLines; - - /** - * A silly list of parameter names to use. Skips "i" because we use - * it as a 'for' loop counter. If you want to get fancy, please feel - * to change how parameter names are obtained. This will break if - * someone decides to create a UI method that takes more than 8 - * parameters. Which one is a bug (this breaking or having a method - * with more than eight parameters) is a subjective thing. - */ - public static String[] paramNames = {"a","b","c","d","e","f","g","h"}; - - /** - * Removes the package names (e.g., javax.swing) from the name. - */ - public static String unqualifyName(String name) { - StringTokenizer parser = new StringTokenizer(name,"."); - String unqualifiedName = null; - while (parser.hasMoreTokens()) { - unqualifiedName = parser.nextToken(); - } - return removeDollars(unqualifiedName); - } - - /** - * Strips the extension from the filename. - */ - public static String stripExtension(String name) { - StringTokenizer parser = new StringTokenizer(name,"."); - return parser.nextToken(); - } - - /** - * Adds some spaces. - */ - public static void indent(StringBuffer s, int i) { - while (i > 0) { - s.append(" "); - i--; - } - } - - /** - * Spits out all the beginning stuff. - */ - public static StringBuffer createPreamble(String prefixName) { - StringBuffer s = new StringBuffer(); - s.append("/*\n"); - s.append(" *\n"); - s.append(" * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved.\n"); - s.append(" * \n"); - s.append(" * This software is the proprietary information of Sun Microsystems, Inc. \n"); - s.append(" * Use is subject to license terms.\n"); - s.append(" * \n"); - s.append(" */\n"); - s.append("package " + prefixName + ".swing.plaf.multi;\n"); - s.append("\n"); - return s; - } - - /** - * Replaces 'Xxx$Yyy' with "Xxx'. Used by addImport because you - * can't import nested classes directly. - */ - public static String removeNestedClassName(String s) { - int dollarPosition = s.indexOf('$'); - - if (dollarPosition >= 0) { // s contains '$' - StringBuffer sb = new StringBuffer(s); - sb.setLength(dollarPosition); - return sb.toString(); - } else { // no '$' - return s; - } - } - - /** - * Replaces '$' with ".'. Needed for printing inner class names - * for argument and return types. - */ - public static String removeDollars(String s) { - int dollarPosition = s.indexOf('$'); - - if (dollarPosition >= 0) { // s contains '$' - StringBuffer sb = new StringBuffer(s); - while (dollarPosition >= 0) { - //XXX: will there ever be more than one '$'? - sb.replace(dollarPosition, dollarPosition+1, "."); - dollarPosition = sb.indexOf("$", dollarPosition); - } - return sb.toString(); - } else { // no $ - return s; - } - } - - /** - * Adds an import line to the String. - */ - public static void addImport(String s, Class theClass) { - if (!theClass.isPrimitive() && (theClass != Object.class)) { - String className = removeNestedClassName(theClass.getName()); - String importLine = new String("import " + className + ";\n"); - if (importLines.indexOf(importLine) == -1) { - importLines += importLine; - } - } - } - - /** - * Spits out the class header information. - */ - public static void addHeader(StringBuffer s, String className) { - s.append("/**\n"); - s.append(" * A multiplexing UI used to combine " + className + "s.\n"); - s.append(" * \n"); - s.append(" *

This file was automatically generated by AutoMulti.\n"); - s.append(" *\n"); - s.append(" * @author Otto Multey\n"); // Get it? I crack myself up. - s.append(" */\n"); - s.append("public class Multi" + className + " extends " + className + " {\n"); - s.append("\n"); - s.append(" /**\n"); - s.append(" * The vector containing the real UIs. This is populated \n"); - s.append(" * in the call to createUI, and can be obtained by calling\n"); - s.append(" * the getUIs method. The first element is guaranteed to be the real UI \n"); - s.append(" * obtained from the default look and feel.\n"); - s.append(" */\n"); - s.append(" protected Vector uis = new Vector();\n"); - s.append("\n"); - s.append("////////////////////\n"); - s.append("// Common UI methods\n"); - s.append("////////////////////\n"); - s.append("\n"); - s.append(" /**\n"); - s.append(" * Returns the list of UIs associated with this multiplexing UI. This \n"); - s.append(" * allows processing of the UIs by an application aware of multiplexing \n"); - s.append(" * UIs on components.\n"); - s.append(" */\n"); - s.append(" public ComponentUI[] getUIs() {\n"); - s.append(" return MultiLookAndFeel.uisToArray(uis);\n"); - s.append(" }\n"); - } - - /** - * Prints out the code for a method. This is pretty specific to the - * Multiplexing UI code, so don't get any fancy ideas. - */ - public static void addMethod(StringBuffer s, Method m, String origName, String className) { - - // Get the method name and the return type. Be a little careful about arrays. - // - String methodName = unqualifyName(m.getName()); - String returnType; - if (!m.getReturnType().isArray()) { - returnType = unqualifyName(m.getReturnType().toString()); - addImport(importLines,m.getReturnType()); - } else { - returnType = unqualifyName(m.getReturnType().getComponentType().toString()) - + "[]"; - addImport(importLines,m.getReturnType().getComponentType()); - } - - // Print the javadoc - // - s.append("\n"); - if (methodName.equals("createUI")) { - s.append(" /**\n"); - s.append(" * Returns a multiplexing UI instance if any of the auxiliary\n"); - s.append(" * LookAndFeels supports this UI. Otherwise, just returns the \n"); - s.append(" * UI object obtained from the default LookAndFeel.\n"); - s.append(" */\n"); - } else if (!returnType.equals("void")) { - s.append(" /**\n"); - s.append(" * Invokes the " + methodName + " method on each UI handled by this object.\n"); - s.append(" * \n"); - s.append(" * @return the value obtained from the first UI, which is\n"); - s.append(" * the UI obtained from the default LookAndFeel\n"); - s.append(" */\n"); - } else { - s.append(" /**\n"); - s.append(" * Invokes the " + methodName - + " method on each UI handled by this object.\n"); - s.append(" */\n"); - } - - // Print the method signature - // - s.append(" public"); - if (Modifier.isStatic(m.getModifiers())) { - s.append(" static"); - } - s.append(" " + returnType); - s.append(" " + methodName); - s.append("("); - - Class[] params = m.getParameterTypes(); - Class temp; - String braces; - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(", "); - } - temp = params[i]; - braces = new String(""); - while (temp.isArray()) { - braces += "[]"; - temp = temp.getComponentType(); - } - s.append(unqualifyName(temp.getName()) + braces + " " + paramNames[i]); - addImport(importLines,temp); - } - s.append(")"); - - // Don't forget about exceptions - // - Class exceptions[] = m.getExceptionTypes(); - String throwsString = new String(""); - - if (exceptions.length > 0) { - s.append("\n"); - indent(s,12); - s.append("throws "); - for (int i = 0; i < exceptions.length; i++) { - if (i > 0) { - s.append(", "); - } - s.append(unqualifyName(exceptions[i].getName())); - addImport(importLines,exceptions[i]); - } - } - s.append(throwsString + " {\n"); - - // Now print out the contents of the method. We do a special thing - // for the createUI method, another thing if the method returns 'void' - // and a third thing if we don't do either of the first two. If - // you want to squash this down, feel free. - // - if (methodName.equals("createUI")) { - indent(s,8); - s.append("ComponentUI mui = new Multi" + origName + "();\n"); - indent(s,8); - s.append("return MultiLookAndFeel.createUIs(mui,\n"); - indent(s,42); - s.append("((Multi" + origName +") mui).uis,\n"); - indent(s,42); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(","); - } - s.append(paramNames[i]); - } - s.append(");\n"); - } else if (!returnType.equals("void")) { - indent(s,8); - s.append(returnType + " returnValue = \n"); - indent(s,12); - s.append("((" + className + ") (uis.elementAt(0)))." - + methodName + "("); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(","); - } - s.append(paramNames[i]); - } - s.append(");\n"); - indent(s,8); - s.append("for (int i = 1; i < uis.size(); i++) {\n"); - indent(s,12); - s.append("((" + className + ") (uis.elementAt(i)))." - + methodName + "("); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(","); - } - s.append(paramNames[i]); - } - s.append(");\n"); - indent(s,8); - s.append("}\n"); - indent(s,8); - s.append("return returnValue;\n"); - } else { - indent(s,8); - s.append("for (int i = 0; i < uis.size(); i++) {\n"); - indent(s,12); - s.append("((" + className + ") (uis.elementAt(i)))." - + methodName + "("); - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(","); - } - s.append(paramNames[i]); - } - s.append(");\n"); - indent(s,8); - s.append("}\n"); - } - indent(s,4); - s.append("}\n"); - } - - /** - * Takes a plaf class name (e.g., "MenuUI") and generates the corresponding - * Multiplexing UI Java source code (e.g., "MultiMenuUI.java"). - */ - public static void generateFile(String prefixName, String className) { - try { - FileOutputStream fos; - PrintWriter outFile; - - importLines = new String(); - importLines += new String("import java.util.Vector;\n"); - - StringBuffer body = new StringBuffer(); - Class wee = Class.forName(prefixName + ".swing.plaf." + className); - String weeName = unqualifyName(wee.getName()); - addImport(importLines,wee); - while (!weeName.equals("Object")) { - body.append("\n"); - body.append("////////////////////\n"); - body.append("// " + weeName + " methods\n"); - body.append("////////////////////\n"); - Method[] methods = wee.getDeclaredMethods(); - for (int i=0; i < methods.length; i++) { - if (Modifier.isPublic(methods[i].getModifiers())) { - addMethod(body,methods[i],className,weeName); - } - } - wee = wee.getSuperclass(); - weeName = unqualifyName(wee.getName()); - addImport(importLines,wee); - } - - fos = new FileOutputStream("Multi" + className + ".java"); - outFile = new PrintWriter(fos); - StringBuffer outText = createPreamble(prefixName); - outText.append(importLines.toString() + "\n"); - addHeader(outText,className); - outText.append(body.toString()); - outText.append("}\n"); - outFile.write(outText.toString()); - outFile.flush(); - outFile.close(); - } catch (Exception e) { - System.err.println(e); - } - } - - /** - * D'Oh! Something bad happened. - */ - public static void usage(String s) throws IOException { - System.err.println("Usage: AutoMulti [com.sun]"); - throw new IllegalArgumentException(s); - } - - /** - * Takes the plaf directory name and generates the multiplexing UI - * source code. - */ - public static void main(String[] args) throws IOException { - - if (args.length < 1) { - usage(""); - } - - String dirName = args[0]; - File dir = new File(dirName); - if (!dir.isDirectory()) { - System.err.println("No such directory: " + dirName); - usage(""); - } - - String prefixName; - if (args.length > 1) { - prefixName = args[1]; - } else { - prefixName = "com.sun.java"; - } - - String plafUIs[] = dir.list(new UIJavaFilter()); - for (int i = 0; i < plafUIs.length; i++) { - generateFile(prefixName,stripExtension(plafUIs[i])); - } - } -} - -/** - * Only accepts file names of the form *UI.java. The one exception - * is not accepting ComponentUI.java because we don't need to generate - * a multiplexing class for it. - */ -class UIJavaFilter implements FilenameFilter { - public boolean accept(File dir, String name) { - if (name.equals("ComponentUI.java")) { - return false; - } else if (name.endsWith("UI.java")) { - return true; - } else { - return false; - } - } -} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/tools/src/build/tools/automulti/README.txt --- a/jdk/make/tools/src/build/tools/automulti/README.txt Fri Oct 10 13:29:11 2008 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,36 +0,0 @@ -AutoMulti is the tool that automatically generates the -Multi*UI classes for the Multiplexing look and feel. -Instructions for using it are in AutoMulti.java. - -TestALFGenerator is a tool (a variation of AutoMulti) -that automatically generates an auxiliary look and -feel that you can use to test the Multiplexing look -and feel. The TestALF look and feel implements every -method by printing the message "In the xxx method of -the TextALFYyyUI class." and, except in the case of -createUI, returning something meaningless (since, -except in the case of createUI, the return value is -ignored). - -TestALFLookAndFeel.java is the only non-auto-generated -file for the TestALF L&F. If you specify a package -argument to TestALFGenerator, you'll have to change -the code in TestALFLookAndFeel.java to reflect the -package name. - -To test any application with the TestALF, make sure the -compiled TestALF classes are in the class path. Then add -this to the /lib/swing.properties file (which -you'll probably have to create): - -swing.auxiliarylaf=TestALFLookAndFeel - -E.g., if you're running SwingSet2 against your solaris -build, then you'd create/edit the swing.properties file -in /build/solaris-sparc/lib. - -Then run any app. You'll see lots of thrilling "In the -Xxxx method of the Yyy class" messages. If you get anything -else (especially an exception), then you've found a bug. -Probably in the default look and feel. - diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/tools/src/build/tools/automulti/TestALFGenerator.java --- a/jdk/make/tools/src/build/tools/automulti/TestALFGenerator.java Fri Oct 10 13:29:11 2008 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,401 +0,0 @@ -/* - * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package build.tools.automulti; - -import java.lang.reflect.*; -import java.util.*; -import java.io.*; - -/** - * Automatically generates an auxiliary look and feel to be - * used for testing the Multiplexing look and feel. - *

- * To use, type 'java TestALFGenerator []' where - * is the directory containing the source for Swing's UI classes. - * is an optional argument that specifies the package - * of the TestALF classes. If it's omitted, the classes are in - * the default package. - * For example: - * - *

- * ../../../../build/solaris-sparc/bin/java TestALFGenerator ../../../../src/share/classes/javax/swing/plaf com.myco.myalaf
- * 
- * - * TestALFGenerator will scour the plaf directory for *UI.java files and - * generate TestALF*UI.java files. - *

- * NOTE: This tool depends upon the existence of and on the - * compiled classes from being somewhere in the class path. - * - * @author Willie Walker - */ -public class TestALFGenerator { - static String importLines; - static String packageName; - static String classPrefix = "TestALF"; - - /** - * A silly list of parameter names to use. Skips "i" because we use - * it as a 'for' loop counter. If you want to get fancy, please feel - * to change how parameter names are obtained. This will break if - * someone decides to create a UI method that takes more than 8 - * parameters. Which one is a bug (this breaking or having a method - * with more than eight parameters) is a subjective thing. - */ - public static String[] paramNames = {"a","b","c","d","e","f","g","h"}; - - /** - * Removes the package names (e.g., javax.swing) from the name. - */ - public static String unqualifyName(String name) { - StringTokenizer parser = new StringTokenizer(name,"."); - String unqualifiedName = null; - while (parser.hasMoreTokens()) { - unqualifiedName = parser.nextToken(); - } - return removeDollars(unqualifiedName); - } - - /** - * Strips the extension from the filename. - */ - public static String stripExtension(String name) { - StringTokenizer parser = new StringTokenizer(name,"."); - return parser.nextToken(); - } - - /** - * Adds some spaces. - */ - public static void indent(StringBuffer s, int i) { - while (i > 0) { - s.append(" "); - i--; - } - } - - /** - * Spits out all the beginning stuff. - */ - public static StringBuffer createPreamble(String prefixName) { - StringBuffer s = new StringBuffer(); - s.append("/*\n"); - s.append(" *\n"); - s.append(" * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved.\n"); - s.append(" * \n"); - s.append(" * This software is the proprietary information of Sun Microsystems, Inc. \n"); - s.append(" * Use is subject to license terms.\n"); - s.append(" * \n"); - s.append(" */\n"); - if (packageName != null) { - s.append("package " + packageName + ";\n"); - s.append("\n"); - } - return s; - } - - /** - * Replaces 'Xxx$Yyy' with "Xxx'. Used by addImport because you - * can't import nested classes directly. - */ - public static String removeNestedClassName(String s) { - int dollarPosition = s.indexOf('$'); - - if (dollarPosition >= 0) { // s contains '$' - StringBuffer sb = new StringBuffer(s); - sb.setLength(dollarPosition); - return sb.toString(); - } else { // no '$' - return s; - } - } - - /** - * Replaces '$' with ".'. Needed for printing inner class names - * for argument and return types. - */ - public static String removeDollars(String s) { - int dollarPosition = s.indexOf('$'); - - if (dollarPosition >= 0) { // s contains '$' - StringBuffer sb = new StringBuffer(s); - while (dollarPosition >= 0) { - //XXX: will there ever be more than one '$'? - sb.replace(dollarPosition, dollarPosition+1, "."); - dollarPosition = sb.indexOf("$", dollarPosition); - } - return sb.toString(); - } else { // no $ - return s; - } - } - - /** - * Adds an import line to the String. - */ - public static void addImport(String s, Class theClass) { - if (!theClass.isPrimitive() && (theClass != Object.class)) { - String className = removeNestedClassName(theClass.getName()); - String importLine = new String("import " + className + ";\n"); - if (importLines.indexOf(importLine) == -1) { - importLines += importLine; - } - } - } - - /** - * Spits out the class header information. - */ - public static void addHeader(StringBuffer s, String className) { - s.append("/**\n"); - s.append(" * An auxiliary UI for " + className + "s.\n"); - s.append(" * \n"); - s.append(" *

This file was automatically generated by TestALFGenerator.\n"); - s.append(" *\n"); - s.append(" * @author Otto Multey\n"); // Get it? I crack myself up. - s.append(" */\n"); - s.append("public class " + classPrefix + className + " extends " + className + " {\n"); - s.append("\n"); - } - - /** - * Prints out the code for a method. - */ - public static void addMethod(StringBuffer s, Method m, String origName, String className) { - - // Get the method name and the return type. Be a little careful about arrays. - // - String methodName = unqualifyName(m.getName()); - String returnType; - - if (!m.getReturnType().isArray()) { - returnType = unqualifyName(m.getReturnType().toString()); - addImport(importLines,m.getReturnType()); - } else { - returnType = unqualifyName(m.getReturnType().getComponentType().toString()) - + "[]"; - addImport(importLines,m.getReturnType().getComponentType()); - } - - // Print the javadoc - // - s.append("\n"); - - if (methodName.equals("createUI")) { - s.append(" /**\n"); - s.append(" * Returns a UI object for this component.\n"); - s.append(" */\n"); - } else { - s.append(" /**\n"); - s.append(" * Prints a message saying this method has been invoked.\n"); - s.append(" */\n"); - } - - // Print the method signature - // - s.append(" public"); - if (Modifier.isStatic(m.getModifiers())) { - s.append(" static"); - } - s.append(" " + returnType); - s.append(" " + methodName); - s.append("("); - - Class[] params = m.getParameterTypes(); - Class temp; - String braces; - for (int i = 0; i < params.length; i++) { - if (i > 0) { - s.append(", "); - } - temp = params[i]; - braces = new String(""); - while (temp.isArray()) { - braces += "[]"; - temp = temp.getComponentType(); - } - s.append(unqualifyName(temp.getName()) + braces + " " + paramNames[i]); - addImport(importLines,temp); - } - s.append(")"); - - // Don't forget about exceptions - // - Class exceptions[] = m.getExceptionTypes(); - String throwsString = new String(""); - - if (exceptions.length > 0) { - s.append("\n"); - indent(s,12); - s.append("throws "); - for (int i = 0; i < exceptions.length; i++) { - if (i > 0) { - s.append(", "); - } - s.append(unqualifyName(exceptions[i].getName())); - addImport(importLines,exceptions[i]); - } - } - s.append(throwsString + " {\n"); - - // Now print out the contents of the method. - indent(s,8); - s.append("System.out.println(\"In the " + methodName - + " method of the " - + classPrefix + origName + " class.\");\n"); - if (methodName.equals("createUI")) { - indent(s,8); - s.append("return ui;\n"); - } else { - // If we have to return something, do so. - if (!returnType.equals("void")) { - Class rType = m.getReturnType(); - indent(s,8); - if (!rType.isPrimitive()) { - s.append("return null;\n"); - } else if (rType == Boolean.TYPE) { - s.append("return false;\n"); - } else if (rType == Character.TYPE) { - s.append("return '0';\n"); - } else { // byte, short, int, long, float, or double - s.append("return 0;\n"); - } - } - } - - indent(s,4); - s.append("}\n"); - } - - /** - * Takes a plaf class name (e.g., "MenuUI") and generates the corresponding - * TestALF UI Java source code (e.g., "TestALFMenuUI.java"). - */ - public static void generateFile(String prefixName, String className) { - try { - FileOutputStream fos; - PrintWriter outFile; - - importLines = new String(); - importLines += new String("import java.util.Vector;\n"); - - StringBuffer body = new StringBuffer(); - Class wee = Class.forName(prefixName + ".swing.plaf." + className); - String weeName = unqualifyName(wee.getName()); - String thisClassName = classPrefix + className; - addImport(importLines,wee); - - // Declare and initialize the shared UI object. - body.append("\n"); - body.append("////////////////////\n"); - body.append("// Shared UI object\n"); - body.append("////////////////////\n"); - body.append("private final static " + thisClassName - + " ui = new " + thisClassName + "();\n"); - - while (!weeName.equals("Object")) { - body.append("\n"); - body.append("////////////////////\n"); - body.append("// " + weeName + " methods\n"); - body.append("////////////////////\n"); - Method[] methods = wee.getDeclaredMethods(); - for (int i=0; i < methods.length; i++) { - if (Modifier.isPublic(methods[i].getModifiers())) { - addMethod(body,methods[i],className,weeName); - } - } - wee = wee.getSuperclass(); - weeName = unqualifyName(wee.getName()); - addImport(importLines,wee); - } - - fos = new FileOutputStream(classPrefix + className + ".java"); - outFile = new PrintWriter(fos); - StringBuffer outText = createPreamble(prefixName); - outText.append(importLines.toString() + "\n"); - addHeader(outText,className); - outText.append(body.toString()); - outText.append("}\n"); - outFile.write(outText.toString()); - outFile.flush(); - outFile.close(); - } catch (Exception e) { - System.err.println(e); - } - } - - /** - * D'Oh! Something bad happened. - */ - public static void usage(String s) throws IOException { - System.err.println("Usage: java TestALFGenerator []"); - throw new IllegalArgumentException(s); - } - - /** - * Takes the plaf directory name and generates the TestALF UI - * source code. - */ - public static void main(String[] args) throws IOException { - - if (args.length < 1) { - usage(""); - } - - String dirName = args[0]; - File dir = new File(dirName); - if (!dir.isDirectory()) { - System.err.println("No such directory: " + dirName); - usage(""); - } - - if (args.length > 1) { - packageName = args[1]; - } - - String plafUIs[] = dir.list(new UIJavaFilter()); - for (int i = 0; i < plafUIs.length; i++) { - generateFile("javax",stripExtension(plafUIs[i])); - } - } -} - -/** - * Only accepts file names of the form *UI.java. The one exception - * is not accepting ComponentUI.java because we don't need to generate - * a TestALF class for it. - */ -class UIJavaFilter implements FilenameFilter { - public boolean accept(File dir, String name) { - if (name.equals("ComponentUI.java")) { - return false; - } else if (name.endsWith("UI.java")) { - return true; - } else { - return false; - } - } -} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/make/tools/src/build/tools/automulti/TestALFLookAndFeel.java --- a/jdk/make/tools/src/build/tools/automulti/TestALFLookAndFeel.java Fri Oct 10 13:29:11 2008 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,182 +0,0 @@ -/* - * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -//package com.myco.myalaf; //search for myalaf for other refs to package name - - -package build.tools.automulti; - -import java.util.Vector; -import java.lang.reflect.Method; -import javax.swing.*; -import javax.swing.plaf.*; - -/** - *

An auxiliary look and feel used for testing the Multiplexing - * look and feel. - *

- * - * @see UIManager#addAuxiliaryLookAndFeel - * @see javax.swing.plaf.multi - * - * @author Kathy Walrath - * @author Will Walker - */ -public class TestALFLookAndFeel extends LookAndFeel { - -////////////////////////////// -// LookAndFeel methods -////////////////////////////// - - /** - * Returns a string, suitable for use in menus, - * that identifies this look and feel. - * - * @return a string such as "Test Auxiliary Look and Feel" - */ - public String getName() { - return "Test Auxiliary Look and Feel"; - } - - /** - * Returns a string, suitable for use by applications/services, - * that identifies this look and feel. - * - * @return "TestALF" - */ - public String getID() { - return "TestALF"; - } - - /** - * Returns a one-line description of this look and feel. - * - * @return a descriptive string such as "Allows multiple UI instances per component instance" - */ - public String getDescription() { - return "Allows multiple UI instances per component instance"; - } - - /** - * Returns false; - * this look and feel is not native to any platform. - * - * @return false - */ - public boolean isNativeLookAndFeel() { - return false; - } - - /** - * Returns true; - * every platform permits this look and feel. - * - * @return true - */ - public boolean isSupportedLookAndFeel() { - return true; - } - - /** - * Creates, initializes, and returns - * the look and feel specific defaults. - * For this look and feel, - * the defaults consist solely of - * mappings of UI class IDs - * (such as "ButtonUI") - * to ComponentUI class names - * (such as "com.myco.myalaf.MultiButtonUI"). - * - * @return an initialized UIDefaults object - * @see javax.swing.JComponent#getUIClassID - */ - public UIDefaults getDefaults() { - System.out.println("In the TestALFLookAndFeel getDefaults method."); - UIDefaults table = new TestALFUIDefaults(); - //String prefix = "com.myco.myalaf.TestALF"; - String prefix = "TestALF"; - Object[] uiDefaults = { - "ButtonUI", prefix + "ButtonUI", - "CheckBoxMenuItemUI", prefix + "MenuItemUI", - "CheckBoxUI", prefix + "ButtonUI", - "ColorChooserUI", prefix + "ColorChooserUI", - "ComboBoxUI", prefix + "ComboBoxUI", - "DesktopIconUI", prefix + "DesktopIconUI", - "DesktopPaneUI", prefix + "DesktopPaneUI", - "EditorPaneUI", prefix + "TextUI", - "FileChooserUI", prefix + "FileChooserUI", - "FormattedTextFieldUI", prefix + "TextUI", - "InternalFrameUI", prefix + "InternalFrameUI", - "LabelUI", prefix + "LabelUI", - "ListUI", prefix + "ListUI", - "MenuBarUI", prefix + "MenuBarUI", - "MenuItemUI", prefix + "MenuItemUI", - "MenuUI", prefix + "MenuItemUI", - "OptionPaneUI", prefix + "OptionPaneUI", - "PanelUI", prefix + "PanelUI", - "PasswordFieldUI", prefix + "TextUI", - "PopupMenuSeparatorUI", prefix + "SeparatorUI", - "PopupMenuUI", prefix + "PopupMenuUI", - "ProgressBarUI", prefix + "ProgressBarUI", - "RadioButtonMenuItemUI", prefix + "MenuItemUI", - "RadioButtonUI", prefix + "ButtonUI", - "RootPaneUI", prefix + "RootPaneUI", - "ScrollBarUI", prefix + "ScrollBarUI", - "ScrollPaneUI", prefix + "ScrollPaneUI", - "SeparatorUI", prefix + "SeparatorUI", - "SliderUI", prefix + "SliderUI", - "SpinnerUI", prefix + "SpinnerUI", - "SplitPaneUI", prefix + "SplitPaneUI", - "TabbedPaneUI", prefix + "TabbedPaneUI", - "TableHeaderUI", prefix + "TableHeaderUI", - "TableUI", prefix + "TableUI", - "TextAreaUI", prefix + "TextUI", - "TextFieldUI", prefix + "TextUI", - "TextPaneUI", prefix + "TextUI", - "ToggleButtonUI", prefix + "ButtonUI", - "ToolBarSeparatorUI", prefix + "SeparatorUI", - "ToolBarUI", prefix + "ToolBarUI", - "ToolTipUI", prefix + "ToolTipUI", - "TreeUI", prefix + "TreeUI", - "ViewportUI", prefix + "ViewportUI", - }; - - table.putDefaults(uiDefaults); - return table; - } - -} - -/** - * We want the Test auxiliary look and feel to be quiet and fallback - * gracefully if it cannot find a UI. This class overrides the - * getUIError method of UIDefaults, which is the method that - * emits error messages when it cannot find a UI class in the - * LAF. - */ -class TestALFUIDefaults extends UIDefaults { - protected void getUIError(String msg) { - System.err.println("Test auxiliary L&F: " + msg); - } -} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/bin/emessages.h --- a/jdk/src/share/bin/emessages.h Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/bin/emessages.h Wed Jul 05 16:42:37 2017 +0200 @@ -50,11 +50,6 @@ #define JAR_ERROR2 "Error: Unable to access jarfile %s" #define JAR_ERROR3 "Error: Invalid or corrupt jarfile %s" -#define CLS_ERROR1 "Error: Could not find the main class %s.\n" JNI_ERROR -#define CLS_ERROR2 "Error: Failed to load Main Class: %s\n%s" -#define CLS_ERROR3 "Error: No main method found in specified class.\n" GEN_ERROR -#define CLS_ERROR4 "Error: Main method not public\n" GEN_ERROR - #define CFG_WARN1 "Warning: %s VM not supported; %s VM will be used" #define CFG_WARN2 "Warning: No leading - on line %d of `%s'" #define CFG_WARN3 "Warning: Missing VM type on line %d of `%s'" diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/bin/java.c --- a/jdk/src/share/bin/java.c Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/bin/java.c Wed Jul 05 16:42:37 2017 +0200 @@ -102,8 +102,7 @@ InvocationFunctions *ifn); static jstring NewPlatformString(JNIEnv *env, char *s); static jobjectArray NewPlatformStringArray(JNIEnv *env, char **strv, int strc); -static jclass LoadClass(JNIEnv *env, char *name); -static jstring GetMainClassName(JNIEnv *env, char *jarname); +static jclass LoadMainClass(JNIEnv *env, jboolean isJar, char *name); static void TranslateApplicationArgs(int jargc, const char **jargv, int *pargc, char ***pargv); static jboolean AddApplicationOptions(int cpathc, const char **cpathv); @@ -301,6 +300,22 @@ } +#define CHECK_EXCEPTION_NULL_LEAVE(e) \ + if ((*env)->ExceptionOccurred(env)) { \ + JLI_ReportExceptionDescription(env); \ + goto leave; \ + } \ + if ((e) == NULL) { \ + JLI_ReportErrorMessage(JNI_ERROR); \ + goto leave; \ + } + +#define CHECK_EXCEPTION_LEAVE(rv) \ + if ((*env)->ExceptionOccurred(env)) { \ + JLI_ReportExceptionDescription(env); \ + ret = (rv); \ + goto leave; \ + } int JNICALL JavaMain(void * _args) @@ -321,9 +336,7 @@ int ret = 0; jlong start, end; - /* Initialize the virtual machine */ - start = CounterGet(); if (!InitializeJVM(&vm, &env, &ifn)) { JLI_ReportErrorMessage(JVM_ERROR1); @@ -332,11 +345,7 @@ if (printVersion || showVersion) { PrintJavaVersion(env, showVersion); - if ((*env)->ExceptionOccurred(env)) { - JLI_ReportExceptionDescription(env); - JLI_ReportErrorMessage(JNI_ERROR); - goto leave; - } + CHECK_EXCEPTION_LEAVE(0); if (printVersion) { ret = 0; goto leave; @@ -346,11 +355,7 @@ /* If the user specified neither a class name nor a JAR file */ if (printXUsage || printUsage || (jarfile == 0 && classname == 0)) { PrintUsage(env, printXUsage); - if ((*env)->ExceptionOccurred(env)) { - JLI_ReportExceptionDescription(env); - JLI_ReportErrorMessage(JNI_ERROR); - ret=1; - } + CHECK_EXCEPTION_LEAVE(1); goto leave; } @@ -395,99 +400,25 @@ * the environment (and remove these comments). */ if (jarfile != 0) { - mainClassName = GetMainClassName(env, jarfile); - if ((*env)->ExceptionOccurred(env)) { - JLI_ReportExceptionDescription(env); - JLI_ReportErrorMessage(JNI_ERROR); - goto leave; - } - if (mainClassName == NULL) { - JLI_ReportErrorMessage(JAR_ERROR1,jarfile, GEN_ERROR); - goto leave; - } - classname = (char *)(*env)->GetStringUTFChars(env, mainClassName, 0); - if (classname == NULL) { - JLI_ReportExceptionDescription(env); - JLI_ReportErrorMessage(JNI_ERROR); - goto leave; - } - mainClass = LoadClass(env, classname); - if(mainClass == NULL) { /* exception occured */ - JLI_ReportExceptionDescription(env); - JLI_ReportErrorMessage(CLS_ERROR1, classname); - goto leave; - } - (*env)->ReleaseStringUTFChars(env, mainClassName, classname); + mainClass = LoadMainClass(env, JNI_TRUE, jarfile); } else { - mainClassName = NewPlatformString(env, classname); - if (mainClassName == NULL) { - JLI_ReportErrorMessage(CLS_ERROR2, classname, GEN_ERROR); - goto leave; - } - classname = (char *)(*env)->GetStringUTFChars(env, mainClassName, 0); - if (classname == NULL) { - JLI_ReportExceptionDescription(env); - JLI_ReportErrorMessage(JNI_ERROR); - goto leave; - } - mainClass = LoadClass(env, classname); - if(mainClass == NULL) { /* exception occured */ - JLI_ReportExceptionDescription(env); - JLI_ReportErrorMessage(CLS_ERROR1, classname); - goto leave; - } - (*env)->ReleaseStringUTFChars(env, mainClassName, classname); + mainClass = LoadMainClass(env, JNI_FALSE, classname); } + CHECK_EXCEPTION_NULL_LEAVE(mainClass); - /* Get the application's main method */ + /* + * The LoadMainClass not only loads the main class, it will also ensure + * that the main method's signature is correct, therefore further checking + * is not required. The main method is invoked here so that extraneous java + * stacks are not in the application stack trace. + */ mainID = (*env)->GetStaticMethodID(env, mainClass, "main", "([Ljava/lang/String;)V"); - if (mainID == NULL) { - if ((*env)->ExceptionOccurred(env)) { - JLI_ReportExceptionDescription(env); - JLI_ReportErrorMessage(JNI_ERROR); - } else { - JLI_ReportErrorMessage(CLS_ERROR3); - } - goto leave; - } - - { /* Make sure the main method is public */ - jint mods; - jmethodID mid; - jobject obj = (*env)->ToReflectedMethod(env, mainClass, - mainID, JNI_TRUE); - - if( obj == NULL) { /* exception occurred */ - JLI_ReportExceptionDescription(env); - JLI_ReportErrorMessage(JNI_ERROR); - goto leave; - } - - mid = - (*env)->GetMethodID(env, - (*env)->GetObjectClass(env, obj), - "getModifiers", "()I"); - if ((*env)->ExceptionOccurred(env)) { - JLI_ReportExceptionDescription(env); - JLI_ReportErrorMessage(JNI_ERROR); - goto leave; - } - - mods = (*env)->CallIntMethod(env, obj, mid); - if ((mods & 1) == 0) { /* if (!Modifier.isPublic(mods)) ... */ - JLI_ReportErrorMessage(CLS_ERROR4); - goto leave; - } - } + CHECK_EXCEPTION_NULL_LEAVE(mainID); /* Build argument array */ mainArgs = NewPlatformStringArray(env, argv, argc); - if (mainArgs == NULL) { - JLI_ReportExceptionDescription(env); - JLI_ReportErrorMessage(JNI_ERROR); - goto leave; - } + CHECK_EXCEPTION_NULL_LEAVE(mainArgs); /* Invoke main method. */ (*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs); @@ -498,8 +429,9 @@ */ ret = (*env)->ExceptionOccurred(env) == NULL ? 0 : 1; +leave: /* - * Detach the main thread so that it appears to have ended when + * Always detach the main thread so that it appears to have ended when * the application's main method exits. This will invoke the * uncaught exception handler machinery if main threw an * exception. An uncaught exception handler cannot change the @@ -508,10 +440,7 @@ if ((*vm)->DetachCurrentThread(vm) != 0) { JLI_ReportErrorMessage(JVM_ERROR2); ret = 1; - goto leave; } - - leave: /* * Wait for all non-daemon threads to end, then destroy the VM. * This will actually create a trivial new Java waiter thread @@ -525,7 +454,6 @@ return ret; } - /* * Checks the command line options to find which JVM type was * specified. If no command line option was given for the JVM type, @@ -1159,7 +1087,7 @@ if (propname) { jclass cls; jmethodID mid; - NULL_CHECK0 (cls = (*env)->FindClass(env, "java/lang/System")); + NULL_CHECK0 (cls = FindBootStrapClass(env, "java/lang/System")); NULL_CHECK0 (mid = (*env)->GetStaticMethodID( env, cls, "getProperty", @@ -1174,7 +1102,7 @@ static jboolean isEncodingSupported(JNIEnv *env, jstring enc) { jclass cls; jmethodID mid; - NULL_CHECK0 (cls = (*env)->FindClass(env, "java/nio/charset/Charset")); + NULL_CHECK0 (cls = FindBootStrapClass(env, "java/nio/charset/Charset")); NULL_CHECK0 (mid = (*env)->GetStaticMethodID( env, cls, "isSupported", @@ -1203,8 +1131,8 @@ jstring str = 0; (*env)->SetByteArrayRegion(env, ary, 0, len, (jbyte *)s); if (!(*env)->ExceptionOccurred(env)) { + NULL_CHECK0(cls = FindBootStrapClass(env, "java/lang/String")); if (isEncodingSupported(env, enc) == JNI_TRUE) { - NULL_CHECK0(cls = (*env)->FindClass(env, "java/lang/String")); NULL_CHECK0(mid = (*env)->GetMethodID(env, cls, "", "([BLjava/lang/String;)V")); str = (*env)->NewObject(env, cls, mid, ary, enc); @@ -1215,7 +1143,6 @@ the encoding name, in which the StringCoding class will pickup the iso-8859-1 as the fallback converter for us. */ - NULL_CHECK0(cls = (*env)->FindClass(env, "java/lang/String")); NULL_CHECK0(mid = (*env)->GetMethodID(env, cls, "", "([B)V")); str = (*env)->NewObject(env, cls, mid, ary); @@ -1238,7 +1165,7 @@ jarray ary; int i; - NULL_CHECK0(cls = (*env)->FindClass(env, "java/lang/String")); + NULL_CHECK0(cls = FindBootStrapClass(env, "java/lang/String")); NULL_CHECK0(ary = (*env)->NewObjectArray(env, strc, cls, 0)); for (i = 0; i < strc; i++) { jstring str = NewPlatformString(env, *strv++); @@ -1250,25 +1177,26 @@ } /* - * Loads a class, convert the '.' to '/'. + * Loads a class and verifies that the main class is present and it is ok to + * call it for more details refer to the java implementation. */ static jclass -LoadClass(JNIEnv *env, char *name) +LoadMainClass(JNIEnv *env, jboolean isJar, char *name) { - char *buf = JLI_MemAlloc(JLI_StrLen(name) + 1); - char *s = buf, *t = name, c; jclass cls; + jmethodID mid; + jstring str; + jobject result; jlong start, end; - if (JLI_IsTraceLauncher()) + if (JLI_IsTraceLauncher()) { start = CounterGet(); - - do { - c = *t++; - *s++ = (c == '.') ? '/' : c; - } while (c != '\0'); - cls = (*env)->FindClass(env, buf); - JLI_MemFree(buf); + } + NULL_CHECK0(cls = FindBootStrapClass(env, "sun/launcher/LauncherHelper")); + NULL_CHECK0(mid = (*env)->GetStaticMethodID(env, cls, "checkAndLoadMain", + "(ZZLjava/lang/String;)Ljava/lang/Object;")); + str = (*env)->NewStringUTF(env, name); + result = (*env)->CallStaticObjectMethod(env, cls, mid, JNI_TRUE, isJar, str); if (JLI_IsTraceLauncher()) { end = CounterGet(); @@ -1277,49 +1205,9 @@ printf("----_JAVA_LAUNCHER_DEBUG----\n"); } - return cls; + return (jclass)result; } - -/* - * Returns the main class name for the specified jar file. - */ -static jstring -GetMainClassName(JNIEnv *env, char *jarname) -{ -#define MAIN_CLASS "Main-Class" - jclass cls; - jmethodID mid; - jobject jar, man, attr; - jstring str, result = 0; - - NULL_CHECK0(cls = (*env)->FindClass(env, "java/util/jar/JarFile")); - NULL_CHECK0(mid = (*env)->GetMethodID(env, cls, "", - "(Ljava/lang/String;)V")); - NULL_CHECK0(str = NewPlatformString(env, jarname)); - NULL_CHECK0(jar = (*env)->NewObject(env, cls, mid, str)); - NULL_CHECK0(mid = (*env)->GetMethodID(env, cls, "getManifest", - "()Ljava/util/jar/Manifest;")); - man = (*env)->CallObjectMethod(env, jar, mid); - if (man != 0) { - NULL_CHECK0(mid = (*env)->GetMethodID(env, - (*env)->GetObjectClass(env, man), - "getMainAttributes", - "()Ljava/util/jar/Attributes;")); - attr = (*env)->CallObjectMethod(env, man, mid); - if (attr != 0) { - NULL_CHECK0(mid = (*env)->GetMethodID(env, - (*env)->GetObjectClass(env, attr), - "getValue", - "(Ljava/lang/String;)Ljava/lang/String;")); - NULL_CHECK0(str = NewPlatformString(env, MAIN_CLASS)); - result = (*env)->CallObjectMethod(env, attr, mid, str); - } - } - return result; -} - - /* * For tools, convert command line args thus: * javac -cp foo:foo/"*" -J-ms32m ... @@ -1522,7 +1410,7 @@ jclass ver; jmethodID print; - NULL_CHECK(ver = (*env)->FindClass(env, "sun/misc/Version")); + NULL_CHECK(ver = FindBootStrapClass(env, "sun/misc/Version")); NULL_CHECK(print = (*env)->GetStaticMethodID(env, ver, (extraLF == JNI_TRUE) ? "println" : "print", @@ -1534,7 +1422,7 @@ } /* - * Prints default usage or the Xusage message, see sun.launcher.LauncherHelp.java + * Prints default usage or the Xusage message, see sun.launcher.LauncherHelper.java */ static void PrintUsage(JNIEnv* env, jboolean doXUsage) @@ -1544,7 +1432,7 @@ jstring jprogname, vm1, vm2; int i; - NULL_CHECK(cls = (*env)->FindClass(env, "sun/launcher/LauncherHelp")); + NULL_CHECK(cls = FindBootStrapClass(env, "sun/launcher/LauncherHelper")); if (doXUsage) { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/bin/java.h --- a/jdk/src/share/bin/java.h Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/bin/java.h Wed Jul 05 16:42:37 2017 +0200 @@ -180,4 +180,16 @@ */ void InitLauncher(jboolean javaw); +/* + * This allows for finding classes from the VM's bootstrap class loader directly, + * FindClass uses the application class loader internally, this will cause + * unnecessary searching of the classpath for the required classes. + * + */ +typedef jclass (JNICALL FindClassFromBootLoader_t(JNIEnv *env, + const char *name, + jboolean init, + jobject loader, + jboolean throwError)); +jclass FindBootStrapClass(JNIEnv *env, const char *classname); #endif /* _JAVA_H_ */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/beans/WeakCache.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/beans/WeakCache.java Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,84 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +package com.sun.beans; + +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; + +import java.util.Map; +import java.util.WeakHashMap; + +/** + * A hashtable-based cache with weak keys and weak values. + * An entry in the map will be automatically removed + * when its key is no longer in the ordinary use. + * A value will be automatically removed as well + * when it is no longer in the ordinary use. + * + * @since 1.7 + * + * @author Sergey A. Malenkov + */ +public final class WeakCache { + private final Map> map = new WeakHashMap>(); + + /** + * Returns a value to which the specified {@code key} is mapped, + * or {@code null} if this map contains no mapping for the {@code key}. + * + * @param key the key whose associated value is returned + * @return a value to which the specified {@code key} is mapped + */ + public V get(K key) { + Reference reference = this.map.get(key); + if (reference == null) { + return null; + } + V value = reference.get(); + if (value == null) { + this.map.remove(key); + } + return value; + } + + /** + * Associates the specified {@code value} with the specified {@code key}. + * Removes the mapping for the specified {@code key} from this cache + * if it is present and the specified {@code value} is {@code null}. + * If the cache previously contained a mapping for the {@code key}, + * the old value is replaced by the specified {@code value}. + * + * @param key the key with which the specified value is associated + * @param value the value to be associated with the specified key + */ + public void put(K key, V value) { + if (value != null) { + this.map.put(key, new WeakReference(value)); + } + else { + this.map.remove(key); + } + } +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,178 @@ +/* + * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package com.sun.java.swing; + +import sun.awt.EventQueueDelegate; +import sun.awt.AppContext; +import java.util.Map; +import java.util.concurrent.Callable; +import java.awt.AWTEvent; +import java.awt.EventQueue; +import java.awt.Component; +import javax.swing.JComponent; +import javax.swing.RepaintManager; + +/** + * A collection of utility methods for Swing. + *

+ * WARNING: While this class is public, it should not be treated as + * public API and its API may change in incompatable ways between dot dot + * releases and even patch releases. You should not rely on this class even + * existing. + * + * This is a second part of sun.swing.SwingUtilities2. It is required + * to provide services for JavaFX applets. + * + */ +public class SwingUtilities3 { + /** + * The {@code clientProperty} key for delegate {@code RepaintManager} + */ + private static final Object DELEGATE_REPAINT_MANAGER_KEY = + new StringBuilder("DelegateRepaintManagerKey"); + + /** + * Registers delegate RepaintManager for {@code JComponent}. + */ + public static void setDelegateRepaintManager(JComponent component, + RepaintManager repaintManager) { + /* setting up flag in AppContext to speed up lookups in case + * there are no delegate RepaintManagers used. + */ + AppContext.getAppContext().put(DELEGATE_REPAINT_MANAGER_KEY, + Boolean.TRUE); + + component.putClientProperty(DELEGATE_REPAINT_MANAGER_KEY, + repaintManager); + } + + /** + * Returns delegate {@code RepaintManager} for {@code component} hierarchy. + */ + public static RepaintManager getDelegateRepaintManager(Component + component) { + RepaintManager delegate = null; + if (Boolean.TRUE == AppContext.getAppContext().get( + DELEGATE_REPAINT_MANAGER_KEY)) { + while (delegate == null && component != null) { + while (component != null + && ! (component instanceof JComponent)) { + component = component.getParent(); + } + if (component != null) { + delegate = (RepaintManager) + ((JComponent) component) + .getClientProperty(DELEGATE_REPAINT_MANAGER_KEY); + component = component.getParent(); + } + + } + } + return delegate; + } + + /* + * We use maps to avoid reflection. Hopefully it should perform better + * this way. + */ + public static void setEventQueueDelegate( + Map> map) { + EventQueueDelegate.setDelegate(new EventQueueDelegateFromMap(map)); + } + + private static class EventQueueDelegateFromMap + implements EventQueueDelegate.Delegate { + private final AWTEvent[] afterDispatchEventArgument; + private final Object[] afterDispatchHandleArgument; + private final Callable afterDispatchCallable; + + private final AWTEvent[] beforeDispatchEventArgument; + private final Callable beforeDispatchCallable; + + private final EventQueue[] getNextEventEventQueueArgument; + private final Callable getNextEventCallable; + + @SuppressWarnings("unchecked") + public EventQueueDelegateFromMap(Map> objectMap) { + Map methodMap = objectMap.get("afterDispatch"); + afterDispatchEventArgument = (AWTEvent[]) methodMap.get("event"); + afterDispatchHandleArgument = (Object[]) methodMap.get("handle"); + afterDispatchCallable = (Callable) methodMap.get("method"); + + methodMap = objectMap.get("beforeDispatch"); + beforeDispatchEventArgument = (AWTEvent[]) methodMap.get("event"); + beforeDispatchCallable = (Callable) methodMap.get("method"); + + methodMap = objectMap.get("getNextEvent"); + getNextEventEventQueueArgument = + (EventQueue[]) methodMap.get("eventQueue"); + getNextEventCallable = (Callable) methodMap.get("method"); + } + + @Override + public void afterDispatch(AWTEvent event, Object handle) throws InterruptedException { + afterDispatchEventArgument[0] = event; + afterDispatchHandleArgument[0] = handle; + try { + afterDispatchCallable.call(); + } catch (InterruptedException e) { + throw e; + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public Object beforeDispatch(AWTEvent event) throws InterruptedException { + beforeDispatchEventArgument[0] = event; + try { + return beforeDispatchCallable.call(); + } catch (InterruptedException e) { + throw e; + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public AWTEvent getNextEvent(EventQueue eventQueue) throws InterruptedException { + getNextEventEventQueueArgument[0] = eventQueue; + try { + return getNextEventCallable.call(); + } catch (InterruptedException e) { + throw e; + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKColorChooserPanel.java --- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKColorChooserPanel.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKColorChooserPanel.java Wed Jul 05 16:42:37 2017 +0200 @@ -442,7 +442,10 @@ } if (updateModel) { - getColorSelectionModel().setSelectedColor(color); + ColorSelectionModel model = getColorSelectionModel(); + if (model != null) { + model.setSelectedColor(color); + } } triangle.setColor(hue, saturation, brightness); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java --- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java Wed Jul 05 16:42:37 2017 +0200 @@ -770,33 +770,56 @@ JComponent maximizeButton = findChild(titlePane, "InternalFrameTitlePane.maximizeButton"); JComponent closeButton = findChild(titlePane, "InternalFrameTitlePane.closeButton"); - int buttonGap = 0; - Insets button_border = (Insets)gm.get("button_border"); Dimension buttonDim = calculateButtonSize(titlePane); - int x = getInt("left_titlebar_edge"); int y = (button_border != null) ? button_border.top : 0; + if (titlePaneParent.getComponentOrientation().isLeftToRight()) { + int x = getInt("left_titlebar_edge"); - menuButton.setBounds(x, y, buttonDim.width, buttonDim.height); + menuButton.setBounds(x, y, buttonDim.width, buttonDim.height); - x = w - buttonDim.width - getInt("right_titlebar_edge"); - if (button_border != null) { - x -= button_border.right; - } + x = w - buttonDim.width - getInt("right_titlebar_edge"); + if (button_border != null) { + x -= button_border.right; + } + + if (frame.isClosable()) { + closeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + x -= buttonDim.width; + } + + if (frame.isMaximizable()) { + maximizeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + x -= buttonDim.width; + } - if (frame.isClosable()) { - closeButton.setBounds(x, y, buttonDim.width, buttonDim.height); - x -= (buttonDim.width + buttonGap); - } + if (frame.isIconifiable()) { + minimizeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + } + } else { + int x = w - buttonDim.width - getInt("right_titlebar_edge"); + + menuButton.setBounds(x, y, buttonDim.width, buttonDim.height); + + x = getInt("left_titlebar_edge"); + if (button_border != null) { + x += button_border.left; + } - if (frame.isMaximizable()) { - maximizeButton.setBounds(x, y, buttonDim.width, buttonDim.height); - x -= (buttonDim.width + buttonGap); - } + if (frame.isClosable()) { + closeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + x += buttonDim.width; + } - if (frame.isIconifiable()) { - minimizeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + if (frame.isMaximizable()) { + maximizeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + x += buttonDim.width; + } + + if (frame.isIconifiable()) { + minimizeButton.setBounds(x, y, buttonDim.width, buttonDim.height); + } } } } // end TitlePaneLayout @@ -973,10 +996,8 @@ String title = jif.getTitle(); if (title != null) { FontMetrics fm = SwingUtilities2.getFontMetrics(jif, g); - if (jif.getComponentOrientation().isLeftToRight()) { - title = SwingUtilities2.clipStringIfNecessary(jif, fm, title, - calculateTitleTextWidth(g, jif)); - } + title = SwingUtilities2.clipStringIfNecessary(jif, fm, title, + calculateTitleArea(jif).width); g.setColor(color); SwingUtilities2.drawString(jif, g, title, x, y + fm.getAscent()); } @@ -1010,9 +1031,10 @@ JComponent titlePane = findChild(jif, "InternalFrame.northPane"); Dimension buttonDim = calculateButtonSize(titlePane); Insets title_border = (Insets)frameGeometry.get("title_border"); - Rectangle r = new Rectangle(); + Insets button_border = (Insets)getFrameGeometry().get("button_border"); - r.x = getInt("left_titlebar_edge") + buttonDim.width; + Rectangle r = new Rectangle(); + r.x = getInt("left_titlebar_edge"); r.y = 0; r.height = titlePane.getHeight(); if (title_border != null) { @@ -1021,15 +1043,36 @@ r.height -= (title_border.top + title_border.bottom); } - r.width = titlePane.getWidth() - r.x - getInt("right_titlebar_edge"); - if (jif.isClosable()) { - r.width -= buttonDim.width; - } - if (jif.isMaximizable()) { - r.width -= buttonDim.width; - } - if (jif.isIconifiable()) { - r.width -= buttonDim.width; + if (titlePane.getParent().getComponentOrientation().isLeftToRight()) { + r.x += buttonDim.width; + if (button_border != null) { + r.x += button_border.left; + } + r.width = titlePane.getWidth() - r.x - getInt("right_titlebar_edge"); + if (jif.isClosable()) { + r.width -= buttonDim.width; + } + if (jif.isMaximizable()) { + r.width -= buttonDim.width; + } + if (jif.isIconifiable()) { + r.width -= buttonDim.width; + } + } else { + if (jif.isClosable()) { + r.x += buttonDim.width; + } + if (jif.isMaximizable()) { + r.x += buttonDim.width; + } + if (jif.isIconifiable()) { + r.x += buttonDim.width; + } + r.width = titlePane.getWidth() - r.x - getInt("right_titlebar_edge") + - buttonDim.width; + if (button_border != null) { + r.x -= button_border.right; + } } if (title_border != null) { r.width -= title_border.right; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/java/swing/plaf/windows/DesktopProperty.java --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/DesktopProperty.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/DesktopProperty.java Wed Jul 05 16:42:37 2017 +0200 @@ -49,8 +49,7 @@ /** * ReferenceQueue of unreferenced WeakPCLs. */ - private static ReferenceQueue queue; - + private static ReferenceQueue queue; /** * PropertyChangeListener attached to the Toolkit. @@ -76,7 +75,7 @@ static { - queue = new ReferenceQueue(); + queue = new ReferenceQueue(); } /** @@ -117,8 +116,8 @@ XPStyle.invalidateStyle(); } Frame appFrames[] = Frame.getFrames(); - for (int j=0; j < appFrames.length; j++) { - updateWindowUI(appFrames[j]); + for (Frame appFrame : appFrames) { + updateWindowUI(appFrame); } } @@ -128,8 +127,8 @@ private static void updateWindowUI(Window window) { SwingUtilities.updateComponentTreeUI(window); Window ownedWins[] = window.getOwnedWindows(); - for (int i=0; i < ownedWins.length; i++) { - updateWindowUI(ownedWins[i]); + for (Window ownedWin : ownedWins) { + updateWindowUI(ownedWin); } } @@ -270,13 +269,13 @@ * is handled via a WeakReference so as not to pin down the * DesktopProperty. */ - private static class WeakPCL extends WeakReference + private static class WeakPCL extends WeakReference implements PropertyChangeListener { private Toolkit kit; private String key; private LookAndFeel laf; - WeakPCL(Object target, Toolkit kit, String key, LookAndFeel laf) { + WeakPCL(DesktopProperty target, Toolkit kit, String key, LookAndFeel laf) { super(target, queue); this.kit = kit; this.key = key; @@ -284,7 +283,7 @@ } public void propertyChange(PropertyChangeEvent pce) { - DesktopProperty property = (DesktopProperty)get(); + DesktopProperty property = get(); if (property == null || laf != UIManager.getLookAndFeel()) { // The property was GC'ed, we're no longer interested in diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsDesktopManager.java --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsDesktopManager.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsDesktopManager.java Wed Jul 05 16:42:37 2017 +0200 @@ -96,7 +96,7 @@ } } catch (PropertyVetoException e) {} if (f != currentFrame) { - currentFrameRef = new WeakReference(f); + currentFrameRef = new WeakReference(f); } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -983,7 +983,7 @@ } else if (s.equals("componentOrientation")) { ComponentOrientation o = (ComponentOrientation)e.getNewValue(); JFileChooser cc = (JFileChooser)e.getSource(); - if (o != (ComponentOrientation)e.getOldValue()) { + if (o != e.getOldValue()) { cc.applyComponentOrientation(o); } } else if (s.equals("ancestor")) { @@ -1123,7 +1123,7 @@ * Data model for a type-face selection combo-box. */ protected class DirectoryComboBoxModel extends AbstractListModel implements ComboBoxModel { - Vector directories = new Vector(); + Vector directories = new Vector(); int[] depths = null; File selectedDirectory = null; JFileChooser chooser = getFileChooser(); @@ -1162,7 +1162,7 @@ // Get the canonical (full) path. This has the side // benefit of removing extraneous chars from the path, // for example /foo/bar/ becomes /foo/bar - File canonical = null; + File canonical; try { canonical = directory.getCanonicalFile(); } catch (IOException e) { @@ -1175,7 +1175,7 @@ File sf = useShellFolder ? ShellFolder.getShellFolder(canonical) : canonical; File f = sf; - Vector path = new Vector(10); + Vector path = new Vector(10); do { path.addElement(f); } while ((f = f.getParentFile()) != null); @@ -1183,7 +1183,7 @@ int pathCount = path.size(); // Insert chain at appropriate place in vector for (int i = 0; i < pathCount; i++) { - f = (File)path.get(i); + f = path.get(i); if (directories.contains(f)) { int topIndex = directories.indexOf(f); for (int j = i-1; j >= 0; j--) { @@ -1202,12 +1202,12 @@ private void calculateDepths() { depths = new int[directories.size()]; for (int i = 0; i < depths.length; i++) { - File dir = (File)directories.get(i); + File dir = directories.get(i); File parent = dir.getParentFile(); depths[i] = 0; if (parent != null) { for (int j = i-1; j >= 0; j--) { - if (parent.equals((File)directories.get(j))) { + if (parent.equals(directories.get(j))) { depths[i] = depths[j] + 1; break; } @@ -1306,8 +1306,8 @@ FileFilter currentFilter = getFileChooser().getFileFilter(); boolean found = false; if(currentFilter != null) { - for(int i=0; i < filters.length; i++) { - if(filters[i] == currentFilter) { + for (FileFilter filter : filters) { + if (filter == currentFilter) { found = true; } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsInternalFrameTitlePane.java Wed Jul 05 16:42:37 2017 +0200 @@ -137,25 +137,46 @@ int baseline = (getHeight() + fm.getAscent() - fm.getLeading() - fm.getDescent()) / 2; - int titleX; - Rectangle r = new Rectangle(0, 0, 0, 0); - if (frame.isIconifiable()) r = iconButton.getBounds(); - else if (frame.isMaximizable()) r = maxButton.getBounds(); - else if (frame.isClosable()) r = closeButton.getBounds(); - int titleW; + Rectangle lastIconBounds = new Rectangle(0, 0, 0, 0); + if (frame.isIconifiable()) { + lastIconBounds = iconButton.getBounds(); + } else if (frame.isMaximizable()) { + lastIconBounds = maxButton.getBounds(); + } else if (frame.isClosable()) { + lastIconBounds = closeButton.getBounds(); + } - if(WindowsGraphicsUtils.isLeftToRight(frame) ) { - if (r.x == 0) r.x = frame.getWidth()-frame.getInsets().right; - titleX = systemLabel.getX() + systemLabel.getWidth() + 2; - if (xp != null) { - titleX += 2; - } - titleW = r.x - titleX - 3; - title = getTitle(frame.getTitle(), fm, titleW); + int titleX; + int titleW; + int gap = 2; + if (WindowsGraphicsUtils.isLeftToRight(frame)) { + if (lastIconBounds.x == 0) { // There are no icons + lastIconBounds.x = frame.getWidth() - frame.getInsets().right; + } + titleX = systemLabel.getX() + systemLabel.getWidth() + gap; + if (xp != null) { + titleX += 2; + } + titleW = lastIconBounds.x - titleX - gap; } else { - titleX = systemLabel.getX() - 2 - - SwingUtilities2.stringWidth(frame,fm,title); + if (lastIconBounds.x == 0) { // There are no icons + lastIconBounds.x = frame.getInsets().left; + } + titleW = SwingUtilities2.stringWidth(frame, fm, title); + int minTitleX = lastIconBounds.x + lastIconBounds.width + gap; + if (xp != null) { + minTitleX += 2; + } + int availableWidth = systemLabel.getX() - gap - minTitleX; + if (availableWidth > titleW) { + titleX = systemLabel.getX() - gap - titleW; + } else { + titleX = minTitleX; + titleW = availableWidth; + } } + title = getTitle(frame.getTitle(), fm, titleW); + if (xp != null) { String shadowType = null; if (isSelected) { @@ -258,8 +279,8 @@ g.fillRect(0, 0, w, h); } Icon icon = getIcon(); - int iconWidth = 0; - int iconHeight = 0; + int iconWidth; + int iconHeight; if (icon != null && (iconWidth = icon.getIconWidth()) > 0 && (iconHeight = icon.getIconHeight()) > 0) { @@ -304,18 +325,18 @@ } protected void addSystemMenuItems(JPopupMenu menu) { - JMenuItem mi = (JMenuItem)menu.add(restoreAction); + JMenuItem mi = menu.add(restoreAction); mi.setMnemonic('R'); - mi = (JMenuItem)menu.add(moveAction); + mi = menu.add(moveAction); mi.setMnemonic('M'); - mi = (JMenuItem)menu.add(sizeAction); + mi = menu.add(sizeAction); mi.setMnemonic('S'); - mi = (JMenuItem)menu.add(iconifyAction); + mi = menu.add(iconifyAction); mi.setMnemonic('n'); - mi = (JMenuItem)menu.add(maximizeAction); + mi = menu.add(maximizeAction); mi.setMnemonic('x'); systemPopupMenu.add(new JSeparator()); - mi = (JMenuItem)menu.add(closeAction); + mi = menu.add(closeAction); mi.setMnemonic('C'); } @@ -441,7 +462,7 @@ public class WindowsPropertyChangeHandler extends PropertyChangeHandler { public void propertyChange(PropertyChangeEvent evt) { - String prop = (String)evt.getPropertyName(); + String prop = evt.getPropertyName(); // Update the internal frame icon for the system menu. if (JInternalFrame.FRAME_ICON_PROPERTY.equals(prop) && diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsScrollBarUI.java --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsScrollBarUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsScrollBarUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -369,21 +369,21 @@ */ private static class Grid { private static final int BUFFER_SIZE = 64; - private static HashMap map; + private static HashMap> map; private BufferedImage image; static { - map = new HashMap(); + map = new HashMap>(); } public static Grid getGrid(Color fg, Color bg) { String key = fg.getRGB() + " " + bg.getRGB(); - WeakReference ref = (WeakReference)map.get(key); - Grid grid = (ref == null) ? null : (Grid)ref.get(); + WeakReference ref = map.get(key); + Grid grid = (ref == null) ? null : ref.get(); if (grid == null) { grid = new Grid(fg, bg); - map.put(key, new WeakReference(grid)); + map.put(key, new WeakReference(grid)); } return grid; } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTabbedPaneUI.java --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTabbedPaneUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTabbedPaneUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -53,13 +53,13 @@ * Keys to use for forward focus traversal when the JComponent is * managing focus. */ - private static Set managingFocusForwardTraversalKeys; + private static Set managingFocusForwardTraversalKeys; /** * Keys to use for backward focus traversal when the JComponent is * managing focus. */ - private static Set managingFocusBackwardTraversalKeys; + private static Set managingFocusBackwardTraversalKeys; private boolean contentOpaque = true; @@ -69,13 +69,13 @@ // focus forward traversal key if (managingFocusForwardTraversalKeys==null) { - managingFocusForwardTraversalKeys = new HashSet(); + managingFocusForwardTraversalKeys = new HashSet(); managingFocusForwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)); } tabPane.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, managingFocusForwardTraversalKeys); // focus backward traversal key if (managingFocusBackwardTraversalKeys==null) { - managingFocusBackwardTraversalKeys = new HashSet(); + managingFocusBackwardTraversalKeys = new HashSet(); managingFocusBackwardTraversalKeys.add( KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK)); } tabPane.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, managingFocusBackwardTraversalKeys); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -124,7 +124,7 @@ setIcon(null); sortIcon = null; SortOrder sortOrder = - getColumnSortOrder(header.getTable(), column); + getColumnSortOrder(table, column); if (sortOrder != null) { switch (sortOrder) { case ASCENDING: diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java --- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java Wed Jul 05 16:42:37 2017 +0200 @@ -228,7 +228,15 @@ // to generate the appropriate exception. } if (c != null) { - MXBeanMappingFactory factory = MXBeanMappingFactory.forInterface(c); + MXBeanMappingFactory factory; + try { + factory = MXBeanMappingFactory.forInterface(c); + } catch (IllegalArgumentException e) { + NotCompliantMBeanException ncmbe = + new NotCompliantMBeanException(e.getMessage()); + ncmbe.initCause(e); + throw ncmbe; + } return new MXBeanSupport(mbean, c, factory); } checkCompliance(mbeanClass); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/jmx/mbeanserver/MXBeanSupport.java --- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MXBeanSupport.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MXBeanSupport.java Wed Jul 05 16:42:37 2017 +0200 @@ -36,7 +36,6 @@ import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.openmbean.MXBeanMappingFactory; -import javax.management.openmbean.MXBeanMappingFactoryClass; /** * Base class for MXBeans. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/Init.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/Init.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/Init.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,12 +20,9 @@ */ package com.sun.org.apache.xml.internal.security; - - import java.io.InputStream; import java.security.AccessController; import java.security.PrivilegedAction; - import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -51,7 +48,7 @@ * done by calling {@link Init#init} which should be done in any static block * of the files of this library. We ensure that this call is only executed once. * - * @author $Author: raul $ + * @author $Author: mullan $ */ public final class Init { @@ -113,20 +110,19 @@ dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); - // We don't allow users to override the Apache XML Security // configuration in the JRE. Users should use the standard security // provider mechanism instead if implementing their own // transform or canonicalization algorithms. - // String cfile = System.getProperty("com.sun.org.apache.xml.internal.security.resource.config"); - // InputStream is = - // Class.forName("com.sun.org.apache.xml.internal.security.Init") - // .getResourceAsStream(cfile != null ? cfile : "resource/config.xml"); + // InputStream is = Class.forName("com.sun.org.apache.xml.internal.security.Init").getResourceAsStream("resource/config.xml"); InputStream is = (InputStream) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { +// String cfile = System.getProperty +// ("com.sun.org.apache.xml.internal.security.resource.config"); return getClass().getResourceAsStream - ("resource/config.xml"); +// (cfile != null ? cfile : "resource/config.xml"); + ("resource/config.xml"); } }); @@ -167,7 +163,7 @@ // // if (tag.equals("ResourceBundles")){ // XX_configure_i18n_start = System.currentTimeMillis(); -// Element resource=(Element)el; +// Element resource=(Element)el; // /* configure internationalization */ // Attr langAttr = resource.getAttributeNode("defaultLanguageCode"); // Attr countryAttr = resource.getAttributeNode("defaultCountryCode"); @@ -202,11 +198,11 @@ if (currMeth.getDeclaringClass().getName() .equals(JAVACLASS)) { - log.log(java.util.logging.Level.FINE, currMeth.getDeclaringClass().toString()); + log.log(java.util.logging.Level.FINE, currMeth.getDe claringClass().toString()); } }*/ - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Canonicalizer.register(" + URI + ", " + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Canonicalizer.register(" + URI + ", " + JAVACLASS + ")"); Canonicalizer.register(URI, JAVACLASS); } catch (ClassNotFoundException e) { @@ -233,9 +229,8 @@ "JAVACLASS"); try { Class.forName(JAVACLASS); - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Transform.register(" + URI + ", " + JAVACLASS - + ")"); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Transform.register(" + URI + ", " + JAVACLASS + ")"); Transform.register(URI, JAVACLASS); } catch (ClassNotFoundException e) { Object exArgs[] = { URI, JAVACLASS }; @@ -284,12 +279,11 @@ // // if (currMeth.getDeclaringClass().getName() // .equals(JAVACLASS)) { -// log.log(java.util.logging.Level.FINE, currMeth.getDeclaringClass().toString()); +// log.log(java.util.logging.Level.FINE, currMeth.getDe claringClass().toString()); // } // } - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "SignatureAlgorithm.register(" + URI + ", " - + JAVACLASS + ")"); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "SignatureAlgorithm.register(" + URI + ", " + JAVACLASS + ")"); SignatureAlgorithm.register(URI, JAVACLASS); } catch (ClassNotFoundException e) { Object exArgs[] = { URI, JAVACLASS }; @@ -320,13 +314,11 @@ "DESCRIPTION"); if ((Description != null) && (Description.length() > 0)) { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " - + Description); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " + Description); } else { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS - + ": For unknown purposes"); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": For unknown purposes"); } try { ResourceResolver.register(JAVACLASS); @@ -359,13 +351,11 @@ "DESCRIPTION"); if ((Description != null) && (Description.length() > 0)) { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " - + Description); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " + Description); } else { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS - + ": For unknown purposes"); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": For unknown purposes"); } KeyResolver.register(JAVACLASS); @@ -376,8 +366,8 @@ if (tag.equals("PrefixMappings")){ XX_configure_reg_prefixes_start = System.currentTimeMillis(); - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Now I try to bind prefixes:"); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Now I try to bind prefixes:"); Element[] nl = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS,"PrefixMapping"); @@ -386,8 +376,8 @@ "namespace"); String prefix = nl[i].getAttributeNS(null, "prefix"); - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Now I try to bind " + prefix + " to " + namespace); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Now I try to bind " + prefix + " to " + namespace); com.sun.org.apache.xml.internal.security.utils.ElementProxy .setDefaultPrefix(namespace, prefix); } @@ -398,19 +388,19 @@ long XX_init_end = System.currentTimeMillis(); //J- - if (true) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "XX_init " + ((int)(XX_init_end - XX_init_start)) + " ms"); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_prng " + ((int)(XX_prng_end - XX_prng_start)) + " ms"); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_parsing " + ((int)(XX_parsing_end - XX_parsing_start)) + " ms"); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_i18n " + ((int)(XX_configure_i18n_end- XX_configure_i18n_start)) + " ms"); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_c14n " + ((int)(XX_configure_reg_c14n_end- XX_configure_reg_c14n_start)) + " ms"); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_jcemapper " + ((int)(XX_configure_reg_jcemapper_end- XX_configure_reg_jcemapper_start)) + " ms"); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_keyInfo " + ((int)(XX_configure_reg_keyInfo_end- XX_configure_reg_keyInfo_start)) + " ms"); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_keyResolver " + ((int)(XX_configure_reg_keyResolver_end- XX_configure_reg_keyResolver_start)) + " ms"); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_prefixes " + ((int)(XX_configure_reg_prefixes_end- XX_configure_reg_prefixes_start)) + " ms"); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_resourceresolver " + ((int)(XX_configure_reg_resourceresolver_end- XX_configure_reg_resourceresolver_start)) + " ms"); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_sigalgos " + ((int)(XX_configure_reg_sigalgos_end- XX_configure_reg_sigalgos_start)) + " ms"); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_transforms " + ((int)(XX_configure_reg_transforms_end- XX_configure_reg_transforms_start)) + " ms"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XX_init " + ((int)(XX_init_end - XX_init_start)) + " ms"); + log.log(java.util.logging.Level.FINE, " XX_prng " + ((int)(XX_prng_end - XX_prng_start)) + " ms"); + log.log(java.util.logging.Level.FINE, " XX_parsing " + ((int)(XX_parsing_end - XX_parsing_start)) + " ms"); + log.log(java.util.logging.Level.FINE, " XX_configure_i18n " + ((int)(XX_configure_i18n_end- XX_configure_i18n_start)) + " ms"); + log.log(java.util.logging.Level.FINE, " XX_configure_reg_c14n " + ((int)(XX_configure_reg_c14n_end- XX_configure_reg_c14n_start)) + " ms"); + log.log(java.util.logging.Level.FINE, " XX_configure_reg_jcemapper " + ((int)(XX_configure_reg_jcemapper_end- XX_configure_reg_jcemapper_start)) + " ms"); + log.log(java.util.logging.Level.FINE, " XX_configure_reg_keyInfo " + ((int)(XX_configure_reg_keyInfo_end- XX_configure_reg_keyInfo_start)) + " ms"); + log.log(java.util.logging.Level.FINE, " XX_configure_reg_keyResolver " + ((int)(XX_configure_reg_keyResolver_end- XX_configure_reg_keyResolver_start)) + " ms"); + log.log(java.util.logging.Level.FINE, " XX_configure_reg_prefixes " + ((int)(XX_configure_reg_prefixes_end- XX_configure_reg_prefixes_start)) + " ms"); + log.log(java.util.logging.Level.FINE, " XX_configure_reg_resourceresolver " + ((int)(XX_configure_reg_resourceresolver_end- XX_configure_reg_resourceresolver_start)) + " ms"); + log.log(java.util.logging.Level.FINE, " XX_configure_reg_sigalgos " + ((int)(XX_configure_reg_sigalgos_end- XX_configure_reg_sigalgos_start)) + " ms"); + log.log(java.util.logging.Level.FINE, " XX_configure_reg_transforms " + ((int)(XX_configure_reg_transforms_end- XX_configure_reg_transforms_start)) + " ms"); } } catch (Exception e) { log.log(java.util.logging.Level.SEVERE, "Bad: ", e); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java Wed Jul 05 16:42:37 2017 +0200 @@ -24,7 +24,7 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; -import com.sun.org.apache.xml.internal.security.utils.ElementProxy; +import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -33,11 +33,7 @@ * The Algorithm class which stores the Algorithm URI as a string. * */ -public abstract class Algorithm extends ElementProxy { - - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(Algorithm.class.getName()); +public abstract class Algorithm extends SignatureElementProxy { /** * @@ -79,7 +75,7 @@ */ protected void setAlgorithmURI(String algorithmURI) { - if ((this._state == MODE_CREATE) && (algorithmURI != null)) { + if ( (algorithmURI != null)) { this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java Wed Jul 05 16:42:37 2017 +0200 @@ -35,7 +35,7 @@ /** * This class maps algorithm identifier URIs to JAVA JCE class names. * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class JCEMapper { @@ -45,9 +45,9 @@ - private static Map uriToJCEName = new HashMap(); + private static Map uriToJCEName; - private static Map algorithmsMap = new HashMap(); + private static Map algorithmsMap; private static String providerName = null; /** @@ -63,6 +63,8 @@ static void loadAlgorithms( Element algorithmsEl) { Element[] algorithms = XMLUtils.selectNodes(algorithmsEl.getFirstChild(),Init.CONF_NS,"Algorithm"); + uriToJCEName = new HashMap( algorithms.length * 2); + algorithmsMap = new HashMap( algorithms.length * 2); for (int i = 0 ;i < algorithms.length ;i ++) { Element el = algorithms[i]; String id = el.getAttribute("URI"); @@ -70,6 +72,7 @@ uriToJCEName.put(id, jceName); algorithmsMap.put(id, new Algorithm(el)); } + } static Algorithm getAlgorithmMapping(String algoURI) { @@ -84,8 +87,8 @@ * */ public static String translateURItoJCEID(String AlgorithmURI) { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI); String jceName = (String) uriToJCEName.get(AlgorithmURI); return jceName; @@ -100,8 +103,8 @@ * */ public static String getAlgorithmClassFromURI(String AlgorithmURI) { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI); return ((Algorithm) algorithmsMap.get(AlgorithmURI)).algorithmClass; } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,10 +20,10 @@ */ package com.sun.org.apache.xml.internal.security.algorithms; - - import java.security.MessageDigest; import java.security.NoSuchProviderException; +import java.util.HashMap; +import java.util.Map; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.utils.Constants; @@ -41,11 +41,6 @@ */ public class MessageDigestAlgorithm extends Algorithm { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - MessageDigestAlgorithm.class.getName()); - /** Message Digest - NOT RECOMMENDED MD5*/ public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "md5"; /** Digest - Required SHA1*/ @@ -76,6 +71,12 @@ this.algorithm = messageDigest; } + static ThreadLocal instances=new ThreadLocal() { + protected Object initialValue() { + return new HashMap(); + }; + }; + /** * Factory method for constructing a message digest algorithm by name. * @@ -86,8 +87,15 @@ */ public static MessageDigestAlgorithm getInstance( Document doc, String algorithmURI) throws XMLSignatureException { + MessageDigest md = getDigestInstance(algorithmURI); + return new MessageDigestAlgorithm(doc, md, algorithmURI); + } - String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI); +private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException { + MessageDigest result=(MessageDigest) ((Map)instances.get()).get(algorithmURI); + if (result!=null) + return result; + String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI); if (algorithmID == null) { Object[] exArgs = { algorithmURI }; @@ -113,8 +121,9 @@ throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); } - return new MessageDigestAlgorithm(doc, md, algorithmURI); - } + ((Map)instances.get()).put(algorithmURI, md); + return md; +} /** * Returns the actual {@link java.security.MessageDigest} algorithm object diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java Wed Jul 05 16:42:37 2017 +0200 @@ -25,6 +25,7 @@ import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import java.util.HashMap; +import java.util.Map; import com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac; import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException; @@ -52,9 +53,35 @@ /** All available algorithm classes are registered here */ static HashMap _algorithmHash = null; + static ThreadLocal instancesSigning=new ThreadLocal() { + protected Object initialValue() { + return new HashMap(); + }; + }; + + static ThreadLocal instancesVerify=new ThreadLocal() { + protected Object initialValue() { + return new HashMap(); + }; + }; + + static ThreadLocal keysSigning=new ThreadLocal() { + protected Object initialValue() { + return new HashMap(); + }; + }; + static ThreadLocal keysVerify=new ThreadLocal() { + protected Object initialValue() { + return new HashMap(); + }; + }; +// boolean isForSigning=false; + /** Field _signatureAlgorithm */ protected SignatureAlgorithmSpi _signatureAlgorithm = null; + private String algorithmURI; + /** * Constructor SignatureAlgorithm * @@ -64,18 +91,49 @@ */ public SignatureAlgorithm(Document doc, String algorithmURI) throws XMLSecurityException { + super(doc, algorithmURI); + this.algorithmURI = algorithmURI; + } - super(doc, algorithmURI); - try { + private void initializeAlgorithm(boolean isForSigning) throws XMLSignatureException { + if (_signatureAlgorithm!=null) { + return; + } + _signatureAlgorithm=isForSigning ? getInstanceForSigning(algorithmURI) : getInstanceForVerify(algorithmURI); + this._signatureAlgorithm + .engineGetContextFromElement(this._constructionElement); + } + private static SignatureAlgorithmSpi getInstanceForSigning(String algorithmURI) throws XMLSignatureException { + SignatureAlgorithmSpi result=(SignatureAlgorithmSpi) ((Map)instancesSigning.get()).get(algorithmURI); + if (result!=null) { + result.reset(); + return result; + } + result=buildSigner(algorithmURI, result); + ((Map)instancesSigning.get()).put(algorithmURI,result); + return result; + } + private static SignatureAlgorithmSpi getInstanceForVerify(String algorithmURI) throws XMLSignatureException { + SignatureAlgorithmSpi result=(SignatureAlgorithmSpi) ((Map)instancesVerify.get()).get(algorithmURI); + if (result!=null) { + result.reset(); + return result; + } + result=buildSigner(algorithmURI, result); + ((Map)instancesVerify.get()).put(algorithmURI,result); + return result; + } + + private static SignatureAlgorithmSpi buildSigner(String algorithmURI, SignatureAlgorithmSpi result) throws XMLSignatureException { + try { Class implementingClass = SignatureAlgorithm.getImplementingClass(algorithmURI); - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \"" + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \"" + implementingClass + "\""); - - this._signatureAlgorithm = - (SignatureAlgorithmSpi) implementingClass.newInstance(); + result=(SignatureAlgorithmSpi) implementingClass.newInstance(); + return result; } catch (IllegalAccessException ex) { Object exArgs[] = { algorithmURI, ex.getMessage() }; @@ -92,7 +150,7 @@ throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex); } - } +} /** * Constructor SignatureAlgorithm @@ -107,7 +165,8 @@ throws XMLSecurityException { this(doc, algorithmURI); - + this.algorithmURI=algorithmURI; + initializeAlgorithm(true); this._signatureAlgorithm.engineSetHMACOutputLength(HMACOutputLength); ((IntegrityHmac)this._signatureAlgorithm) .engineAddContextToElement(this._constructionElement); @@ -124,37 +183,7 @@ throws XMLSecurityException { super(element, BaseURI); - - String algorithmURI = this.getURI(); - - try { - Class implementingClass = - SignatureAlgorithm.getImplementingClass(algorithmURI); - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \"" - + implementingClass + "\""); - - this._signatureAlgorithm = - (SignatureAlgorithmSpi) implementingClass.newInstance(); - - this._signatureAlgorithm - .engineGetContextFromElement(this._constructionElement); - } catch (IllegalAccessException ex) { - Object exArgs[] = { algorithmURI, ex.getMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, - ex); - } catch (InstantiationException ex) { - Object exArgs[] = { algorithmURI, ex.getMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, - ex); - } catch (NullPointerException ex) { - Object exArgs[] = { algorithmURI, ex.getMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, - ex); - } + algorithmURI = this.getURI(); } /** @@ -175,7 +204,12 @@ * @return the result of the {@link java.security.Signature#getAlgorithm} method */ public String getJCEAlgorithmString() { - return this._signatureAlgorithm.engineGetJCEAlgorithmString(); + try { + return getInstanceForVerify(algorithmURI).engineGetJCEAlgorithmString(); + } catch (XMLSignatureException e) { + //Ignore. + return null; + } } /** @@ -184,7 +218,11 @@ * @return The Provider of this Signature Alogrithm */ public String getJCEProviderName() { - return this._signatureAlgorithm.engineGetJCEProviderName(); + try { + return getInstanceForVerify(algorithmURI).engineGetJCEProviderName(); + } catch (XMLSignatureException e) { + return null; + } } /** @@ -231,7 +269,13 @@ * @throws XMLSignatureException */ public void initSign(Key signingKey) throws XMLSignatureException { - this._signatureAlgorithm.engineInitSign(signingKey); + initializeAlgorithm(true); + Map map=(Map)keysSigning.get(); + if (map.get(this.algorithmURI)==signingKey) { + return; + } + map.put(this.algorithmURI,signingKey); + this._signatureAlgorithm.engineInitSign(signingKey); } /** @@ -244,6 +288,7 @@ */ public void initSign(Key signingKey, SecureRandom secureRandom) throws XMLSignatureException { + initializeAlgorithm(true); this._signatureAlgorithm.engineInitSign(signingKey, secureRandom); } @@ -258,6 +303,7 @@ public void initSign( Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) throws XMLSignatureException { + initializeAlgorithm(true); this._signatureAlgorithm.engineInitSign(signingKey, algorithmParameterSpec); } @@ -282,7 +328,13 @@ * @throws XMLSignatureException */ public void initVerify(Key verificationKey) throws XMLSignatureException { - this._signatureAlgorithm.engineInitVerify(verificationKey); + initializeAlgorithm(false); + Map map=(Map)keysVerify.get(); + if (map.get(this.algorithmURI)==verificationKey) { + return; + } + map.put(this.algorithmURI,verificationKey); + this._signatureAlgorithm.engineInitVerify(verificationKey); } /** @@ -320,7 +372,7 @@ .getLogger(SignatureAlgorithm.class.getName()); } - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Init() called"); + log.log(java.util.logging.Level.FINE, "Init() called"); if (!SignatureAlgorithm._alreadyInitialized) { SignatureAlgorithm._algorithmHash = new HashMap(10); @@ -340,8 +392,8 @@ throws AlgorithmAlreadyRegisteredException,XMLSignatureException { { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass); // are we already registered? Class registeredClassClass = diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,27 +20,20 @@ */ package com.sun.org.apache.xml.internal.security.algorithms; - - import java.security.Key; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; -import org.w3c.dom.Document; import org.w3c.dom.Element; /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public abstract class SignatureAlgorithmSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(SignatureAlgorithmSpi.class.getName()); - /** * Returns the URI representation of Transformation algorithm * @@ -167,20 +160,6 @@ protected abstract void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException; - /** Field _doc */ - Document _doc = null; - - /** - * Method engineSetDocument - * - * @param doc - */ - protected void engineSetDocument(Document doc) { - this._doc = doc; - } - - /** Field _constructionElement */ - Element _constructionElement = null; /** * Method engineGetContextFromElement @@ -188,7 +167,6 @@ * @param element */ protected void engineGetContextFromElement(Element element) { - this._constructionElement = element; } /** @@ -199,4 +177,7 @@ */ protected abstract void engineSetHMACOutputLength(int HMACOutputLength) throws XMLSignatureException; + + public void reset() { + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java Wed Jul 05 16:42:37 2017 +0200 @@ -45,7 +45,7 @@ /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { @@ -74,8 +74,8 @@ public IntegrityHmac() throws XMLSignatureException { String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID); try { this._macAlgorithm = Mac.getInstance(algorithmID); @@ -99,6 +99,10 @@ throw new XMLSignatureException("empty"); } + public void reset() { + _HMACOutputLength=0; + } + /** * Proxy method for {@link java.security.Signature#verify(byte[])} * which is executed on the internal {@link java.security.Signature} object. @@ -145,7 +149,20 @@ try { this._macAlgorithm.init(secretKey); } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); + // reinstantiate Mac object to work around bug in JDK + // see: http://bugs.sun.com/view_bug.do?bug_id=4953555 + Mac mac = this._macAlgorithm; + try { + this._macAlgorithm = Mac.getInstance + (_macAlgorithm.getAlgorithm()); + } catch (Exception e) { + // this shouldn't occur, but if it does, restore previous Mac + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Mac:" + e); + } + this._macAlgorithm = mac; + } + throw new XMLSignatureException("empty", ex); } } @@ -323,7 +340,7 @@ */ protected String engineGetJCEAlgorithmString() { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()"); + log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()"); return this._macAlgorithm.getAlgorithm(); } @@ -397,7 +414,8 @@ /** * Class IntegrityHmacSHA1 * - * @author $Author: raul $ + * @author $Author: mullan $ + * @version $Revision: 1.5 $ */ public static class IntegrityHmacSHA1 extends IntegrityHmac { @@ -423,7 +441,8 @@ /** * Class IntegrityHmacSHA256 * - * @author $Author: raul $ + * @author $Author: mullan $ + * @version $Revision: 1.5 $ */ public static class IntegrityHmacSHA256 extends IntegrityHmac { @@ -449,7 +468,8 @@ /** * Class IntegrityHmacSHA384 * - * @author $Author: raul $ + * @author $Author: mullan $ + * @version $Revision: 1.5 $ */ public static class IntegrityHmacSHA384 extends IntegrityHmac { @@ -475,7 +495,8 @@ /** * Class IntegrityHmacSHA512 * - * @author $Author: raul $ + * @author $Author: mullan $ + * @version $Revision: 1.5 $ */ public static class IntegrityHmacSHA512 extends IntegrityHmac { @@ -501,7 +522,8 @@ /** * Class IntegrityHmacRIPEMD160 * - * @author $Author: raul $ + * @author $Author: mullan $ + * @version $Revision: 1.5 $ */ public static class IntegrityHmacRIPEMD160 extends IntegrityHmac { @@ -527,7 +549,8 @@ /** * Class IntegrityHmacMD5 * - * @author $Author: raul $ + * @author $Author: mullan $ + * @version $Revision: 1.5 $ */ public static class IntegrityHmacMD5 extends IntegrityHmac { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java Wed Jul 05 16:42:37 2017 +0200 @@ -3,7 +3,7 @@ * DO NOT REMOVE OR ALTER! */ /* - * Copyright 1999-2004 The Apache Software Foundation. + * Copyright 1999-2007 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.algorithms.implementations; - - import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; @@ -38,329 +36,344 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignature; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; - /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { - /** {@link java.util.logging} logging facility */ + /** {@link java.util.logging} logging facility */ static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(SignatureBaseRSA.class.getName()); + java.util.logging.Logger.getLogger + (SignatureBaseRSA.class.getName()); + + /** @inheritDoc */ + public abstract String engineGetURI(); + + /** Field algorithm */ + private java.security.Signature _signatureAlgorithm = null; + + /** + * Constructor SignatureRSA + * + * @throws XMLSignatureException + */ + public SignatureBaseRSA() throws XMLSignatureException { + + String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); + + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Created SignatureRSA using " + algorithmID); + String provider=JCEMapper.getProviderId(); + try { + if (provider==null) { + this._signatureAlgorithm = Signature.getInstance(algorithmID); + } else { + this._signatureAlgorithm = Signature.getInstance(algorithmID,provider); + } + } catch (java.security.NoSuchAlgorithmException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } catch (NoSuchProviderException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + } + + /** @inheritDoc */ + protected void engineSetParameter(AlgorithmParameterSpec params) + throws XMLSignatureException { + + try { + this._signatureAlgorithm.setParameter(params); + } catch (InvalidAlgorithmParameterException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected boolean engineVerify(byte[] signature) + throws XMLSignatureException { + + try { + return this._signatureAlgorithm.verify(signature); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineInitVerify(Key publicKey) throws XMLSignatureException { + + if (!(publicKey instanceof PublicKey)) { + String supplied = publicKey.getClass().getName(); + String needed = PublicKey.class.getName(); + Object exArgs[] = { supplied, needed }; + + throw new XMLSignatureException + ("algorithms.WrongKeyForThisOperation", exArgs); + } + + try { + this._signatureAlgorithm.initVerify((PublicKey) publicKey); + } catch (InvalidKeyException ex) { + // reinstantiate Signature object to work around bug in JDK + // see: http://bugs.sun.com/view_bug.do?bug_id=4953555 + Signature sig = this._signatureAlgorithm; + try { + this._signatureAlgorithm = Signature.getInstance + (_signatureAlgorithm.getAlgorithm()); + } catch (Exception e) { + // this shouldn't occur, but if it does, restore previous + // Signature + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e); + } + this._signatureAlgorithm = sig; + } + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected byte[] engineSign() throws XMLSignatureException { + try { + return this._signatureAlgorithm.sign(); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineInitSign(Key privateKey, SecureRandom secureRandom) + throws XMLSignatureException { + + if (!(privateKey instanceof PrivateKey)) { + String supplied = privateKey.getClass().getName(); + String needed = PrivateKey.class.getName(); + Object exArgs[] = { supplied, needed }; + + throw new XMLSignatureException + ("algorithms.WrongKeyForThisOperation", exArgs); + } + + try { + this._signatureAlgorithm.initSign + ((PrivateKey) privateKey, secureRandom); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineInitSign(Key privateKey) throws XMLSignatureException { + + if (!(privateKey instanceof PrivateKey)) { + String supplied = privateKey.getClass().getName(); + String needed = PrivateKey.class.getName(); + Object exArgs[] = { supplied, needed }; + + throw new XMLSignatureException + ("algorithms.WrongKeyForThisOperation", exArgs); + } + + try { + this._signatureAlgorithm.initSign((PrivateKey) privateKey); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineUpdate(byte[] input) throws XMLSignatureException { + try { + this._signatureAlgorithm.update(input); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineUpdate(byte input) throws XMLSignatureException { + try { + this._signatureAlgorithm.update(input); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } /** @inheritDoc */ - public abstract String engineGetURI(); - - /** Field algorithm */ - private java.security.Signature _signatureAlgorithm = null; - - /** - * Constructor SignatureRSA - * - * @throws XMLSignatureException - */ - public SignatureBaseRSA() throws XMLSignatureException { - - String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); - - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID); - String provider=JCEMapper.getProviderId(); - try { - if (provider==null) { - this._signatureAlgorithm = Signature.getInstance(algorithmID); - } else { - this._signatureAlgorithm = Signature.getInstance(algorithmID,provider); - } - } catch (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (NoSuchProviderException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + protected void engineUpdate(byte buf[], int offset, int len) + throws XMLSignatureException { + try { + this._signatureAlgorithm.update(buf, offset, len); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); } - } - - /** @inheritDoc */ - protected void engineSetParameter(AlgorithmParameterSpec params) - throws XMLSignatureException { + } - try { - this._signatureAlgorithm.setParameter(params); - } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @inheritDoc */ + protected String engineGetJCEAlgorithmString() { + return this._signatureAlgorithm.getAlgorithm(); + } - /** @inheritDoc */ - protected boolean engineVerify(byte[] signature) - throws XMLSignatureException { + /** @inheritDoc */ + protected String engineGetJCEProviderName() { + return this._signatureAlgorithm.getProvider().getName(); + } - try { - return this._signatureAlgorithm.verify(signature); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @inheritDoc */ + protected void engineSetHMACOutputLength(int HMACOutputLength) + throws XMLSignatureException { + throw new XMLSignatureException + ("algorithms.HMACOutputLengthOnlyForHMAC"); + } - /** @inheritDoc */ - protected void engineInitVerify(Key publicKey) throws XMLSignatureException { - - if (!(publicKey instanceof PublicKey)) { - String supplied = publicKey.getClass().getName(); - String needed = PublicKey.class.getName(); - Object exArgs[] = { supplied, needed }; - - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** @inheritDoc */ + protected void engineInitSign( + Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) + throws XMLSignatureException { + throw new XMLSignatureException( + "algorithms.CannotUseAlgorithmParameterSpecOnRSA"); + } - try { - this._signatureAlgorithm.initVerify((PublicKey) publicKey); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** @inheritDoc */ - protected byte[] engineSign() throws XMLSignatureException { - - try { - return this._signatureAlgorithm.sign(); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Class SignatureRSASHA1 + * + * @author $Author: mullan $ + * @version $Revision: 1.5 $ + */ + public static class SignatureRSASHA1 extends SignatureBaseRSA { - /** @inheritDoc */ - protected void engineInitSign(Key privateKey, SecureRandom secureRandom) - throws XMLSignatureException { - - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; + /** + * Constructor SignatureRSASHA1 + * + * @throws XMLSignatureException + */ + public SignatureRSASHA1() throws XMLSignatureException { + super(); + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } - - try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey, - secureRandom); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1; + } + } - /** @inheritDoc */ - protected void engineInitSign(Key privateKey) throws XMLSignatureException { - - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; - - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } - - try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Class SignatureRSASHA256 + * + * @author $Author: mullan $ + * @version $Revision: 1.5 $ + */ + public static class SignatureRSASHA256 extends SignatureBaseRSA { - /** @inheritDoc */ - protected void engineUpdate(byte[] input) throws XMLSignatureException { - - try { - this._signatureAlgorithm.update(input); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Constructor SignatureRSASHA256 + * + * @throws XMLSignatureException + */ + public SignatureRSASHA256() throws XMLSignatureException { + super(); + } - /** @inheritDoc */ - protected void engineUpdate(byte input) throws XMLSignatureException { - - try { - this._signatureAlgorithm.update(input); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** @inheritDoc */ - protected void engineUpdate(byte buf[], int offset, int len) - throws XMLSignatureException { + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256; + } + } - try { - this._signatureAlgorithm.update(buf, offset, len); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** @inheritDoc */ - protected String engineGetJCEAlgorithmString() { - return this._signatureAlgorithm.getAlgorithm(); - } - - /** @inheritDoc */ - protected String engineGetJCEProviderName() { - return this._signatureAlgorithm.getProvider().getName(); - } + /** + * Class SignatureRSASHA384 + * + * @author $Author: mullan $ + * @version $Revision: 1.5 $ + */ + public static class SignatureRSASHA384 extends SignatureBaseRSA { - /** @inheritDoc */ - protected void engineSetHMACOutputLength(int HMACOutputLength) - throws XMLSignatureException { - throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); - } + /** + * Constructor SignatureRSASHA384 + * + * @throws XMLSignatureException + */ + public SignatureRSASHA384() throws XMLSignatureException { + super(); + } - /** @inheritDoc */ - protected void engineInitSign( - Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { - throw new XMLSignatureException( - "algorithms.CannotUseAlgorithmParameterSpecOnRSA"); - } - - /** - * Class SignatureRSASHA1 - * - * @author $Author: raul $ - */ - public static class SignatureRSASHA1 extends SignatureBaseRSA { + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384; + } + } - /** - * Constructor SignatureRSASHA1 - * - * @throws XMLSignatureException - */ - public SignatureRSASHA1() throws XMLSignatureException { - super(); - } - - /** @inheritDoc */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1; - } - } - - /** - * Class SignatureRSASHA256 - * - * @author $Author: raul $ - */ - public static class SignatureRSASHA256 extends SignatureBaseRSA { + /** + * Class SignatureRSASHA512 + * + * @author $Author: mullan $ + * @version $Revision: 1.5 $ + */ + public static class SignatureRSASHA512 extends SignatureBaseRSA { - /** - * Constructor SignatureRSASHA256 - * - * @throws XMLSignatureException - */ - public SignatureRSASHA256() throws XMLSignatureException { - super(); - } + /** + * Constructor SignatureRSASHA512 + * + * @throws XMLSignatureException + */ + public SignatureRSASHA512() throws XMLSignatureException { + super(); + } - /** @inheritDoc */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256; - } - } - - /** - * Class SignatureRSASHA384 - * - * @author $Author: raul $ - */ - public static class SignatureRSASHA384 extends SignatureBaseRSA { + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512; + } + } - /** - * Constructor SignatureRSASHA384 - * - * @throws XMLSignatureException - */ - public SignatureRSASHA384() throws XMLSignatureException { - super(); - } - - /** @inheritDoc */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384; - } - } + /** + * Class SignatureRSARIPEMD160 + * + * @author $Author: mullan $ + * @version $Revision: 1.5 $ + */ + public static class SignatureRSARIPEMD160 extends SignatureBaseRSA { - /** - * Class SignatureRSASHA512 - * - * @author $Author: raul $ - */ - public static class SignatureRSASHA512 extends SignatureBaseRSA { + /** + * Constructor SignatureRSARIPEMD160 + * + * @throws XMLSignatureException + */ + public SignatureRSARIPEMD160() throws XMLSignatureException { + super(); + } - /** - * Constructor SignatureRSASHA512 - * - * @throws XMLSignatureException - */ - public SignatureRSASHA512() throws XMLSignatureException { - super(); - } - - /** @inheritDoc */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512; - } - } + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160; + } + } - /** - * Class SignatureRSARIPEMD160 - * - * @author $Author: raul $ - */ - public static class SignatureRSARIPEMD160 extends SignatureBaseRSA { - - /** - * Constructor SignatureRSARIPEMD160 - * - * @throws XMLSignatureException - */ - public SignatureRSARIPEMD160() throws XMLSignatureException { - super(); - } - - /** @inheritDoc */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160; - } - } + /** + * Class SignatureRSAMD5 + * + * @author $Author: mullan $ + * @version $Revision: 1.5 $ + */ + public static class SignatureRSAMD5 extends SignatureBaseRSA { - /** - * Class SignatureRSAMD5 - * - * @author $Author: raul $ - */ - public static class SignatureRSAMD5 extends SignatureBaseRSA { + /** + * Constructor SignatureRSAMD5 + * + * @throws XMLSignatureException + */ + public SignatureRSAMD5() throws XMLSignatureException { + super(); + } - /** - * Constructor SignatureRSAMD5 - * - * @throws XMLSignatureException - */ - public SignatureRSAMD5() throws XMLSignatureException { - super(); - } - - /** @inheritDoc */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5; - } - } + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5; + } + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,8 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.algorithms.implementations; - - import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; @@ -39,342 +37,359 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; import com.sun.org.apache.xml.internal.security.utils.Constants; - /** * - * @author $Author: vishal $ + * @author $Author: mullan $ */ public class SignatureDSA extends SignatureAlgorithmSpi { - /** {@link java.util.logging} logging facility */ + /** {@link java.util.logging} logging facility */ static java.util.logging.Logger log = java.util.logging.Logger.getLogger(SignatureDSA.class.getName()); - /** Field _URI */ - public static final String _URI = Constants.SignatureSpecNS + "dsa-sha1"; + /** Field _URI */ + public static final String _URI = Constants.SignatureSpecNS + "dsa-sha1"; - /** Field algorithm */ - private java.security.Signature _signatureAlgorithm = null; + /** Field algorithm */ + private java.security.Signature _signatureAlgorithm = null; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return SignatureDSA._URI; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return SignatureDSA._URI; + } - /** - * Constructor SignatureDSA - * - * @throws XMLSignatureException - */ - public SignatureDSA() throws XMLSignatureException { + /** + * Constructor SignatureDSA + * + * @throws XMLSignatureException + */ + public SignatureDSA() throws XMLSignatureException { - String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA._URI); - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID); + String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA._URI); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID); - try { - this._signatureAlgorithm = Signature.getInstance(algorithmID); - } catch (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } - } + String provider = JCEMapper.getProviderId(); + try { + if (provider == null) { + this._signatureAlgorithm = Signature.getInstance(algorithmID); + } else { + this._signatureAlgorithm = + Signature.getInstance(algorithmID, provider); + } + } catch (java.security.NoSuchAlgorithmException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } catch (java.security.NoSuchProviderException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + } - /** - * @inheritDoc - */ - protected void engineSetParameter(AlgorithmParameterSpec params) - throws XMLSignatureException { + /** + * @inheritDoc + */ + protected void engineSetParameter(AlgorithmParameterSpec params) + throws XMLSignatureException { - try { - this._signatureAlgorithm.setParameter(params); - } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); - } - } + try { + this._signatureAlgorithm.setParameter(params); + } catch (InvalidAlgorithmParameterException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * @inheritDoc - */ - protected boolean engineVerify(byte[] signature) + /** + * @inheritDoc + */ + protected boolean engineVerify(byte[] signature) throws XMLSignatureException { - try { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature)); + try { + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature)); - byte[] jcebytes = SignatureDSA.convertXMLDSIGtoASN1(signature); + byte[] jcebytes = SignatureDSA.convertXMLDSIGtoASN1(signature); - return this._signatureAlgorithm.verify(jcebytes); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } - } + return this._signatureAlgorithm.verify(jcebytes); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * @inheritDoc - */ - protected void engineInitVerify(Key publicKey) throws XMLSignatureException { + /** + * @inheritDoc + */ + protected void engineInitVerify(Key publicKey) throws XMLSignatureException { - if (!(publicKey instanceof PublicKey)) { - String supplied = publicKey.getClass().getName(); - String needed = PublicKey.class.getName(); - Object exArgs[] = { supplied, needed }; + if (!(publicKey instanceof PublicKey)) { + String supplied = publicKey.getClass().getName(); + String needed = PublicKey.class.getName(); + Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + throw new XMLSignatureException + ("algorithms.WrongKeyForThisOperation", exArgs); + } - try { - this._signatureAlgorithm.initVerify((PublicKey) publicKey); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** - * @inheritDoc - */ - protected byte[] engineSign() throws XMLSignatureException { + try { + this._signatureAlgorithm.initVerify((PublicKey) publicKey); + } catch (InvalidKeyException ex) { + // reinstantiate Signature object to work around bug in JDK + // see: http://bugs.sun.com/view_bug.do?bug_id=4953555 + Signature sig = this._signatureAlgorithm; + try { + this._signatureAlgorithm = Signature.getInstance + (_signatureAlgorithm.getAlgorithm()); + } catch (Exception e) { + // this shouldn't occur, but if it does, restore previous + // Signature + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e); + } + this._signatureAlgorithm = sig; + } + throw new XMLSignatureException("empty", ex); + } + } - try { - byte jcebytes[] = this._signatureAlgorithm.sign(); + /** + * @inheritDoc + */ + protected byte[] engineSign() throws XMLSignatureException { + + try { + byte jcebytes[] = this._signatureAlgorithm.sign(); - return SignatureDSA.convertASN1toXMLDSIG(jcebytes); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + return SignatureDSA.convertASN1toXMLDSIG(jcebytes); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * @inheritDoc - */ - protected void engineInitSign(Key privateKey, SecureRandom secureRandom) + /** + * @inheritDoc + */ + protected void engineInitSign(Key privateKey, SecureRandom secureRandom) throws XMLSignatureException { - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; + if (!(privateKey instanceof PrivateKey)) { + String supplied = privateKey.getClass().getName(); + String needed = PrivateKey.class.getName(); + Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + throw new XMLSignatureException + ("algorithms.WrongKeyForThisOperation", exArgs); + } - try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey, + try { + this._signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * @inheritDoc - */ - protected void engineInitSign(Key privateKey) throws XMLSignatureException { + /** + * @inheritDoc + */ + protected void engineInitSign(Key privateKey) throws XMLSignatureException { - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; + if (!(privateKey instanceof PrivateKey)) { + String supplied = privateKey.getClass().getName(); + String needed = PrivateKey.class.getName(); + Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + throw new XMLSignatureException + ("algorithms.WrongKeyForThisOperation", exArgs); + } - try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } + try { + this._signatureAlgorithm.initSign((PrivateKey) privateKey); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * @inheritDoc - */ - protected void engineUpdate(byte[] input) throws XMLSignatureException { - - try { - this._signatureAlgorithm.update(input); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * @inheritDoc + */ + protected void engineUpdate(byte[] input) throws XMLSignatureException { + try { + this._signatureAlgorithm.update(input); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * @inheritDoc - */ - protected void engineUpdate(byte input) throws XMLSignatureException { - - try { - this._signatureAlgorithm.update(input); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * @inheritDoc + */ + protected void engineUpdate(byte input) throws XMLSignatureException { + try { + this._signatureAlgorithm.update(input); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * @inheritDoc - */ - protected void engineUpdate(byte buf[], int offset, int len) - throws XMLSignatureException { - - try { - this._signatureAlgorithm.update(buf, offset, len); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * @inheritDoc + */ + protected void engineUpdate(byte buf[], int offset, int len) + throws XMLSignatureException { + try { + this._signatureAlgorithm.update(buf, offset, len); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * Method engineGetJCEAlgorithmString - * - * @inheritDoc - */ - protected String engineGetJCEAlgorithmString() { - return this._signatureAlgorithm.getAlgorithm(); - } + /** + * Method engineGetJCEAlgorithmString + * + * @inheritDoc + */ + protected String engineGetJCEAlgorithmString() { + return this._signatureAlgorithm.getAlgorithm(); + } - /** - * Method engineGetJCEProviderName - * - * @inheritDoc - */ - protected String engineGetJCEProviderName() { - return this._signatureAlgorithm.getProvider().getName(); - } - + /** + * Method engineGetJCEProviderName + * + * @inheritDoc + */ + protected String engineGetJCEProviderName() { + return this._signatureAlgorithm.getProvider().getName(); + } - /** - * Converts an ASN.1 DSA value to a XML Signature DSA Value. - * - * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value - * pairs; the XML Signature requires the core BigInteger values. - * - * @param asn1Bytes - * @return the decode bytes - * - * @throws IOException - * @see 6.4.1 DSA - */ - private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) + /** + * Converts an ASN.1 DSA value to a XML Signature DSA Value. + * + * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value + * pairs; the XML Signature requires the core BigInteger values. + * + * @param asn1Bytes + * @return the decode bytes + * + * @throws IOException + * @see 6.4.1 DSA + */ + private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException { - byte rLength = asn1Bytes[3]; - int i; + byte rLength = asn1Bytes[3]; + int i; - for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--); + for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--); - byte sLength = asn1Bytes[5 + rLength]; - int j; + byte sLength = asn1Bytes[5 + rLength]; + int j; - for (j = sLength; + for (j = sLength; (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--); - if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2) + if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2) || (asn1Bytes[2] != 2) || (i > 20) || (asn1Bytes[4 + rLength] != 2) || (j > 20)) { - throw new IOException("Invalid ASN.1 format of DSA signature"); - } - byte xmldsigBytes[] = new byte[40]; + throw new IOException("Invalid ASN.1 format of DSA signature"); + } + byte xmldsigBytes[] = new byte[40]; - System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i, + System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i, i); - System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes, + System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes, 40 - j, j); - return xmldsigBytes; - } + return xmldsigBytes; + } - /** - * Converts a XML Signature DSA Value to an ASN.1 DSA value. - * - * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value - * pairs; the XML Signature requires the core BigInteger values. - * - * @param xmldsigBytes - * @return the encoded ASN.1 bytes - * - * @throws IOException - * @see 6.4.1 DSA - */ - private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) + /** + * Converts a XML Signature DSA Value to an ASN.1 DSA value. + * + * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value + * pairs; the XML Signature requires the core BigInteger values. + * + * @param xmldsigBytes + * @return the encoded ASN.1 bytes + * + * @throws IOException + * @see 6.4.1 DSA + */ + private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException { - if (xmldsigBytes.length != 40) { - throw new IOException("Invalid XMLDSIG format of DSA signature"); - } + if (xmldsigBytes.length != 40) { + throw new IOException("Invalid XMLDSIG format of DSA signature"); + } - int i; + int i; - for (i = 20; (i > 0) && (xmldsigBytes[20 - i] == 0); i--); + for (i = 20; (i > 0) && (xmldsigBytes[20 - i] == 0); i--); - int j = i; + int j = i; - if (xmldsigBytes[20 - i] < 0) { + if (xmldsigBytes[20 - i] < 0) { j += 1; - } + } - int k; + int k; - for (k = 20; (k > 0) && (xmldsigBytes[40 - k] == 0); k--); + for (k = 20; (k > 0) && (xmldsigBytes[40 - k] == 0); k--); - int l = k; + int l = k; - if (xmldsigBytes[40 - k] < 0) { - l += 1; - } + if (xmldsigBytes[40 - k] < 0) { + l += 1; + } - byte asn1Bytes[] = new byte[6 + j + l]; + byte asn1Bytes[] = new byte[6 + j + l]; - asn1Bytes[0] = 48; - asn1Bytes[1] = (byte) (4 + j + l); - asn1Bytes[2] = 2; - asn1Bytes[3] = (byte) j; + asn1Bytes[0] = 48; + asn1Bytes[1] = (byte) (4 + j + l); + asn1Bytes[2] = 2; + asn1Bytes[3] = (byte) j; - System.arraycopy(xmldsigBytes, 20 - i, asn1Bytes, (4 + j) - i, i); + System.arraycopy(xmldsigBytes, 20 - i, asn1Bytes, (4 + j) - i, i); - asn1Bytes[4 + j] = 2; - asn1Bytes[5 + j] = (byte) l; + asn1Bytes[4 + j] = 2; + asn1Bytes[5 + j] = (byte) l; - System.arraycopy(xmldsigBytes, 40 - k, asn1Bytes, (6 + j + l) - k, k); + System.arraycopy(xmldsigBytes, 40 - k, asn1Bytes, (6 + j + l) - k, k); - return asn1Bytes; - } + return asn1Bytes; + } - /** - * Method engineSetHMACOutputLength - * - * @param HMACOutputLength - * @throws XMLSignatureException - */ - protected void engineSetHMACOutputLength(int HMACOutputLength) - throws XMLSignatureException { - throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); - } + /** + * Method engineSetHMACOutputLength + * + * @param HMACOutputLength + * @throws XMLSignatureException + */ + protected void engineSetHMACOutputLength(int HMACOutputLength) + throws XMLSignatureException { + throw new XMLSignatureException( + "algorithms.HMACOutputLengthOnlyForHMAC"); + } - /** - * Method engineInitSign - * - * @param signingKey - * @param algorithmParameterSpec - * @throws XMLSignatureException - */ - protected void engineInitSign( - Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { - throw new XMLSignatureException( - "algorithms.CannotUseAlgorithmParameterSpecOnDSA"); - } + /** + * Method engineInitSign + * + * @param signingKey + * @param algorithmParameterSpec + * @throws XMLSignatureException + */ + protected void engineInitSign( + Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) + throws XMLSignatureException { + throw new XMLSignatureException( + "algorithms.CannotUseAlgorithmParameterSpecOnDSA"); + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,384 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/* + * Copyright 1999-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.sun.org.apache.xml.internal.security.algorithms.implementations; + + + +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.NoSuchProviderException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.Signature; +import java.security.SignatureException; +import java.security.spec.AlgorithmParameterSpec; + +import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper; +import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi; +import com.sun.org.apache.xml.internal.security.signature.XMLSignature; +import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; +import com.sun.org.apache.xml.internal.security.utils.Base64; + + +/** + * + * @author $Author: mullan $ + */ +public abstract class SignatureECDSA extends SignatureAlgorithmSpi { + + /** {@link java.util.logging} logging facility */ + static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SignatureECDSA.class.getName()); + + /** @inheritDoc */ + public abstract String engineGetURI(); + + /** Field algorithm */ + private java.security.Signature _signatureAlgorithm = null; + + /** + * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value. + * + * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value + * pairs; the XML Signature requires the core BigInteger values. + * + * @param asn1Bytes + * @return the decode bytes + * + * @throws IOException + * @see 6.4.1 DSA + * @see 3.3. ECDSA Signatures + */ + private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) + throws IOException { + + byte rLength = asn1Bytes[3]; + int i; + + for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--); + + byte sLength = asn1Bytes[5 + rLength]; + int j; + + for (j = sLength; + (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--); + + if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2) + || (asn1Bytes[2] != 2) || (i > 24) + || (asn1Bytes[4 + rLength] != 2) || (j > 24)) { + throw new IOException("Invalid ASN.1 format of ECDSA signature"); + } + byte xmldsigBytes[] = new byte[48]; + + System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 24 - i, + i); + System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes, + 48 - j, j); + + return xmldsigBytes; + } + + /** + * Converts a XML Signature ECDSA Value to an ASN.1 DSA value. + * + * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value + * pairs; the XML Signature requires the core BigInteger values. + * + * @param xmldsigBytes + * @return the encoded ASN.1 bytes + * + * @throws IOException + * @see 6.4.1 DSA + * @see 3.3. ECDSA Signatures + */ + private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) + throws IOException { + + if (xmldsigBytes.length != 48) { + throw new IOException("Invalid XMLDSIG format of ECDSA signature"); + } + + int i; + + for (i = 24; (i > 0) && (xmldsigBytes[24 - i] == 0); i--); + + int j = i; + + if (xmldsigBytes[24 - i] < 0) { + j += 1; + } + + int k; + + for (k = 24; (k > 0) && (xmldsigBytes[48 - k] == 0); k--); + + int l = k; + + if (xmldsigBytes[48 - k] < 0) { + l += 1; + } + + byte asn1Bytes[] = new byte[6 + j + l]; + + asn1Bytes[0] = 48; + asn1Bytes[1] = (byte) (4 + j + l); + asn1Bytes[2] = 2; + asn1Bytes[3] = (byte) j; + + System.arraycopy(xmldsigBytes, 24 - i, asn1Bytes, (4 + j) - i, i); + + asn1Bytes[4 + j] = 2; + asn1Bytes[5 + j] = (byte) l; + + System.arraycopy(xmldsigBytes, 48 - k, asn1Bytes, (6 + j + l) - k, k); + + return asn1Bytes; + } + + /** + * Constructor SignatureRSA + * + * @throws XMLSignatureException + */ + public SignatureECDSA() throws XMLSignatureException { + + String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); + + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID); + String provider=JCEMapper.getProviderId(); + try { + if (provider==null) { + this._signatureAlgorithm = Signature.getInstance(algorithmID); + } else { + this._signatureAlgorithm = Signature.getInstance(algorithmID,provider); + } + } catch (java.security.NoSuchAlgorithmException ex) { + Object[] exArgs = { algorithmID, + ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } catch (NoSuchProviderException ex) { + Object[] exArgs = { algorithmID, + ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + } + + /** @inheritDoc */ + protected void engineSetParameter(AlgorithmParameterSpec params) + throws XMLSignatureException { + + try { + this._signatureAlgorithm.setParameter(params); + } catch (InvalidAlgorithmParameterException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected boolean engineVerify(byte[] signature) + throws XMLSignatureException { + + try { + byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature); + + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature)); + + return this._signatureAlgorithm.verify(jcebytes); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineInitVerify(Key publicKey) throws XMLSignatureException { + + if (!(publicKey instanceof PublicKey)) { + String supplied = publicKey.getClass().getName(); + String needed = PublicKey.class.getName(); + Object exArgs[] = { supplied, needed }; + + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", + exArgs); + } + + try { + this._signatureAlgorithm.initVerify((PublicKey) publicKey); + } catch (InvalidKeyException ex) { + // reinstantiate Signature object to work around bug in JDK + // see: http://bugs.sun.com/view_bug.do?bug_id=4953555 + Signature sig = this._signatureAlgorithm; + try { + this._signatureAlgorithm = Signature.getInstance + (_signatureAlgorithm.getAlgorithm()); + } catch (Exception e) { + // this shouldn't occur, but if it does, restore previous + // Signature + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e); + } + this._signatureAlgorithm = sig; + } + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected byte[] engineSign() throws XMLSignatureException { + + try { + byte jcebytes[] = this._signatureAlgorithm.sign(); + + return SignatureECDSA.convertASN1toXMLDSIG(jcebytes); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineInitSign(Key privateKey, SecureRandom secureRandom) + throws XMLSignatureException { + + if (!(privateKey instanceof PrivateKey)) { + String supplied = privateKey.getClass().getName(); + String needed = PrivateKey.class.getName(); + Object exArgs[] = { supplied, needed }; + + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", + exArgs); + } + + try { + this._signatureAlgorithm.initSign((PrivateKey) privateKey, + secureRandom); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineInitSign(Key privateKey) throws XMLSignatureException { + + if (!(privateKey instanceof PrivateKey)) { + String supplied = privateKey.getClass().getName(); + String needed = PrivateKey.class.getName(); + Object exArgs[] = { supplied, needed }; + + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", + exArgs); + } + + try { + this._signatureAlgorithm.initSign((PrivateKey) privateKey); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineUpdate(byte[] input) throws XMLSignatureException { + + try { + this._signatureAlgorithm.update(input); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineUpdate(byte input) throws XMLSignatureException { + + try { + this._signatureAlgorithm.update(input); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineUpdate(byte buf[], int offset, int len) + throws XMLSignatureException { + + try { + this._signatureAlgorithm.update(buf, offset, len); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected String engineGetJCEAlgorithmString() { + return this._signatureAlgorithm.getAlgorithm(); + } + + /** @inheritDoc */ + protected String engineGetJCEProviderName() { + return this._signatureAlgorithm.getProvider().getName(); + } + + /** @inheritDoc */ + protected void engineSetHMACOutputLength(int HMACOutputLength) + throws XMLSignatureException { + throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); + } + + /** @inheritDoc */ + protected void engineInitSign( + Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) + throws XMLSignatureException { + throw new XMLSignatureException( + "algorithms.CannotUseAlgorithmParameterSpecOnRSA"); + } + + /** + * Class SignatureRSASHA1 + * + * @author $Author: mullan $ + * @version $Revision: 1.2 $ + */ + public static class SignatureECDSASHA1 extends SignatureECDSA { + + /** + * Constructor SignatureRSASHA1 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA1() throws XMLSignatureException { + super(); + } + + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1; + } + } + +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java Wed Jul 05 16:42:37 2017 +0200 @@ -3,7 +3,7 @@ * DO NOT REMOVE OR ALTER! */ /* - * Copyright 1999-2004 The Apache Software Foundation. + * Copyright 1999-2008 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.c14n; - - import java.io.ByteArrayInputStream; import java.io.OutputStream; import java.util.HashMap; @@ -37,318 +35,326 @@ import org.w3c.dom.NodeList; import org.xml.sax.InputSource; - /** * - * * @author Christian Geuer-Pollmann */ public class Canonicalizer { - //J- - /** The output encoding of canonicalized data */ - public static final String ENCODING = "UTF8"; - + /** The output encoding of canonicalized data */ + public static final String ENCODING = "UTF8"; - /** - * XPath Expresion for selecting every node and continuos comments joined in only one node + /** + * XPath Expresion for selecting every node and continuous comments joined + * in only one node */ - public static final String XPATH_C14N_WITH_COMMENTS_SINGLE_NODE = "(.//. | .//@* | .//namespace::*)"; + public static final String XPATH_C14N_WITH_COMMENTS_SINGLE_NODE = + "(.//. | .//@* | .//namespace::*)"; - - /** + /** * The URL defined in XML-SEC Rec for inclusive c14n without comments. */ - public static final String ALGO_ID_C14N_OMIT_COMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; - /** - * The URL defined in XML-SEC Rec for inclusive c14n with comments. - */ - public static final String ALGO_ID_C14N_WITH_COMMENTS = ALGO_ID_C14N_OMIT_COMMENTS + "#WithComments"; - /** - * The URL defined in XML-SEC Rec for exclusive c14n without comments. - */ - public static final String ALGO_ID_C14N_EXCL_OMIT_COMMENTS = "http://www.w3.org/2001/10/xml-exc-c14n#"; - /** - * The URL defined in XML-SEC Rec for exclusive c14n with comments. - */ - public static final String ALGO_ID_C14N_EXCL_WITH_COMMENTS = ALGO_ID_C14N_EXCL_OMIT_COMMENTS + "WithComments"; - - static boolean _alreadyInitialized = false; - static Map _canonicalizerHash = null; - - protected CanonicalizerSpi canonicalizerSpi = null; - //J+ + public static final String ALGO_ID_C14N_OMIT_COMMENTS = + "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; + /** + * The URL defined in XML-SEC Rec for inclusive c14n with comments. + */ + public static final String ALGO_ID_C14N_WITH_COMMENTS = + ALGO_ID_C14N_OMIT_COMMENTS + "#WithComments"; + /** + * The URL defined in XML-SEC Rec for exclusive c14n without comments. + */ + public static final String ALGO_ID_C14N_EXCL_OMIT_COMMENTS = + "http://www.w3.org/2001/10/xml-exc-c14n#"; + /** + * The URL defined in XML-SEC Rec for exclusive c14n with comments. + */ + public static final String ALGO_ID_C14N_EXCL_WITH_COMMENTS = + ALGO_ID_C14N_EXCL_OMIT_COMMENTS + "WithComments"; + /** + * The URI for inclusive c14n 1.1 without comments. + */ + public static final String ALGO_ID_C14N11_OMIT_COMMENTS = + "http://www.w3.org/2006/12/xml-c14n11"; + /** + * The URI for inclusive c14n 1.1 with comments. + */ + public static final String ALGO_ID_C14N11_WITH_COMMENTS = + ALGO_ID_C14N11_OMIT_COMMENTS + "#WithComments"; - /** - * Method init - * - */ - public static void init() { + static boolean _alreadyInitialized = false; + static Map _canonicalizerHash = null; + + protected CanonicalizerSpi canonicalizerSpi = null; + + /** + * Method init + * + */ + public static void init() { - if (!Canonicalizer._alreadyInitialized) { - Canonicalizer._canonicalizerHash = new HashMap(10); - Canonicalizer._alreadyInitialized = true; - } - } + if (!Canonicalizer._alreadyInitialized) { + Canonicalizer._canonicalizerHash = new HashMap(10); + Canonicalizer._alreadyInitialized = true; + } + } - /** - * Constructor Canonicalizer - * - * @param algorithmURI - * @throws InvalidCanonicalizerException - */ - private Canonicalizer(String algorithmURI) + /** + * Constructor Canonicalizer + * + * @param algorithmURI + * @throws InvalidCanonicalizerException + */ + private Canonicalizer(String algorithmURI) throws InvalidCanonicalizerException { - try { - Class implementingClass = getImplementingClass(algorithmURI); + try { + Class implementingClass = getImplementingClass(algorithmURI); - this.canonicalizerSpi = - (CanonicalizerSpi) implementingClass.newInstance(); - this.canonicalizerSpi.reset=true; - } catch (Exception e) { - Object exArgs[] = { algorithmURI }; + this.canonicalizerSpi = + (CanonicalizerSpi) implementingClass.newInstance(); + this.canonicalizerSpi.reset=true; + } catch (Exception e) { + Object exArgs[] = { algorithmURI }; - throw new InvalidCanonicalizerException( - "signature.Canonicalizer.UnknownCanonicalizer", exArgs); - } - } + throw new InvalidCanonicalizerException( + "signature.Canonicalizer.UnknownCanonicalizer", exArgs); + } + } - /** - * Method getInstance - * - * @param algorithmURI - * @return a Conicicalizer instance ready for the job - * @throws InvalidCanonicalizerException - */ - public static final Canonicalizer getInstance(String algorithmURI) + /** + * Method getInstance + * + * @param algorithmURI + * @return a Conicicalizer instance ready for the job + * @throws InvalidCanonicalizerException + */ + public static final Canonicalizer getInstance(String algorithmURI) throws InvalidCanonicalizerException { - Canonicalizer c14nizer = new Canonicalizer(algorithmURI); + Canonicalizer c14nizer = new Canonicalizer(algorithmURI); - return c14nizer; - } + return c14nizer; + } - /** - * Method register - * - * @param algorithmURI - * @param implementingClass - * @throws AlgorithmAlreadyRegisteredException - */ - public static void register(String algorithmURI, String implementingClass) + /** + * Method register + * + * @param algorithmURI + * @param implementingClass + * @throws AlgorithmAlreadyRegisteredException + */ + public static void register(String algorithmURI, String implementingClass) throws AlgorithmAlreadyRegisteredException { - // check whether URI is already registered - Class registeredClass = getImplementingClass(algorithmURI); + // check whether URI is already registered + Class registeredClass = getImplementingClass(algorithmURI); - if (registeredClass != null) { - Object exArgs[] = { algorithmURI, registeredClass }; + if (registeredClass != null) { + Object exArgs[] = { algorithmURI, registeredClass }; - throw new AlgorithmAlreadyRegisteredException( - "algorithm.alreadyRegistered", exArgs); - } + throw new AlgorithmAlreadyRegisteredException( + "algorithm.alreadyRegistered", exArgs); + } - try { - _canonicalizerHash.put(algorithmURI, Class.forName(implementingClass)); + try { + _canonicalizerHash.put(algorithmURI, Class.forName(implementingClass)); } catch (ClassNotFoundException e) { - throw new RuntimeException("c14n class not found"); + throw new RuntimeException("c14n class not found"); } - } + } - /** - * Method getURI - * - * @return the URI defined for this c14n instance. - */ - public final String getURI() { - return this.canonicalizerSpi.engineGetURI(); - } + /** + * Method getURI + * + * @return the URI defined for this c14n instance. + */ + public final String getURI() { + return this.canonicalizerSpi.engineGetURI(); + } - /** - * Method getIncludeComments - * - * @return true if the c14n respect the comments. - */ - public boolean getIncludeComments() { - return this.canonicalizerSpi.engineGetIncludeComments(); - } + /** + * Method getIncludeComments + * + * @return true if the c14n respect the comments. + */ + public boolean getIncludeComments() { + return this.canonicalizerSpi.engineGetIncludeComments(); + } - /** - * This method tries to canonicalize the given bytes. It's possible to even - * canonicalize non-wellformed sequences if they are well-formed after being - * wrapped with a >a<...>/a<. - * - * @param inputBytes - * @return the result of the conicalization. - * @throws CanonicalizationException - * @throws java.io.IOException - * @throws javax.xml.parsers.ParserConfigurationException - * @throws org.xml.sax.SAXException - */ - public byte[] canonicalize(byte[] inputBytes) + /** + * This method tries to canonicalize the given bytes. It's possible to even + * canonicalize non-wellformed sequences if they are well-formed after being + * wrapped with a >a<...>/a<. + * + * @param inputBytes + * @return the result of the conicalization. + * @throws CanonicalizationException + * @throws java.io.IOException + * @throws javax.xml.parsers.ParserConfigurationException + * @throws org.xml.sax.SAXException + */ + public byte[] canonicalize(byte[] inputBytes) throws javax.xml.parsers.ParserConfigurationException, java.io.IOException, org.xml.sax.SAXException, CanonicalizationException { - ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes); - InputSource in = new InputSource(bais); - DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes); + InputSource in = new InputSource(bais); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); - dfactory.setNamespaceAware(true); + dfactory.setNamespaceAware(true); - // needs to validate for ID attribute nomalization - dfactory.setValidating(true); + // needs to validate for ID attribute nomalization + dfactory.setValidating(true); - DocumentBuilder db = dfactory.newDocumentBuilder(); + DocumentBuilder db = dfactory.newDocumentBuilder(); - /* - * for some of the test vectors from the specification, - * there has to be a validatin parser for ID attributes, default - * attribute values, NMTOKENS, etc. - * Unfortunaltely, the test vectors do use different DTDs or - * even no DTD. So Xerces 1.3.1 fires many warnings about using - * ErrorHandlers. - * - * Text from the spec: - * - * The input octet stream MUST contain a well-formed XML document, - * but the input need not be validated. However, the attribute - * value normalization and entity reference resolution MUST be - * performed in accordance with the behaviors of a validating - * XML processor. As well, nodes for default attributes (declared - * in the ATTLIST with an AttValue but not specified) are created - * in each element. Thus, the declarations in the document type - * declaration are used to help create the canonical form, even - * though the document type declaration is not retained in the - * canonical form. - * - */ - db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils - .IgnoreAllErrorHandler()); + /* + * for some of the test vectors from the specification, + * there has to be a validatin parser for ID attributes, default + * attribute values, NMTOKENS, etc. + * Unfortunaltely, the test vectors do use different DTDs or + * even no DTD. So Xerces 1.3.1 fires many warnings about using + * ErrorHandlers. + * + * Text from the spec: + * + * The input octet stream MUST contain a well-formed XML document, + * but the input need not be validated. However, the attribute + * value normalization and entity reference resolution MUST be + * performed in accordance with the behaviors of a validating + * XML processor. As well, nodes for default attributes (declared + * in the ATTLIST with an AttValue but not specified) are created + * in each element. Thus, the declarations in the document type + * declaration are used to help create the canonical form, even + * though the document type declaration is not retained in the + * canonical form. + * + */ + db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils + .IgnoreAllErrorHandler()); - Document document = db.parse(in); - byte result[] = this.canonicalizeSubtree(document); + Document document = db.parse(in); + byte result[] = this.canonicalizeSubtree(document); - return result; - } + return result; + } - /** - * Canonicalizes the subtree rooted by node. - * - * @param node The node to canicalize - * @return the result of the c14n. - * - * @throws CanonicalizationException - */ - public byte[] canonicalizeSubtree(Node node) + /** + * Canonicalizes the subtree rooted by node. + * + * @param node The node to canicalize + * @return the result of the c14n. + * + * @throws CanonicalizationException + */ + public byte[] canonicalizeSubtree(Node node) throws CanonicalizationException { - return this.canonicalizerSpi.engineCanonicalizeSubTree(node); - } + return this.canonicalizerSpi.engineCanonicalizeSubTree(node); + } - /** - * Canonicalizes the subtree rooted by node. - * - * @param node - * @param inclusiveNamespaces - * @return the result of the c14n. - * @throws CanonicalizationException - */ - public byte[] canonicalizeSubtree(Node node, String inclusiveNamespaces) + /** + * Canonicalizes the subtree rooted by node. + * + * @param node + * @param inclusiveNamespaces + * @return the result of the c14n. + * @throws CanonicalizationException + */ + public byte[] canonicalizeSubtree(Node node, String inclusiveNamespaces) throws CanonicalizationException { - return this.canonicalizerSpi.engineCanonicalizeSubTree(node, + return this.canonicalizerSpi.engineCanonicalizeSubTree(node, inclusiveNamespaces); - } + } - /** - * Canonicalizes an XPath node set. The xpathNodeSet is treated - * as a list of XPath nodes, not as a list of subtrees. - * - * @param xpathNodeSet - * @return the result of the c14n. - * @throws CanonicalizationException - */ - public byte[] canonicalizeXPathNodeSet(NodeList xpathNodeSet) + /** + * Canonicalizes an XPath node set. The xpathNodeSet is treated + * as a list of XPath nodes, not as a list of subtrees. + * + * @param xpathNodeSet + * @return the result of the c14n. + * @throws CanonicalizationException + */ + public byte[] canonicalizeXPathNodeSet(NodeList xpathNodeSet) throws CanonicalizationException { - return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet); - } + return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet); + } - /** - * Canonicalizes an XPath node set. The xpathNodeSet is treated - * as a list of XPath nodes, not as a list of subtrees. - * - * @param xpathNodeSet - * @param inclusiveNamespaces - * @return the result of the c14n. - * @throws CanonicalizationException - */ - public byte[] canonicalizeXPathNodeSet( + /** + * Canonicalizes an XPath node set. The xpathNodeSet is treated + * as a list of XPath nodes, not as a list of subtrees. + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return the result of the c14n. + * @throws CanonicalizationException + */ + public byte[] canonicalizeXPathNodeSet( NodeList xpathNodeSet, String inclusiveNamespaces) throws CanonicalizationException { - return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, + return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces); - } + } - /** - * Canonicalizes an XPath node set. - * - * @param xpathNodeSet - * @return the result of the c14n. - * @throws CanonicalizationException - */ - public byte[] canonicalizeXPathNodeSet(Set xpathNodeSet) + /** + * Canonicalizes an XPath node set. + * + * @param xpathNodeSet + * @return the result of the c14n. + * @throws CanonicalizationException + */ + public byte[] canonicalizeXPathNodeSet(Set xpathNodeSet) throws CanonicalizationException { - return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet); - } + return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet); + } - /** - * Canonicalizes an XPath node set. - * - * @param xpathNodeSet - * @param inclusiveNamespaces - * @return the result of the c14n. - * @throws CanonicalizationException - */ - public byte[] canonicalizeXPathNodeSet( - Set xpathNodeSet, String inclusiveNamespaces) - throws CanonicalizationException { - return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, - inclusiveNamespaces); - } + /** + * Canonicalizes an XPath node set. + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return the result of the c14n. + * @throws CanonicalizationException + */ + public byte[] canonicalizeXPathNodeSet(Set xpathNodeSet, + String inclusiveNamespaces) throws CanonicalizationException { + return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, + inclusiveNamespaces); + } - /** - * Sets the writter where the cannocalization ends. ByteArrayOutputStream if - * none is setted. - * @param os - */ - public void setWriter(OutputStream os) { - this.canonicalizerSpi.setWriter(os); - } + /** + * Sets the writer where the canonicalization ends. ByteArrayOutputStream + * if none is set. + * @param os + */ + public void setWriter(OutputStream os) { + this.canonicalizerSpi.setWriter(os); + } - /** - * Returns the name of the implementing {@link CanonicalizerSpi} class - * - * @return the name of the implementing {@link CanonicalizerSpi} class - */ - public String getImplementingCanonicalizerClass() { - return this.canonicalizerSpi.getClass().getName(); - } + /** + * Returns the name of the implementing {@link CanonicalizerSpi} class + * + * @return the name of the implementing {@link CanonicalizerSpi} class + */ + public String getImplementingCanonicalizerClass() { + return this.canonicalizerSpi.getClass().getName(); + } - /** - * Method getImplementingClass - * - * @param URI - * @return the name of the class that implements the give URI - */ - private static Class getImplementingClass(String URI) { - return (Class) _canonicalizerHash.get(URI); - } + /** + * Method getImplementingClass + * + * @param URI + * @return the name of the class that implements the given URI + */ + private static Class getImplementingClass(String URI) { + return (Class) _canonicalizerHash.get(URI); + } - /** - * Set the canonicalizator behaviour to not reset. - * - */ - public void notReset() { - this.canonicalizerSpi.reset=false; - } + /** + * Set the canonicalizer behaviour to not reset. + */ + public void notReset() { + this.canonicalizerSpi.reset = false; + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -21,17 +20,17 @@ */ package com.sun.org.apache.xml.internal.security.c14n.helper; - - import com.sun.org.apache.xml.internal.security.utils.Constants; import org.w3c.dom.Attr; - +import java.io.Serializable; +import java.util.Comparator; /** * Compares two attributes based on the C14n specification. * *
    - *
  • Namespace nodes have a lesser document order position than attribute nodes. + *
  • Namespace nodes have a lesser document order position than attribute + * nodes. *
  • An element's namespace nodes are sorted lexicographically by * local name (the default namespace node, if one exists, has no * local name and is therefore lexicographically least). @@ -40,104 +39,89 @@ * key (an empty namespace URI is lexicographically least). *
* - * $todo$ Should we implement java.util.Comparator and import java.util.Arrays to use Arrays.sort(intarray); * @author Christian Geuer-Pollmann */ -public class AttrCompare implements java.util.Comparator { +public class AttrCompare implements Comparator, Serializable { - private final int ATTR0_BEFORE_ATTR1 = -1; - private final int ATTR1_BEFORE_ATTR0 = 1; + private final static long serialVersionUID = -7113259629930576230L; + private final static int ATTR0_BEFORE_ATTR1 = -1; + private final static int ATTR1_BEFORE_ATTR0 = 1; + private final static String XMLNS=Constants.NamespaceSpecNS; - private final static String XMLNS=Constants.NamespaceSpecNS; - /** - * Compares two attributes based on the C14n specification. - * - *
    - *
  • Namespace nodes have a lesser document order position than attribute nodes. - *
  • An element's namespace nodes are sorted lexicographically by - * local name (the default namespace node, if one exists, has no - * local name and is therefore lexicographically least). - *
  • An element's attribute nodes are sorted lexicographically with - * namespace URI as the primary key and local name as the secondary - * key (an empty namespace URI is lexicographically least). - *
- * - * @param obj0 casted Attr - * @param obj1 casted Attr - * @return returns a negative integer, zero, or a positive integer as obj0 is less than, equal to, or greater than obj1 - * - */ - public int compare(Object obj0, Object obj1) { + /** + * Compares two attributes based on the C14n specification. + * + *
    + *
  • Namespace nodes have a lesser document order position than + * attribute nodes. + *
  • An element's namespace nodes are sorted lexicographically by + * local name (the default namespace node, if one exists, has no + * local name and is therefore lexicographically least). + *
  • An element's attribute nodes are sorted lexicographically with + * namespace URI as the primary key and local name as the secondary + * key (an empty namespace URI is lexicographically least). + *
+ * + * @param obj0 casted Attr + * @param obj1 casted Attr + * @return returns a negative integer, zero, or a positive integer as + * obj0 is less than, equal to, or greater than obj1 + * + */ + public int compare(Object obj0, Object obj1) { - Attr attr0 = (Attr) obj0; - Attr attr1 = (Attr) obj1; - String namespaceURI0 = attr0.getNamespaceURI(); - String namespaceURI1 = attr1.getNamespaceURI(); + Attr attr0 = (Attr) obj0; + Attr attr1 = (Attr) obj1; + String namespaceURI0 = attr0.getNamespaceURI(); + String namespaceURI1 = attr1.getNamespaceURI(); - boolean isNamespaceAttr0 = - XMLNS.equals(namespaceURI0); - boolean isNamespaceAttr1 = - XMLNS.equals(namespaceURI1); + boolean isNamespaceAttr0 = XMLNS==namespaceURI0; + boolean isNamespaceAttr1 = XMLNS==namespaceURI1; - if (isNamespaceAttr0) { - if (isNamespaceAttr1) { - - // both are namespaces - String localname0 = attr0.getLocalName(); - String localname1 = attr1.getLocalName(); + if (isNamespaceAttr0) { + if (isNamespaceAttr1) { + // both are namespaces + String localname0 = attr0.getLocalName(); + String localname1 = attr1.getLocalName(); - if (localname0.equals("xmlns")) { - localname0 = ""; - } + if (localname0.equals("xmlns")) { + localname0 = ""; + } - if (localname1.equals("xmlns")) { - localname1 = ""; - } + if (localname1.equals("xmlns")) { + localname1 = ""; + } - return localname0.compareTo(localname1); - } - // attr0 is a namespace, attr1 is not - return ATTR0_BEFORE_ATTR1; + return localname0.compareTo(localname1); + } + // attr0 is a namespace, attr1 is not + return ATTR0_BEFORE_ATTR1; + } - } - if (isNamespaceAttr1) { - + if (isNamespaceAttr1) { // attr1 is a namespace, attr0 is not return ATTR1_BEFORE_ATTR0; - } - - // none is a namespae + } - if (namespaceURI0 == null) { - if (namespaceURI1 == null) { - /* - String localName0 = attr0.getLocalName(); - String localName1 = attr1.getLocalName(); - return localName0.compareTo(localName1); - */ - + // none is a namespace + if (namespaceURI0 == null) { + if (namespaceURI1 == null) { String name0 = attr0.getName(); String name1 = attr1.getName(); return name0.compareTo(name1); + } + return ATTR0_BEFORE_ATTR1; } - return ATTR0_BEFORE_ATTR1; - } - if (namespaceURI1 == null) { - return ATTR1_BEFORE_ATTR0; - } - int a = namespaceURI0.compareTo(namespaceURI1); + if (namespaceURI1 == null) { + return ATTR1_BEFORE_ATTR0; + } - if (a != 0) { - return a; - } - /* - String localName0 = ; - String localName1 =;*/ + int a = namespaceURI0.compareTo(namespaceURI1); + if (a != 0) { + return a; + } - return (attr0.getLocalName()) - .compareTo( attr1.getLocalName()); - - } - + return (attr0.getLocalName()).compareTo(attr1.getLocalName()); + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,684 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/* + * Copyright 2008 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.sun.org.apache.xml.internal.security.c14n.implementations; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import javax.xml.parsers.ParserConfigurationException; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.xml.sax.SAXException; + +import java.util.logging.Logger; +import java.util.logging.Logger; +import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; +import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper; +import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; + +/** + * Implements + * Canonical XML Version 1.1, a W3C Proposed Recommendation from 29 + * January 2008. + * + * @author Sean Mullan + * @author Raul Benito + * @version $Revision: 1.2 $ + */ +public abstract class Canonicalizer11 extends CanonicalizerBase { + boolean firstCall = true; + final SortedSet result = new TreeSet(COMPARE); + static final String XMLNS_URI = Constants.NamespaceSpecNS; + static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS; + + static Logger log = Logger.getLogger(Canonicalizer11.class.getName()); + + static class XmlAttrStack { + int currentLevel = 0; + int lastlevel = 0; + XmlsStackElement cur; + static class XmlsStackElement { + int level; + boolean rendered = false; + List nodes = new ArrayList(); + }; + List levels = new ArrayList(); + void push(int level) { + currentLevel = level; + if (currentLevel == -1) + return; + cur = null; + while (lastlevel >= currentLevel) { + levels.remove(levels.size() - 1); + if (levels.size() == 0) { + lastlevel = 0; + return; + } + lastlevel=((XmlsStackElement)levels.get(levels.size()-1)).level; + } + } + void addXmlnsAttr(Attr n) { + if (cur == null) { + cur = new XmlsStackElement(); + cur.level = currentLevel; + levels.add(cur); + lastlevel = currentLevel; + } + cur.nodes.add(n); + } + void getXmlnsAttr(Collection col) { + if (cur == null) { + cur = new XmlsStackElement(); + cur.level = currentLevel; + lastlevel = currentLevel; + levels.add(cur); + } + int size = levels.size() - 2; + boolean parentRendered = false; + XmlsStackElement e = null; + if (size == -1) { + parentRendered = true; + } else { + e = (XmlsStackElement) levels.get(size); + if (e.rendered && e.level+1 == currentLevel) + parentRendered = true; + } + if (parentRendered) { + col.addAll(cur.nodes); + cur.rendered = true; + return; + } + + Map loa = new HashMap(); + List baseAttrs = new ArrayList(); + boolean successiveOmitted = true; + for (;size>=0;size--) { + e = (XmlsStackElement) levels.get(size); + if (e.rendered) { + successiveOmitted = false; + } + Iterator it = e.nodes.iterator(); + while (it.hasNext() && successiveOmitted) { + Attr n = (Attr) it.next(); + if (n.getLocalName().equals("base")) { + if (!e.rendered) { + baseAttrs.add(n); + } + } else if (!loa.containsKey(n.getName())) + loa.put(n.getName(), n); + } + } + if (!baseAttrs.isEmpty()) { + Iterator it = cur.nodes.iterator(); + String base = null; + Attr baseAttr = null; + while (it.hasNext()) { + Attr n = (Attr) it.next(); + if (n.getLocalName().equals("base")) { + base = n.getValue(); + baseAttr = n; + break; + } + } + it = baseAttrs.iterator(); + while (it.hasNext()) { + Attr n = (Attr) it.next(); + if (base == null) { + base = n.getValue(); + baseAttr = n; + } else { + try { + base = joinURI(n.getValue(), base); + } catch (URISyntaxException ue) { + ue.printStackTrace(); + } + } + } + if (base != null && base.length() != 0) { + baseAttr.setValue(base); + col.add(baseAttr); + } + } + + cur.rendered = true; + col.addAll(loa.values()); + } + }; + XmlAttrStack xmlattrStack = new XmlAttrStack(); + + /** + * Constructor Canonicalizer11 + * + * @param includeComments + */ + public Canonicalizer11(boolean includeComments) { + super(includeComments); + } + + /** + * Returns the Attr[]s to be outputted for the given element. + *
+ * The code of this method is a copy of {@link #handleAttributes(Element, + * NameSpaceSymbTable)}, + * whereas it takes into account that subtree-c14n is -- well -- + * subtree-based. + * So if the element in question isRoot of c14n, it's parent is not in the + * node set, as well as all other ancestors. + * + * @param E + * @param ns + * @return the Attr[]s to be outputted + * @throws CanonicalizationException + */ + Iterator handleAttributesSubtree(Element E, NameSpaceSymbTable ns) + throws CanonicalizationException { + if (!E.hasAttributes() && !firstCall) { + return null; + } + // result will contain the attrs which have to be outputted + final SortedSet result = this.result; + result.clear(); + NamedNodeMap attrs = E.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr N = (Attr) attrs.item(i); + String NUri = N.getNamespaceURI(); + + if (XMLNS_URI != NUri) { + // It's not a namespace attr node. Add to the result and + // continue. + result.add(N); + continue; + } + + String NName = N.getLocalName(); + String NValue = N.getValue(); + if (XML.equals(NName) + && XML_LANG_URI.equals(NValue)) { + // The default mapping for xml must not be output. + continue; + } + + Node n = ns.addMappingAndRender(NName, NValue, N); + + if (n != null) { + // Render the ns definition + result.add(n); + if (C14nHelper.namespaceIsRelative(N)) { + Object exArgs[] = {E.getTagName(), NName, N.getNodeValue()}; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs); + } + } + } + + if (firstCall) { + // It is the first node of the subtree + // Obtain all the namespaces defined in the parents, and added + // to the output. + ns.getUnrenderedNodes(result); + // output the attributes in the xml namespace. + xmlattrStack.getXmlnsAttr(result); + firstCall = false; + } + + return result.iterator(); + } + + /** + * Returns the Attr[]s to be outputted for the given element. + *
+ * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a + * DOM which has been prepared using + * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( + * org.w3c.dom.Document)}. + * + * @param E + * @param ns + * @return the Attr[]s to be outputted + * @throws CanonicalizationException + */ + Iterator handleAttributes(Element E, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + xmlattrStack.push(ns.getLevel()); + boolean isRealVisible = isVisibleDO(E, ns.getLevel()) == 1; + NamedNodeMap attrs = null; + int attrsLength = 0; + if (E.hasAttributes()) { + attrs = E.getAttributes(); + attrsLength = attrs.getLength(); + } + + SortedSet result = this.result; + result.clear(); + + for (int i = 0; i < attrsLength; i++) { + Attr N = (Attr) attrs.item(i); + String NUri = N.getNamespaceURI(); + + if (XMLNS_URI != NUri) { + // A non namespace definition node. + if (XML_LANG_URI == NUri) { + if (N.getLocalName().equals("id")) { + if (isRealVisible) { + // treat xml:id like any other attribute + // (emit it, but don't inherit it) + result.add(N); + } + } else { + xmlattrStack.addXmlnsAttr(N); + } + } else if (isRealVisible) { + // The node is visible add the attribute to the list of + // output attributes. + result.add(N); + } + // keep working + continue; + } + + String NName = N.getLocalName(); + String NValue = N.getValue(); + if ("xml".equals(NName) + && XML_LANG_URI.equals(NValue)) { + /* except omit namespace node with local name xml, which defines + * the xml prefix, if its string value is + * http://www.w3.org/XML/1998/namespace. + */ + continue; + } + // add the prefix binding to the ns symb table. + // ns.addInclusiveMapping(NName,NValue,N,isRealVisible); + if (isVisible(N)) { + if (!isRealVisible && ns.removeMappingIfRender(NName)) { + continue; + } + // The xpath select this node output it if needed. + // Node n = ns.addMappingAndRenderXNodeSet + // (NName, NValue, N, isRealVisible); + Node n = ns.addMappingAndRender(NName, NValue, N); + if (n != null) { + result.add(n); + if (C14nHelper.namespaceIsRelative(N)) { + Object exArgs[] = + { E.getTagName(), NName, N.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs); + } + } + } else { + if (isRealVisible && NName != XMLNS) { + ns.removeMapping(NName); + } else { + ns.addMapping(NName, NValue, N); + } + } + } + if (isRealVisible) { + // The element is visible, handle the xmlns definition + Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS); + Node n = null; + if (xmlns == null) { + // No xmlns def just get the already defined. + n = ns.getMapping(XMLNS); + } else if (!isVisible(xmlns)) { + // There is a defn but the xmlns is not selected by the xpath. + // then xmlns="" + n = ns.addMappingAndRender(XMLNS, "", nullNode); + } + // output the xmlns def if needed. + if (n != null) { + result.add(n); + } + // Float all xml:* attributes of the unselected parent elements to + // this one. addXmlAttributes(E,result); + xmlattrStack.getXmlnsAttr(result); + ns.getUnrenderedNodes(result); + } + + return result.iterator(); + } + + /** + * Always throws a CanonicalizationException because this is inclusive c14n. + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException always + */ + public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, + String inclusiveNamespaces) throws CanonicalizationException { + throw new CanonicalizationException( + "c14n.Canonicalizer.UnsupportedOperation"); + } + + /** + * Always throws a CanonicalizationException because this is inclusive c14n. + * + * @param rootNode + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree(Node rootNode, + String inclusiveNamespaces) throws CanonicalizationException { + throw new CanonicalizationException( + "c14n.Canonicalizer.UnsupportedOperation"); + } + + void circumventBugIfNeeded(XMLSignatureInput input) + throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException { + if (!input.isNeedsToBeExpanded()) + return; + Document doc = null; + if (input.getSubNode() != null) { + doc = XMLUtils.getOwnerDocument(input.getSubNode()); + } else { + doc = XMLUtils.getOwnerDocument(input.getNodeSet()); + } + XMLUtils.circumventBug2650(doc); + } + + void handleParent(Element e, NameSpaceSymbTable ns) { + if (!e.hasAttributes()) { + return; + } + xmlattrStack.push(-1); + NamedNodeMap attrs = e.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr N = (Attr) attrs.item(i); + if (Constants.NamespaceSpecNS != N.getNamespaceURI()) { + // Not a namespace definition, ignore. + if (XML_LANG_URI == N.getNamespaceURI()) { + xmlattrStack.addXmlnsAttr(N); + } + continue; + } + + String NName = N.getLocalName(); + String NValue = N.getNodeValue(); + if (XML.equals(NName) + && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { + continue; + } + ns.addMapping(NName,NValue,N); + } + } + + private static String joinURI(String baseURI, String relativeURI) + throws URISyntaxException { + String bscheme = null; + String bauthority = null; + String bpath = ""; + String bquery = null; + String bfragment = null; // Is this correct? + + // pre-parse the baseURI + if (baseURI != null) { + if (baseURI.endsWith("..")) { + baseURI = baseURI + "/"; + } + URI base = new URI(baseURI); + bscheme = base.getScheme(); + bauthority = base.getAuthority(); + bpath = base.getPath(); + bquery = base.getQuery(); + bfragment = base.getFragment(); + } + + URI r = new URI(relativeURI); + String rscheme = r.getScheme(); + String rauthority = r.getAuthority(); + String rpath = r.getPath(); + String rquery = r.getQuery(); + String rfragment = null; + + String tscheme, tauthority, tpath, tquery, tfragment; + if (rscheme != null && rscheme.equals(bscheme)) { + rscheme = null; + } + if (rscheme != null) { + tscheme = rscheme; + tauthority = rauthority; + tpath = removeDotSegments(rpath); + tquery = rquery; + } else { + if (rauthority != null) { + tauthority = rauthority; + tpath = removeDotSegments(rpath); + tquery = rquery; + } else { + if (rpath.length() == 0) { + tpath = bpath; + if (rquery != null) { + tquery = rquery; + } else { + tquery = bquery; + } + } else { + if (rpath.startsWith("/")) { + tpath = removeDotSegments(rpath); + } else { + if (bauthority != null && bpath.length() == 0) { + tpath = "/" + rpath; + } else { + int last = bpath.lastIndexOf('/'); + if (last == -1) { + tpath = rpath; + } else { + tpath = bpath.substring(0, last+1) + rpath; + } + } + tpath = removeDotSegments(tpath); + } + tquery = rquery; + } + tauthority = bauthority; + } + tscheme = bscheme; + } + tfragment = rfragment; + return new URI(tscheme, tauthority, tpath, tquery, tfragment).toString(); + } + + private static String removeDotSegments(String path) { + + log.log(java.util.logging.Level.FINE, "STEP OUTPUT BUFFER\t\tINPUT BUFFER"); + + // 1. The input buffer is initialized with the now-appended path + // components then replace occurrences of "//" in the input buffer + // with "/" until no more occurrences of "//" are in the input buffer. + String input = path; + while (input.indexOf("//") > -1) { + input = input.replaceAll("//", "/"); + } + + // Initialize the output buffer with the empty string. + StringBuffer output = new StringBuffer(); + + // If the input buffer starts with a root slash "/" then move this + // character to the output buffer. + if (input.charAt(0) == '/') { + output.append("/"); + input = input.substring(1); + } + + printStep("1 ", output.toString(), input); + + // While the input buffer is not empty, loop as follows + while (input.length() != 0) { + // 2A. If the input buffer begins with a prefix of "./", + // then remove that prefix from the input buffer + // else if the input buffer begins with a prefix of "../", then + // if also the output does not contain the root slash "/" only, + // then move this prefix to the end of the output buffer else + // remove that prefix + if (input.startsWith("./")) { + input = input.substring(2); + printStep("2A", output.toString(), input); + } else if (input.startsWith("../")) { + input = input.substring(3); + if (!output.toString().equals("/")) { + output.append("../"); + } + printStep("2A", output.toString(), input); + // 2B. if the input buffer begins with a prefix of "/./" or "/.", + // where "." is a complete path segment, then replace that prefix + // with "/" in the input buffer; otherwise, + } else if (input.startsWith("/./")) { + input = input.substring(2); + printStep("2B", output.toString(), input); + } else if (input.equals("/.")) { + // FIXME: what is complete path segment? + input = input.replaceFirst("/.", "/"); + printStep("2B", output.toString(), input); + // 2C. if the input buffer begins with a prefix of "/../" or "/..", + // where ".." is a complete path segment, then replace that prefix + // with "/" in the input buffer and if also the output buffer is + // empty, last segment in the output buffer equals "../" or "..", + // where ".." is a complete path segment, then append ".." or "/.." + // for the latter case respectively to the output buffer else + // remove the last segment and its preceding "/" (if any) from the + // output buffer and if hereby the first character in the output + // buffer was removed and it was not the root slash then delete a + // leading slash from the input buffer; otherwise, + } else if (input.startsWith("/../")) { + input = input.substring(3); + if (output.length() == 0) { + output.append("/"); + } else if (output.toString().endsWith("../")) { + output.append(".."); + } else if (output.toString().endsWith("..")) { + output.append("/.."); + } else { + int index = output.lastIndexOf("/"); + if (index == -1) { + output = new StringBuffer(); + if (input.charAt(0) == '/') { + input = input.substring(1); + } + } else { + output = output.delete(index, output.length()); + } + } + printStep("2C", output.toString(), input); + } else if (input.equals("/..")) { + // FIXME: what is complete path segment? + input = input.replaceFirst("/..", "/"); + if (output.length() == 0) { + output.append("/"); + } else if (output.toString().endsWith("../")) { + output.append(".."); + } else if (output.toString().endsWith("..")) { + output.append("/.."); + } else { + int index = output.lastIndexOf("/"); + if (index == -1) { + output = new StringBuffer(); + if (input.charAt(0) == '/') { + input = input.substring(1); + } + } else { + output = output.delete(index, output.length()); + } + } + printStep("2C", output.toString(), input); + // 2D. if the input buffer consists only of ".", then remove + // that from the input buffer else if the input buffer consists + // only of ".." and if the output buffer does not contain only + // the root slash "/", then move the ".." to the output buffer + // else delte it.; otherwise, + } else if (input.equals(".")) { + input = ""; + printStep("2D", output.toString(), input); + } else if (input.equals("..")) { + if (!output.toString().equals("/")) + output.append(".."); + input = ""; + printStep("2D", output.toString(), input); + // 2E. move the first path segment (if any) in the input buffer + // to the end of the output buffer, including the initial "/" + // character (if any) and any subsequent characters up to, but not + // including, the next "/" character or the end of the input buffer. + } else { + int end = -1; + int begin = input.indexOf('/'); + if (begin == 0) { + end = input.indexOf('/', 1); + } else { + end = begin; + begin = 0; + } + String segment; + if (end == -1) { + segment = input.substring(begin); + input = ""; + } else { + segment = input.substring(begin, end); + input = input.substring(end); + } + output.append(segment); + printStep("2E", output.toString(), input); + } + } + + // 3. Finally, if the only or last segment of the output buffer is + // "..", where ".." is a complete path segment not followed by a slash + // then append a slash "/". The output buffer is returned as the result + // of remove_dot_segments + if (output.toString().endsWith("..")) { + output.append("/"); + printStep("3 ", output.toString(), input); + } + + return output.toString(); + } + + private static void printStep(String step, String output, String input) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, " " + step + ": " + output); + if (output.length() == 0) { + log.log(java.util.logging.Level.FINE, "\t\t\t\t" + input); + } else { + log.log(java.util.logging.Level.FINE, "\t\t\t" + input); + } + } + } +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,41 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/* + * Copyright 2008 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.sun.org.apache.xml.internal.security.c14n.implementations; + +import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; + +/** + * @author Sean Mullan + */ +public class Canonicalizer11_OmitComments extends Canonicalizer11 { + + public Canonicalizer11_OmitComments() { + super(false); + } + + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS; + } + + public final boolean engineGetIncludeComments() { + return false; + } +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,41 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/* + * Copyright 2008 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.sun.org.apache.xml.internal.security.c14n.implementations; + +import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; + +/** + * @author Sean Mullan + */ +public class Canonicalizer11_WithComments extends Canonicalizer11 { + + public Canonicalizer11_WithComments() { + super(true); + } + + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS; + } + + public final boolean engineGetIncludeComments() { + return true; + } +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -23,20 +22,30 @@ +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; +import javax.xml.parsers.ParserConfigurationException; + import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper; +import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Attr; +import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; +import org.xml.sax.SAXException; /** @@ -44,13 +53,92 @@ * XML Version 1.0, a W3C Recommendation from 15 March 2001. * * @author Christian Geuer-Pollmann + * @version $Revision: 1.5 $ */ public abstract class Canonicalizer20010315 extends CanonicalizerBase { boolean firstCall=true; final SortedSet result= new TreeSet(COMPARE); static final String XMLNS_URI=Constants.NamespaceSpecNS; static final String XML_LANG_URI=Constants.XML_LANG_SPACE_SpecNS; - /** + static class XmlAttrStack { + int currentLevel=0; + int lastlevel=0; + XmlsStackElement cur; + static class XmlsStackElement { + int level; + boolean rendered=false; + List nodes=new ArrayList(); + }; + List levels=new ArrayList(); + void push(int level) { + currentLevel=level; + if (currentLevel==-1) + return; + cur=null; + while (lastlevel>=currentLevel) { + levels.remove(levels.size()-1); + if (levels.size()==0) { + lastlevel=0; + return; + } + lastlevel=((XmlsStackElement)levels.get(levels.size()-1)).level; + } + } + void addXmlnsAttr(Attr n) { + if (cur==null) { + cur=new XmlsStackElement(); + cur.level=currentLevel; + levels.add(cur); + lastlevel=currentLevel; + } + cur.nodes.add(n); + } + void getXmlnsAttr(Collection col) { + int size=levels.size()-1; + if (cur==null) { + cur=new XmlsStackElement(); + cur.level=currentLevel; + lastlevel=currentLevel; + levels.add(cur); + } + boolean parentRendered=false; + XmlsStackElement e=null; + if (size==-1) { + parentRendered=true; + } else { + e=(XmlsStackElement)levels.get(size); + if (e.rendered && e.level+1==currentLevel) + parentRendered=true; + + } + if (parentRendered) { + col.addAll(cur.nodes); + cur.rendered=true; + return; + } + + Map loa = new HashMap(); + for (;size>=0;size--) { + e=(XmlsStackElement)levels.get(size); + Iterator it=e.nodes.iterator(); + while (it.hasNext()) { + Attr n=(Attr)it.next(); + if (!loa.containsKey(n.getName())) + loa.put(n.getName(),n); + } + //if (e.rendered) + //break; + + }; + //cur.nodes.clear(); + //cur.nodes.addAll(loa.values()); + cur.rendered=true; + col.addAll(loa.values()); + } + + } + XmlAttrStack xmlattrStack=new XmlAttrStack(); + /** * Constructor Canonicalizer20010315 * * @param includeComments @@ -86,16 +174,16 @@ for (int i = 0; i < attrsLength; i++) { Attr N = (Attr) attrs.item(i); - String NName=N.getLocalName(); - String NValue=N.getValue(); String NUri =N.getNamespaceURI(); - if (!XMLNS_URI.equals(NUri)) { + if (XMLNS_URI!=NUri) { //It's not a namespace attr node. Add to the result and continue. result.add(N); continue; } + String NName=N.getLocalName(); + String NValue=N.getValue(); if (XML.equals(NName) && XML_LANG_URI.equals(NValue)) { //The default mapping for xml must not be output. @@ -120,65 +208,14 @@ //Obtain all the namespaces defined in the parents, and added to the output. ns.getUnrenderedNodes(result); //output the attributes in the xml namespace. - addXmlAttributesSubtree(E, result); - firstCall=false; + xmlattrStack.getXmlnsAttr(result); + firstCall=false; } return result.iterator(); } /** - * Float the xml:* attributes of the parent nodes to the root node of c14n - * @param E the root node. - * @param result the xml:* attributes to output. - */ - private void addXmlAttributesSubtree(Element E, SortedSet result) { - // E is in the node-set - Node parent = E.getParentNode(); - Map loa = new HashMap(); - - if ((parent != null) && (parent.getNodeType() == Node.ELEMENT_NODE)) { - - // parent element is not in node set - for (Node ancestor = parent; - (ancestor != null) - && (ancestor.getNodeType() == Node.ELEMENT_NODE); - ancestor = ancestor.getParentNode()) { - Element el=((Element) ancestor); - if (!el.hasAttributes()) { - continue; - } - // for all ancestor elements - NamedNodeMap ancestorAttrs = el.getAttributes(); - - for (int i = 0; i < ancestorAttrs.getLength(); i++) { - // for all attributes in the ancestor element - Attr currentAncestorAttr = (Attr) ancestorAttrs.item(i); - - if (XML_LANG_URI.equals( - currentAncestorAttr.getNamespaceURI())) { - - // do we have an xml:* ? - if (!E.hasAttributeNS( - XML_LANG_URI, - currentAncestorAttr.getLocalName())) { - - // the xml:* attr is not in E - if (!loa.containsKey(currentAncestorAttr.getName())) { - loa.put(currentAncestorAttr.getName(), - currentAncestorAttr); - } - } - } - } - } - } - - result.addAll( loa.values()); - - } - - /** * Returns the Attr[]s to be outputted for the given element. *
* IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has @@ -192,7 +229,8 @@ */ Iterator handleAttributes(Element E, NameSpaceSymbTable ns ) throws CanonicalizationException { // result will contain the attrs which have to be outputted - boolean isRealVisible=isVisible(E); + xmlattrStack.push(ns.getLevel()); + boolean isRealVisible=isVisibleDO(E,ns.getLevel())==1; NamedNodeMap attrs = null; int attrsLength = 0; if (E.hasAttributes()) { @@ -204,16 +242,15 @@ SortedSet result = this.result; result.clear(); - for (int i = 0; i < attrsLength; i++) { Attr N = (Attr) attrs.item(i); - String NName=N.getLocalName(); - String NValue=N.getValue(); String NUri =N.getNamespaceURI(); - if (!XMLNS_URI.equals(NUri)) { + if (XMLNS_URI!=NUri) { //A non namespace definition node. - if (isRealVisible){ + if (XML_LANG_URI==NUri) { + xmlattrStack.addXmlnsAttr(N); + } else if (isRealVisible){ //The node is visible add the attribute to the list of output attributes. result.add(N); } @@ -221,7 +258,8 @@ continue; } - + String NName=N.getLocalName(); + String NValue=N.getValue(); if ("xml".equals(NName) && XML_LANG_URI.equals(NValue)) { /* except omit namespace node with local name xml, which defines @@ -232,16 +270,26 @@ //add the prefix binding to the ns symb table. //ns.addInclusiveMapping(NName,NValue,N,isRealVisible); if (isVisible(N)) { - //The xpath select this node output it if needed. - Node n=ns.addMappingAndRenderXNodeSet(NName,NValue,N,isRealVisible); - if (n!=null) { + if (!isRealVisible && ns.removeMappingIfRender(NName)) { + continue; + } + //The xpath select this node output it if needed. + //Node n=ns.addMappingAndRenderXNodeSet(NName,NValue,N,isRealVisible); + Node n=ns.addMappingAndRender(NName,NValue,N); + if (n!=null) { result.add(n); if (C14nHelper.namespaceIsRelative(N)) { Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() }; throw new CanonicalizationException( "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } + } + } + } else { + if (isRealVisible && NName!=XMLNS) { + ns.removeMapping(NName); + } else { + ns.addMapping(NName,NValue,N); + } } } if (isRealVisible) { @@ -254,85 +302,22 @@ } else if ( !isVisible(xmlns)) { //There is a definition but the xmlns is not selected by the xpath. //then xmlns="" - n=ns.addMappingAndRenderXNodeSet(XMLNS,"",nullNode,true); + n=ns.addMappingAndRender(XMLNS,"",nullNode); } //output the xmlns def if needed. if (n!=null) { result.add(n); } //Float all xml:* attributes of the unselected parent elements to this one. - addXmlAttributes(E,result); + //addXmlAttributes(E,result); + xmlattrStack.getXmlnsAttr(result); + ns.getUnrenderedNodes(result); + } return result.iterator(); } /** - * Float the xml:* attributes of the unselected parent nodes to the ciurrent node. - * @param E - * @param result - */ - private void addXmlAttributes(Element E, SortedSet result) { - /* The processing of an element node E MUST be modified slightly when an - * XPath node-set is given as input and the element's parent is omitted - * from the node-set. The method for processing the attribute axis of an - * element E in the node-set is enhanced. All element nodes along E's - * ancestor axis are examined for nearest occurrences of attributes in - * the xml namespace, such as xml:lang and xml:space (whether or not they - * are in the node-set). From this list of attributes, remove any that are - * in E's attribute axis (whether or not they are in the node-set). Then, - * lexicographically merge this attribute list with the nodes of E's - * attribute axis that are in the node-set. The result of visiting the - * attribute axis is computed by processing the attribute nodes in this - * merged attribute list. - */ - - // E is in the node-set - Node parent = E.getParentNode(); - Map loa = new HashMap(); - - if ((parent != null) && (parent.getNodeType() == Node.ELEMENT_NODE) - &&!isVisible(parent)) { - - // parent element is not in node set - for (Node ancestor = parent; - (ancestor != null) - && (ancestor.getNodeType() == Node.ELEMENT_NODE); - ancestor = ancestor.getParentNode()) { - Element el=((Element) ancestor); - if (!el.hasAttributes()) { - continue; - } - // for all ancestor elements - NamedNodeMap ancestorAttrs =el.getAttributes(); - - for (int i = 0; i < ancestorAttrs.getLength(); i++) { - - // for all attributes in the ancestor element - Attr currentAncestorAttr = (Attr) ancestorAttrs.item(i); - - if (XML_LANG_URI.equals( - currentAncestorAttr.getNamespaceURI())) { - - // do we have an xml:* ? - if (!E.hasAttributeNS( - XML_LANG_URI, - currentAncestorAttr.getLocalName())) { - - // the xml:* attr is not in E - if (!loa.containsKey(currentAncestorAttr.getName())) { - loa.put(currentAncestorAttr.getName(), - currentAncestorAttr); - } - } - } - } - } - } - result.addAll(loa.values()); - -} - - /** * Always throws a CanonicalizationException because this is inclusive c14n. * * @param xpathNodeSet @@ -363,4 +348,43 @@ throw new CanonicalizationException( "c14n.Canonicalizer.UnsupportedOperation"); } + void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { + if (!input.isNeedsToBeExpanded()) + return; + Document doc = null; + if (input.getSubNode() != null) { + doc=XMLUtils.getOwnerDocument(input.getSubNode()); + } else { + doc=XMLUtils.getOwnerDocument(input.getNodeSet()); + } + XMLUtils.circumventBug2650(doc); + + } + + void handleParent(Element e, NameSpaceSymbTable ns) { + if (!e.hasAttributes()) { + return; + } + xmlattrStack.push(-1); + NamedNodeMap attrs = e.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr N = (Attr) attrs.item(i); + if (Constants.NamespaceSpecNS!=N.getNamespaceURI()) { + //Not a namespace definition, ignore. + if (XML_LANG_URI==N.getNamespaceURI()) { + xmlattrStack.addXmlnsAttr(N); + } + continue; + } + + String NName=N.getLocalName(); + String NValue=N.getNodeValue(); + if (XML.equals(NName) + && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { + continue; + } + ns.addMapping(NName,NValue,N); + } + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -21,20 +20,26 @@ */ package com.sun.org.apache.xml.internal.security.c14n.implementations; +import java.io.IOException; import java.util.Iterator; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; +import javax.xml.parsers.ParserConfigurationException; + import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNamespaces; import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Attr; +import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; +import org.xml.sax.SAXException; /** * Implements " Exclusive XML @@ -47,6 +52,7 @@ * THIS implementation is a complete rewrite of the algorithm. * * @author Christian Geuer-Pollmann + * @version $Revision: 1.5 $ * @see * XML Canonicalization, Version 1.0 */ @@ -55,7 +61,7 @@ * This Set contains the names (Strings like "xmlns" or "xmlns:foo") of * the inclusive namespaces. */ - TreeSet _inclusiveNSSet = null; + TreeSet _inclusiveNSSet = new TreeSet(); static final String XMLNS_URI=Constants.NamespaceSpecNS; final SortedSet result = new TreeSet(COMPARE); /** @@ -143,10 +149,8 @@ for (int i = 0; i < attrsLength; i++) { Attr N = (Attr) attrs.item(i); - String NName=N.getLocalName(); - String NNodeValue=N.getNodeValue(); - if (!XMLNS_URI.equals(N.getNamespaceURI())) { + if (XMLNS_URI!=N.getNamespaceURI()) { //Not a namespace definition. //The Element is output element, add his prefix(if used) to visibyUtilized String prefix = N.getPrefix(); @@ -157,6 +161,8 @@ result.add(N); continue; } + String NName=N.getLocalName(); + String NNodeValue=N.getNodeValue(); if (ns.addMapping(NName, NNodeValue,N)) { //New definition check if it is relative. @@ -168,17 +174,17 @@ } } } - + String prefix; if (E.getNamespaceURI() != null) { - String prefix = E.getPrefix(); + prefix = E.getPrefix(); if ((prefix == null) || (prefix.length() == 0)) { - visiblyUtilized.add(XMLNS); - } else { - visiblyUtilized.add(prefix); + prefix=XMLNS; } + } else { - visiblyUtilized.add(XMLNS); + prefix=XMLNS; } + visiblyUtilized.add(prefix); //This can be optimezed by I don't have time Iterator it=visiblyUtilized.iterator(); @@ -211,12 +217,6 @@ } - /** @inheritDoc */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet - ) throws CanonicalizationException { - return engineCanonicalizeXPathNodeSet(xpathNodeSet,""); - } - /** * @inheritDoc * @param E @@ -236,21 +236,20 @@ //The prefix visibly utilized(in the attribute or in the name) in the element Set visiblyUtilized =null; //It's the output selected. - boolean isOutputElement = isVisible(E); + boolean isOutputElement=isVisibleDO(E,ns.getLevel())==1; if (isOutputElement) { visiblyUtilized = (Set) this._inclusiveNSSet.clone(); } for (int i = 0; i < attrsLength; i++) { Attr N = (Attr) attrs.item(i); - String NName=N.getLocalName(); - String NNodeValue=N.getNodeValue(); - if ( !isVisible(N) ) { - //The node is not in the nodeset(if there is a nodeset) - continue; - } + - if (!XMLNS_URI.equals(N.getNamespaceURI())) { + if (XMLNS_URI!=N.getNamespaceURI()) { + if ( !isVisible(N) ) { + //The node is not in the nodeset(if there is a nodeset) + continue; + } //Not a namespace definition. if (isOutputElement) { //The Element is output element, add his prefix(if used) to visibyUtilized @@ -263,6 +262,25 @@ } continue; } + String NName=N.getLocalName(); + if (isOutputElement && !isVisible(N) && NName!=XMLNS) { + ns.removeMappingIfNotRender(NName); + continue; + } + String NNodeValue=N.getNodeValue(); + + if (!isOutputElement && isVisible(N) && _inclusiveNSSet.contains(NName) && !ns.removeMappingIfRender(NName)) { + Node n=ns.addMappingAndRender(NName,NNodeValue,N); + if (n!=null) { + result.add(n); + if (C14nHelper.namespaceIsRelative(N)) { + Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs); + } + } + } + if (ns.addMapping(NName, NNodeValue,N)) { @@ -306,18 +324,20 @@ } result.add(key); } - } else /*if (_circunvented)*/ { - Iterator it=this._inclusiveNSSet.iterator(); - while (it.hasNext()) { - String s=(String)it.next(); - Attr key=ns.getMappingWithoutRendered(s); - if (key==null) { - continue; - } - result.add(key); - } } return result.iterator(); } + void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { + if (!input.isNeedsToBeExpanded() || _inclusiveNSSet.isEmpty()) + return; + Document doc = null; + if (input.getSubNode() != null) { + doc=XMLUtils.getOwnerDocument(input.getSubNode()); + } else { + doc=XMLUtils.getOwnerDocument(input.getNodeSet()); + } + + XMLUtils.circumventBug2650(doc); + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java Wed Jul 05 16:42:37 2017 +0200 @@ -28,6 +28,7 @@ /** * Class Canonicalizer20010315ExclWithComments * + * @version $Revision: 1.5 $ */ public class Canonicalizer20010315ExclWithComments extends Canonicalizer20010315Excl { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java Wed Jul 05 16:42:37 2017 +0200 @@ -27,9 +27,11 @@ import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; +import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; +import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; @@ -45,7 +47,6 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Attr; import org.w3c.dom.Comment; -import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; @@ -57,6 +58,7 @@ * Abstract base class for canonicalization algorithms. * * @author Christian Geuer-Pollmann + * @version $Revision: 1.5 $ */ public abstract class CanonicalizerBase extends CanonicalizerSpi { //Constants to be outputed, In char array form, so @@ -123,6 +125,18 @@ return engineCanonicalizeSubTree(rootNode,(Node)null); } /** + * Method engineCanonicalizeXPathNodeSet + * @inheritDoc + * @param xpathNodeSet + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) + throws CanonicalizationException { + this._xpathNodeSet = xpathNodeSet; + return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this._xpathNodeSet)); + } + + /** * Canonicalizes a Subtree node. * @param input the root of the subtree to canicalize * @return The canonicalize stream. @@ -143,15 +157,8 @@ return bytes; } else if (input.isNodeSet()) { nodeFilter=input.getNodeFilters(); - Document doc = null; - if (input.getSubNode() != null) { - doc=XMLUtils.getOwnerDocument(input.getSubNode()); - } else { - doc=XMLUtils.getOwnerDocument(input.getNodeSet()); - } - if (input.isNeedsToBeExpanded()) { - XMLUtils.circumventBug2650(doc); - } + + circumventBugIfNeeded(input); if (input.getSubNode() != null) { bytes = engineCanonicalizeXPathNodeSetInternal(input.getSubNode()); @@ -173,6 +180,13 @@ } } /** + * @param _writer The _writer to set. + */ + public void setWriter(OutputStream _writer) { + this._writer = _writer; + } + + /** * Canonicalizes a Subtree node. * * @param rootNode @@ -187,11 +201,13 @@ this._excludeNode = excludeNode; try { NameSpaceSymbTable ns=new NameSpaceSymbTable(); + int nodeLevel=NODE_BEFORE_DOCUMENT_ELEMENT; if (rootNode instanceof Element) { //Fills the nssymbtable with the definitions of the parent of the root subnode getParentNameSpaces((Element)rootNode,ns); + nodeLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } - this.canonicalizeSubTree(rootNode,ns,rootNode); + this.canonicalizeSubTree(rootNode,ns,rootNode,nodeLevel); this._writer.close(); if (this._writer instanceof ByteArrayOutputStream) { byte []result=((ByteArrayOutputStream)this._writer).toByteArray(); @@ -199,6 +215,12 @@ ((ByteArrayOutputStream)this._writer).reset(); } return result; + } else if (this._writer instanceof UnsyncByteArrayOutputStream) { + byte []result=((UnsyncByteArrayOutputStream)this._writer).toByteArray(); + if (reset) { + ((UnsyncByteArrayOutputStream)this._writer).reset(); + } + return result; } return null; @@ -219,13 +241,17 @@ * @throws CanonicalizationException * @throws IOException */ - final void canonicalizeSubTree(Node currentNode, NameSpaceSymbTable ns,Node endnode) + final void canonicalizeSubTree(Node currentNode, NameSpaceSymbTable ns,Node endnode, + int documentLevel) throws CanonicalizationException, IOException { + if (isVisibleInt(currentNode)==-1) + return; Node sibling=null; Node parentNode=null; final OutputStream writer=this._writer; final Node excludeNode=this._excludeNode; final boolean includeComments=this._includeComments; + Map cache=new HashMap(); do { switch (currentNode.getNodeType()) { @@ -242,18 +268,17 @@ case Node.DOCUMENT_FRAGMENT_NODE : case Node.DOCUMENT_NODE : ns.outputNodePush(); - //currentNode = currentNode.getFirstChild(); sibling= currentNode.getFirstChild(); break; case Node.COMMENT_NODE : if (includeComments) { - outputCommentToWriter((Comment) currentNode, writer); + outputCommentToWriter((Comment) currentNode, writer, documentLevel); } break; case Node.PROCESSING_INSTRUCTION_NODE : - outputPItoWriter((ProcessingInstruction) currentNode, writer); + outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); break; case Node.TEXT_NODE : @@ -262,6 +287,7 @@ break; case Node.ELEMENT_NODE : + documentLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; if (currentNode==excludeNode) { break; } @@ -270,27 +296,27 @@ ns.outputNodePush(); writer.write('<'); String name=currentElement.getTagName(); - writeStringToUtf8(name,writer); + UtfHelpper.writeByte(name,writer,cache); Iterator attrs = this.handleAttributesSubtree(currentElement,ns); if (attrs!=null) { //we output all Attrs which are available while (attrs.hasNext()) { Attr attr = (Attr) attrs.next(); - outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer); + outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache); } } writer.write('>'); sibling= currentNode.getFirstChild(); if (sibling==null) { writer.write(_END_TAG); - writeStringToUtf8(name,writer); + UtfHelpper.writeStringToUtf8(name,writer); writer.write('>'); //We fineshed with this level, pop to the previous definitions. ns.outputNodePop(); - if (parentNode != null) { + if (parentNode != null) { sibling= currentNode.getNextSibling(); - } + } } else { parentNode=currentElement; } @@ -298,7 +324,7 @@ } while (sibling==null && parentNode!=null) { writer.write(_END_TAG); - writeStringToUtf8(((Element)parentNode).getTagName(),writer); + UtfHelpper.writeByte(((Element)parentNode).getTagName(),writer,cache); writer.write('>'); //We fineshed with this level, pop to the previous definitions. ns.outputNodePop(); @@ -307,6 +333,7 @@ sibling=parentNode.getNextSibling(); parentNode=parentNode.getParentNode(); if (!(parentNode instanceof Element)) { + documentLevel=NODE_AFTER_DOCUMENT_ELEMENT; parentNode=null; } } @@ -317,47 +344,8 @@ } while(true); } - /** - * Checks whether a Comment or ProcessingInstruction is before or after the - * document element. This is needed for prepending or appending "\n"s. - * - * @param currentNode comment or pi to check - * @return NODE_BEFORE_DOCUMENT_ELEMENT, NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT or NODE_AFTER_DOCUMENT_ELEMENT - * @see #NODE_BEFORE_DOCUMENT_ELEMENT - * @see #NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT - * @see #NODE_AFTER_DOCUMENT_ELEMENT - */ - final static int getPositionRelativeToDocumentElement(Node currentNode) { - - if ((currentNode == null) || - (currentNode.getParentNode().getNodeType() != Node.DOCUMENT_NODE) ) { - return CanonicalizerBase.NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - Element documentElement = currentNode.getOwnerDocument().getDocumentElement(); - if ( (documentElement == null) || (documentElement == currentNode) ){ - return CanonicalizerBase.NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - for (Node x = currentNode; x != null; x = x.getNextSibling()) { - if (x == documentElement) { - return CanonicalizerBase.NODE_BEFORE_DOCUMENT_ELEMENT; - } - } - return CanonicalizerBase.NODE_AFTER_DOCUMENT_ELEMENT; - } - - /** - * Method engineCanonicalizeXPathNodeSet - * @inheritDoc - * @param xpathNodeSet - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) - throws CanonicalizationException { - this._xpathNodeSet = xpathNodeSet; - return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this._xpathNodeSet)); - } private byte[] engineCanonicalizeXPathNodeSetInternal(Node doc) throws CanonicalizationException { @@ -370,6 +358,12 @@ ((ByteArrayOutputStream)this._writer).reset(); } return sol; + } else if (this._writer instanceof UnsyncByteArrayOutputStream) { + byte []result=((UnsyncByteArrayOutputStream)this._writer).toByteArray(); + if (reset) { + ((UnsyncByteArrayOutputStream)this._writer).reset(); + } + return result; } return null; } catch (UnsupportedEncodingException ex) { @@ -390,11 +384,17 @@ */ final void canonicalizeXPathNodeSet(Node currentNode,Node endnode ) throws CanonicalizationException, IOException { - boolean currentNodeIsVisible = false; - NameSpaceSymbTable ns=new NameSpaceSymbTable(); + if (isVisibleInt(currentNode)==-1) + return; + boolean currentNodeIsVisible = false; + NameSpaceSymbTable ns=new NameSpaceSymbTable(); + if (currentNode instanceof Element) + getParentNameSpaces((Element)currentNode,ns); Node sibling=null; Node parentNode=null; OutputStream writer=this._writer; + int documentLevel=NODE_BEFORE_DOCUMENT_ELEMENT; + Map cache=new HashMap(); do { switch (currentNode.getNodeType()) { @@ -416,14 +416,14 @@ break; case Node.COMMENT_NODE : - if (this._includeComments && isVisible(currentNode)) { - outputCommentToWriter((Comment) currentNode, writer); + if (this._includeComments && (isVisibleDO(currentNode,ns.getLevel())==1)) { + outputCommentToWriter((Comment) currentNode, writer, documentLevel); } break; case Node.PROCESSING_INSTRUCTION_NODE : if (isVisible(currentNode)) - outputPItoWriter((ProcessingInstruction) currentNode, writer); + outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); break; case Node.TEXT_NODE : @@ -436,12 +436,6 @@ || (nextSibling.getNodeType() == Node.CDATA_SECTION_NODE)); nextSibling = nextSibling.getNextSibling()) { - /* The XPath data model allows to select only the first of a - * sequence of mixed text and CDATA nodes. But we must output - * them all, so we must search: - * - * @see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=6329 - */ outputTextToWriter(nextSibling.getNodeValue(), writer); currentNode=nextSibling; sibling=currentNode.getNextSibling(); @@ -451,15 +445,21 @@ break; case Node.ELEMENT_NODE : + documentLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; Element currentElement = (Element) currentNode; //Add a level to the nssymbtable. So latter can be pop-back. String name=null; - currentNodeIsVisible=isVisible(currentNode); + int i=isVisibleDO(currentNode,ns.getLevel()); + if (i==-1) { + sibling= currentNode.getNextSibling(); + break; + } + currentNodeIsVisible=(i==1); if (currentNodeIsVisible) { ns.outputNodePush(); writer.write('<'); name=currentElement.getTagName(); - writeStringToUtf8(name,writer); + UtfHelpper.writeByte(name,writer,cache); } else { ns.push(); } @@ -469,7 +469,7 @@ //we output all Attrs which are available while (attrs.hasNext()) { Attr attr = (Attr) attrs.next(); - outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer); + outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache); } } if (currentNodeIsVisible) { @@ -480,7 +480,7 @@ if (sibling==null) { if (currentNodeIsVisible) { writer.write(_END_TAG); - writeStringToUtf8(name,writer); + UtfHelpper.writeByte(name,writer,cache); writer.write('>'); //We fineshed with this level, pop to the previous definitions. ns.outputNodePop(); @@ -498,7 +498,7 @@ while (sibling==null && parentNode!=null) { if (isVisible(parentNode)) { writer.write(_END_TAG); - writeStringToUtf8(((Element)parentNode).getTagName(),writer); + UtfHelpper.writeByte(((Element)parentNode).getTagName(),writer,cache); writer.write('>'); //We fineshed with this level, pop to the previous definitions. ns.outputNodePop(); @@ -511,6 +511,7 @@ parentNode=parentNode.getParentNode(); if (!(parentNode instanceof Element)) { parentNode=null; + documentLevel=NODE_AFTER_DOCUMENT_ELEMENT; } } if (sibling==null) @@ -519,12 +520,38 @@ sibling=currentNode.getNextSibling(); } while(true); } + int isVisibleDO(Node currentNode,int level) { + if (nodeFilter!=null) { + Iterator it=nodeFilter.iterator(); + while (it.hasNext()) { + int i=((NodeFilter)it.next()).isNodeIncludeDO(currentNode,level); + if (i!=1) + return i; + } + } + if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode)) + return 0; + return 1; + } + int isVisibleInt(Node currentNode) { + if (nodeFilter!=null) { + Iterator it=nodeFilter.iterator(); + while (it.hasNext()) { + int i=((NodeFilter)it.next()).isNodeInclude(currentNode); + if (i!=1) + return i; + } + } + if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode)) + return 0; + return 1; + } boolean isVisible(Node currentNode) { if (nodeFilter!=null) { Iterator it=nodeFilter.iterator(); while (it.hasNext()) { - if (!((NodeFilter)it.next()).isNodeInclude(currentNode)) + if (((NodeFilter)it.next()).isNodeInclude(currentNode)!=1) return false; } } @@ -533,19 +560,42 @@ return true; } + void handleParent(Element e,NameSpaceSymbTable ns) { + if (!e.hasAttributes()) { + return; + } + NamedNodeMap attrs = e.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr N = (Attr) attrs.item(i); + if (Constants.NamespaceSpecNS!=N.getNamespaceURI()) { + //Not a namespace definition, ignore. + continue; + } + + String NName=N.getLocalName(); + String NValue=N.getNodeValue(); + if (XML.equals(NName) + && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { + continue; + } + ns.addMapping(NName,NValue,N); + } + } + /** * Adds to ns the definitons from the parent elements of el * @param el * @param ns */ - final static void getParentNameSpaces(Element el,NameSpaceSymbTable ns) { - List parents=new ArrayList(); + final void getParentNameSpaces(Element el,NameSpaceSymbTable ns) { + List parents=new ArrayList(10); Node n1=el.getParentNode(); if (!(n1 instanceof Element)) { return; } //Obtain all the parents of the elemnt - Element parent=(Element) el.getParentNode(); + Element parent=(Element) n1; while (parent!=null) { parents.add(parent); Node n=parent.getParentNode(); @@ -557,28 +607,9 @@ //Visit them in reverse order. ListIterator it=parents.listIterator(parents.size()); while (it.hasPrevious()) { - Element ele=(Element)it.previous(); - if (!ele.hasAttributes()) { - continue; + Element ele=(Element)it.previous(); + handleParent(ele, ns); } - NamedNodeMap attrs = ele.getAttributes(); - int attrsLength = attrs.getLength(); - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - if (!Constants.NamespaceSpecNS.equals(N.getNamespaceURI())) { - //Not a namespace definition, ignore. - continue; - } - - String NName=N.getLocalName(); - String NValue=N.getNodeValue(); - if (XML.equals(NName) - && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { - continue; - } - ns.addMapping(NName,NValue,N); - } - } Attr nsprefix; if (((nsprefix=ns.getMappingWithoutRendered("xmlns"))!=null) && "".equals(nsprefix.getValue())) { @@ -586,269 +617,6 @@ } } /** - * Outputs an Attribute to the internal Writer. - * - * The string value of the node is modified by replacing - *
    - *
  • all ampersands (&) with &amp;
  • - *
  • all open angle brackets (<) with &lt;
  • - *
  • all quotation mark characters with &quot;
  • - *
  • and the whitespace characters #x9, #xA, and #xD, with character - * references. The character references are written in uppercase - * hexadecimal with no leading zeroes (for example, #xD is represented - * by the character reference &#xD;)
  • - *
- * - * @param name - * @param value - * @param writer - * @throws IOException - */ - static final void outputAttrToWriter(final String name, final String value, final OutputStream writer) throws IOException { - writer.write(' '); - writeStringToUtf8(name,writer); - writer.write(equalsStr); - byte []toWrite; - final int length = value.length(); - for (int i=0;i < length; i++) { - char c = value.charAt(i); - - switch (c) { - - case '&' : - toWrite=_AMP_; - //writer.write(_AMP_); - break; - - case '<' : - toWrite=_LT_; - //writer.write(_LT_); - break; - - case '"' : - toWrite=_QUOT_; - //writer.write(_QUOT_); - break; - - case 0x09 : // '\t' - toWrite=__X9_; - //writer.write(__X9_); - break; - - case 0x0A : // '\n' - toWrite=__XA_; - //writer.write(__XA_); - break; - - case 0x0D : // '\r' - toWrite=__XD_; - //writer.write(__XD_); - break; - - default : - writeCharToUtf8(c,writer); - //this._writer.write(c); - continue; - } - writer.write(toWrite); - } - - writer.write('\"'); - } - - final static void writeCharToUtf8(final char c,final OutputStream out) throws IOException{ - char ch; - if (/*(c >= 0x0001) &&*/ (c <= 0x007F)) { - out.write(c); - return; - } - int bias; - int write; - if (c > 0x07FF) { - ch=(char)(c>>>12); - write=0xE0; - if (ch>0) { - write |= ( ch & 0x0F); - } - out.write(write); - write=0x80; - bias=0x3F; - } else { - write=0xC0; - bias=0x1F; - } - ch=(char)(c>>>6); - if (ch>0) { - write|= (ch & bias); - } - out.write(write); - out.write(0x80 | ((c) & 0x3F)); - - } - - final static void writeStringToUtf8(final String str,final OutputStream out) throws IOException{ - final int length=str.length(); - int i=0; - char c; - while (i= 0x0001) &&*/ (c <= 0x007F)) { - out.write(c); - continue; - } - char ch; - int bias; - int write; - if (c > 0x07FF) { - ch=(char)(c>>>12); - write=0xE0; - if (ch>0) { - write |= ( ch & 0x0F); - } - out.write(write); - write=0x80; - bias=0x3F; - } else { - write=0xC0; - bias=0x1F; - } - ch=(char)(c>>>6); - if (ch>0) { - write|= (ch & bias); - } - out.write(write); - out.write(0x80 | ((c) & 0x3F)); - continue; - - } - - } - /** - * Outputs a PI to the internal Writer. - * - * @param currentPI - * @param writer where to write the things - * @throws IOException - */ - static final void outputPItoWriter(ProcessingInstruction currentPI, OutputStream writer) throws IOException { - final int position = getPositionRelativeToDocumentElement(currentPI); - - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - writer.write('\n'); - } - writer.write(_BEGIN_PI); - - final String target = currentPI.getTarget(); - int length = target.length(); - - for (int i = 0; i < length; i++) { - char c=target.charAt(i); - if (c==0x0D) { - writer.write(__XD_); - } else { - writeCharToUtf8(c,writer); - } - } - - final String data = currentPI.getData(); - - length = data.length(); - - if (length > 0) { - writer.write(' '); - - for (int i = 0; i < length; i++) { - char c=data.charAt(i); - if (c==0x0D) { - writer.write(__XD_); - } else { - writeCharToUtf8(c,writer); - } - } - } - - writer.write(_END_PI); - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - writer.write('\n'); - } - } - - /** - * Method outputCommentToWriter - * - * @param currentComment - * @param writer writer where to write the things - * @throws IOException - */ - static final void outputCommentToWriter(Comment currentComment, OutputStream writer) throws IOException { - final int position = getPositionRelativeToDocumentElement(currentComment); - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - writer.write('\n'); - } - writer.write(_BEGIN_COMM); - - final String data = currentComment.getData(); - final int length = data.length(); - - for (int i = 0; i < length; i++) { - char c=data.charAt(i); - if (c==0x0D) { - writer.write(__XD_); - } else { - writeCharToUtf8(c,writer); - } - } - - writer.write(_END_COMM); - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - writer.write('\n'); - } - } - - /** - * Outputs a Text of CDATA section to the internal Writer. - * - * @param text - * @param writer writer where to write the things - * @throws IOException - */ - static final void outputTextToWriter(final String text, final OutputStream writer) throws IOException { - final int length = text.length(); - byte []toWrite; - for (int i = 0; i < length; i++) { - char c = text.charAt(i); - - switch (c) { - - case '&' : - toWrite=_AMP_; - //writer.write(_AMP_); - break; - - case '<' : - toWrite=_LT_; - //writer.write(_LT_); - break; - - case '>' : - toWrite=_GT_; - //writer.write(_GT_); - break; - - case 0xD : - toWrite=__XD_; - //writer.write(__XD_); - break; - - default : - writeCharToUtf8(c,writer); - continue; - } - writer.write(toWrite); - } - } - - /** * Obtain the attributes to output for this node in XPathNodeSet c14n. * * @param E @@ -870,13 +638,207 @@ abstract Iterator handleAttributesSubtree(Element E, NameSpaceSymbTable ns) throws CanonicalizationException; + abstract void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException; + /** + * Outputs an Attribute to the internal Writer. + * + * The string value of the node is modified by replacing + *
    + *
  • all ampersands (&) with &amp;
  • + *
  • all open angle brackets (<) with &lt;
  • + *
  • all quotation mark characters with &quot;
  • + *
  • and the whitespace characters #x9, #xA, and #xD, with character + * references. The character references are written in uppercase + * hexadecimal with no leading zeroes (for example, #xD is represented + * by the character reference &#xD;)
  • + *
+ * + * @param name + * @param value + * @param writer + * @throws IOException + */ + static final void outputAttrToWriter(final String name, final String value, final OutputStream writer, + final Map cache) throws IOException { + writer.write(' '); + UtfHelpper.writeByte(name,writer,cache); + writer.write(equalsStr); + byte []toWrite; + final int length = value.length(); + int i=0; + while (i < length) { + char c = value.charAt(i++); + + switch (c) { + + case '&' : + toWrite=_AMP_; + break; + + case '<' : + toWrite=_LT_; + break; + + case '"' : + toWrite=_QUOT_; + break; + + case 0x09 : // '\t' + toWrite=__X9_; + break; + + case 0x0A : // '\n' + toWrite=__XA_; + break; + + case 0x0D : // '\r' + toWrite=__XD_; + break; + + default : + if (c < 0x80 ) { + writer.write(c); + } else { + UtfHelpper.writeCharToUtf8(c,writer); + }; + continue; + } + writer.write(toWrite); + } + + writer.write('\"'); + } + + /** + * Outputs a PI to the internal Writer. + * + * @param currentPI + * @param writer where to write the things + * @throws IOException + */ + static final void outputPItoWriter(ProcessingInstruction currentPI, OutputStream writer,int position) throws IOException { + + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + writer.write('\n'); + } + writer.write(_BEGIN_PI); + + final String target = currentPI.getTarget(); + int length = target.length(); - /** - * @param _writer The _writer to set. - */ - public void setWriter(OutputStream _writer) { - this._writer = _writer; - } + for (int i = 0; i < length; i++) { + char c=target.charAt(i); + if (c==0x0D) { + writer.write(__XD_); + } else { + if (c < 0x80) { + writer.write(c); + } else { + UtfHelpper.writeCharToUtf8(c,writer); + }; + } + } + + final String data = currentPI.getData(); + + length = data.length(); + + if (length > 0) { + writer.write(' '); + + for (int i = 0; i < length; i++) { + char c=data.charAt(i); + if (c==0x0D) { + writer.write(__XD_); + } else { + UtfHelpper.writeCharToUtf8(c,writer); + } + } + } + + writer.write(_END_PI); + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + writer.write('\n'); + } + } + + /** + * Method outputCommentToWriter + * + * @param currentComment + * @param writer writer where to write the things + * @throws IOException + */ + static final void outputCommentToWriter(Comment currentComment, OutputStream writer,int position) throws IOException { + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + writer.write('\n'); + } + writer.write(_BEGIN_COMM); + + final String data = currentComment.getData(); + final int length = data.length(); + + for (int i = 0; i < length; i++) { + char c=data.charAt(i); + if (c==0x0D) { + writer.write(__XD_); + } else { + if (c < 0x80) { + writer.write(c); + } else { + UtfHelpper.writeCharToUtf8(c,writer); + }; + } + } + + writer.write(_END_COMM); + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + writer.write('\n'); + } + } + + /** + * Outputs a Text of CDATA section to the internal Writer. + * + * @param text + * @param writer writer where to write the things + * @throws IOException + */ + static final void outputTextToWriter(final String text, final OutputStream writer) throws IOException { + final int length = text.length(); + byte []toWrite; + for (int i = 0; i < length; i++) { + char c = text.charAt(i); + + switch (c) { + + case '&' : + toWrite=_AMP_; + break; + + case '<' : + toWrite=_LT_; + break; + + case '>' : + toWrite=_GT_; + break; + + case 0xD : + toWrite=__XD_; + break; + + default : + if (c < 0x80) { + writer.write(c); + } else { + UtfHelpper.writeCharToUtf8(c,writer); + }; + continue; + } + writer.write(toWrite); + } + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,16 +20,10 @@ */ package com.sun.org.apache.xml.internal.security.c14n.implementations; -import java.lang.reflect.Array; -import java.util.AbstractList; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.HashMap; import java.util.Iterator; import java.util.List; -import java.util.Map; - import org.w3c.dom.Attr; @@ -46,21 +40,26 @@ public class NameSpaceSymbTable { /**The map betwen prefix-> entry table. */ - SymbMap symb = new SymbMap(); + SymbMap symb; /**The level of nameSpaces (for Inclusive visibility).*/ int nameSpaces=0; /**The stacks for removing the definitions when doing pop.*/ - List level = new ArrayList(); + List level; boolean cloned=true; static final String XMLNS="xmlns"; + final static SymbMap initialMap=new SymbMap(); + static { + NameSpaceSymbEntry ne=new NameSpaceSymbEntry("",null,true,XMLNS); + ne.lastrendered=""; + initialMap.put(XMLNS,ne); + } /** * Default constractor **/ public NameSpaceSymbTable() { + level = new ArrayList(10); //Insert the default binding for xmlns. - NameSpaceSymbEntry ne=new NameSpaceSymbEntry("",null,true); - ne.lastrendered=""; - symb.put(XMLNS,ne); + symb=(SymbMap) initialMap.clone(); } /** @@ -75,8 +74,14 @@ NameSpaceSymbEntry n=(NameSpaceSymbEntry)(it.next()); //put them rendered? if ((!n.rendered) && (n.n!=null)) { + n=(NameSpaceSymbEntry) n.clone(); + needsClone(); + symb.put(n.prefix,n); + n.lastrendered=n.uri; + n.rendered=true; + result.add(n.n); - n.rendered=true; + } } } @@ -104,10 +109,6 @@ **/ public void push() { //Put the number of namespace definitions in the stack. - /**if (cloned) { - Object ob[]= {symb,cloned ? symb : null}; - level.add(ob); - } **/ level.add(null); cloned=false; } @@ -124,7 +125,7 @@ if (size==0) { cloned=false; } else - cloned=(level.get(size-1)!=symb); + cloned=(level.get(size-1)!=symb); } else { cloned=false; } @@ -134,8 +135,7 @@ final void needsClone() { if (!cloned) { - level.remove(level.size()-1); - level.add(symb); + level.set(level.size()-1,symb); symb=(SymbMap) symb.clone(); cloned=true; } @@ -200,7 +200,7 @@ return false; } //Creates and entry in the table for this new definition. - NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,false); + NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,false,prefix); needsClone(); symb.put(prefix, ne); if (ob != null) { @@ -238,7 +238,7 @@ return null; } - NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,true); + NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,true,prefix); ne.lastrendered=uri; needsClone(); symb.put(prefix, ne); @@ -251,53 +251,38 @@ } return ne.n; } - /** - * Adds & gets(if needed) the attribute node that defines the binding for the prefix. - * Take on account if the rules of rendering in the inclusive c14n. - * For inclusive c14n. - * @param prefix the prefix to obtain the attribute. - * @param outputNode the container element is an output element. - * @param uri the Uri of the definition - * @param n the attribute that have the definition - * @return null if there is no need to render the prefix. Otherwise the node of - * definition. - **/ - public Node addMappingAndRenderXNodeSet(String prefix, String uri,Attr n,boolean outputNode) { + + public int getLevel() { + // TODO Auto-generated method stub + return level.size(); + } + + public void removeMapping(String prefix) { NameSpaceSymbEntry ob = symb.get(prefix); - int visibleNameSpaces=nameSpaces; - if ((ob!=null) && uri.equals(ob.uri)) { - if (!ob.rendered) { - ob=(NameSpaceSymbEntry)ob.clone(); - needsClone(); - symb.put(prefix,ob); - ob.rendered=true; - ob.level=visibleNameSpaces; - return ob.n; - } - ob=(NameSpaceSymbEntry)ob.clone(); + + if (ob!=null) { + needsClone(); + symb.put(prefix,null); + } + } + + public void removeMappingIfNotRender(String prefix) { + NameSpaceSymbEntry ob = symb.get(prefix); + + if (ob!=null && !ob.rendered) { needsClone(); - symb.put(prefix,ob); - if (outputNode && (((visibleNameSpaces-ob.level)<2) || XMLNS.equals(prefix)) ) { - ob.level=visibleNameSpaces; - return null; //Already rendered, just return nulll - } - ob.level=visibleNameSpaces; - return ob.n; - } + symb.put(prefix,null); + } + } - NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,true); - ne.level=nameSpaces; - ne.rendered=true; - needsClone(); - symb.put(prefix, ne); - if (ob != null) { - ne.lastrendered=ob.lastrendered; + public boolean removeMappingIfRender(String prefix) { + NameSpaceSymbEntry ob = symb.get(prefix); - if ((ob.lastrendered!=null)&& (ob.lastrendered.equals(uri))) { - ne.rendered=true; - } - } - return ne.n; + if (ob!=null && ob.rendered) { + needsClone(); + symb.put(prefix,null); + } + return false; } } @@ -305,10 +290,11 @@ * The internal structure of NameSpaceSymbTable. **/ class NameSpaceSymbEntry implements Cloneable { - NameSpaceSymbEntry(String name,Attr n,boolean rendered) { + NameSpaceSymbEntry(String name,Attr n,boolean rendered,String prefix) { this.uri=name; this.rendered=rendered; this.n=n; + this.prefix=prefix; } /** @inheritDoc */ public Object clone() { @@ -320,6 +306,7 @@ } /** The level where the definition was rendered(Only for inclusive) */ int level=0; + String prefix; /**The URI that the prefix defines */ String uri; /**The last output in the URI for this prefix (This for speed reason).*/ @@ -330,53 +317,57 @@ Attr n; }; -class SymbMap implements Cloneable{ - int free=23; - NameSpaceSymbEntry[] entries=new NameSpaceSymbEntry[free]; - String[] keys=new String[free]; - - void put(String key, NameSpaceSymbEntry value) { +class SymbMap implements Cloneable { + int free=23; + NameSpaceSymbEntry[] entries; + String[] keys; + SymbMap() { + entries=new NameSpaceSymbEntry[free]; + keys=new String[free]; + } + void put(String key, NameSpaceSymbEntry value) { int index = index(key); - Object oldKey = keys[index]; - keys[index] = key; - entries[index] = value; + Object oldKey = keys[index]; + keys[index] = key; + entries[index] = value; if (oldKey==null || !oldKey.equals(key)) { - if (--free == 0) { - free=entries.length; - int newCapacity = free<<2; - rehash(newCapacity); - } + if (--free == 0) { + free=entries.length; + int newCapacity = free<<2; + rehash(newCapacity); + } } } List entrySet() { - List a=new ArrayList(); - for (int i=0;iint value @@ -384,37 +375,38 @@ protected void rehash(int newCapacity) { int oldCapacity = keys.length; String oldKeys[] = keys; - NameSpaceSymbEntry oldVals[] = entries; + NameSpaceSymbEntry oldVals[] = entries; - keys = new String[newCapacity]; - entries = new NameSpaceSymbEntry[newCapacity]; + keys = new String[newCapacity]; + entries = new NameSpaceSymbEntry[newCapacity]; for (int i = oldCapacity; i-- > 0;) { if(oldKeys[i] != null) { String o = oldKeys[i]; int index = index(o); - keys[index] = o; - entries[index] = oldVals[i]; + keys[index] = o; + entries[index] = oldVals[i]; } } } - NameSpaceSymbEntry get(String key) { - return entries[index(key)]; - } - protected Object clone() { - // TODO Auto-generated method stub - try { - SymbMap copy=(SymbMap) super.clone(); - copy.entries=new NameSpaceSymbEntry[entries.length]; - System.arraycopy(entries,0,copy.entries,0,entries.length); - copy.keys=new String[keys.length]; - System.arraycopy(keys,0,copy.keys,0,keys.length); + + NameSpaceSymbEntry get(String key) { + return entries[index(key)]; + } - return copy; - } catch (CloneNotSupportedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return null; + protected Object clone() { + try { + SymbMap copy=(SymbMap) super.clone(); + copy.entries=new NameSpaceSymbEntry[entries.length]; + System.arraycopy(entries,0,copy.entries,0,entries.length); + copy.keys=new String[keys.length]; + System.arraycopy(keys,0,copy.keys,0,keys.length); + + return copy; + } catch (CloneNotSupportedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } + return null; + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,155 @@ +package com.sun.org.apache.xml.internal.security.c14n.implementations; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.Map; + +public class UtfHelpper { + + final static void writeByte(final String str,final OutputStream out,Map cache) throws IOException { + byte []result=(byte[]) cache.get(str); + if (result==null) { + result=getStringInUtf8(str); + cache.put(str,result); + } + + out.write(result); + + } + + final static void writeCharToUtf8(final char c,final OutputStream out) throws IOException{ + if (c < 0x80) { + out.write(c); + return; + } + if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ + //No Surrogates in sun java + out.write(0x3f); + return; + } + int bias; + int write; + char ch; + if (c > 0x07FF) { + ch=(char)(c>>>12); + write=0xE0; + if (ch>0) { + write |= ( ch & 0x0F); + } + out.write(write); + write=0x80; + bias=0x3F; + } else { + write=0xC0; + bias=0x1F; + } + ch=(char)(c>>>6); + if (ch>0) { + write|= (ch & bias); + } + out.write(write); + out.write(0x80 | ((c) & 0x3F)); + + } + + final static void writeStringToUtf8(final String str,final OutputStream out) throws IOException{ + final int length=str.length(); + int i=0; + char c; + while (i= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ + //No Surrogates in sun java + out.write(0x3f); + continue; + } + char ch; + int bias; + int write; + if (c > 0x07FF) { + ch=(char)(c>>>12); + write=0xE0; + if (ch>0) { + write |= ( ch & 0x0F); + } + out.write(write); + write=0x80; + bias=0x3F; + } else { + write=0xC0; + bias=0x1F; + } + ch=(char)(c>>>6); + if (ch>0) { + write|= (ch & bias); + } + out.write(write); + out.write(0x80 | ((c) & 0x3F)); + + } + + } + public final static byte[] getStringInUtf8(final String str) { + final int length=str.length(); + boolean expanded=false; + byte []result=new byte[length]; + int i=0; + int out=0; + char c; + while (i= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ + //No Surrogates in sun java + result[out++]=0x3f; + + continue; + } + if (!expanded) { + byte newResult[]=new byte[3*length]; + System.arraycopy(result, 0, newResult, 0, out); + result=newResult; + expanded=true; + } + char ch; + int bias; + byte write; + if (c > 0x07FF) { + ch=(char)(c>>>12); + write=(byte)0xE0; + if (ch>0) { + write |= ( ch & 0x0F); + } + result[out++]=write; + write=(byte)0x80; + bias=0x3F; + } else { + write=(byte)0xC0; + bias=0x1F; + } + ch=(char)(c>>>6); + if (ch>0) { + write|= (ch & bias); + } + result[out++]=write; + result[out++]=(byte)(0x80 | ((c) & 0x3F));/**/ + + } + if (expanded) { + byte newResult[]=new byte[out]; + System.arraycopy(result, 0, newResult, 0, out); + result=newResult; + } + return result; + } + + + +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java Wed Jul 05 16:42:37 2017 +0200 @@ -22,6 +22,7 @@ import java.io.ByteArrayOutputStream; +import java.io.InputStream; import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; @@ -30,6 +31,7 @@ import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; +import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; @@ -204,7 +206,7 @@ * @since 1.0. */ private XMLCipher() { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Constructing XMLCipher..."); + logger.log(java.util.logging.Level.FINE, "Constructing XMLCipher..."); _factory = new Factory(); _serializer = new Serializer(); @@ -266,7 +268,7 @@ public static XMLCipher getInstance(String transformation) throws XMLEncryptionException { // sanity checks - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Getting XMLCipher..."); + logger.log(java.util.logging.Level.FINE, "Getting XMLCipher..."); if (null == transformation) logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null..."); if(!isValidEncryptionAlgorithm(transformation)) @@ -294,7 +296,7 @@ try { instance._contextCipher = Cipher.getInstance(jceAlgorithm); - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "cihper.algoritm = " + + logger.log(java.util.logging.Level.FINE, "cihper.algoritm = " + instance._contextCipher.getAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLEncryptionException("empty", nsae); @@ -305,49 +307,6 @@ return (instance); } - public static XMLCipher getInstance(String transformation,Cipher cipher) throws - XMLEncryptionException { - // sanity checks - logger.log(java.util.logging.Level.FINE, "Getting XMLCipher..."); - if (null == transformation) - logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null..."); - if(!isValidEncryptionAlgorithm(transformation)) - logger.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS); - - XMLCipher instance = new XMLCipher(); - - instance._algorithm = transformation; - instance._key = null; - instance._kek = null; - - - /* Create a canonicaliser - used when serialising DOM to octets - * prior to encryption (and for the reverse) */ - - try { - instance._canon = Canonicalizer.getInstance - (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); - - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - - String jceAlgorithm = JCEMapper.translateURItoJCEID(transformation); - - try { - instance._contextCipher = cipher; - //Cipher.getInstance(jceAlgorithm); - logger.log(java.util.logging.Level.FINE, "cihper.algoritm = " + - instance._contextCipher.getAlgorithm()); - }catch(Exception ex) { - throw new XMLEncryptionException("empty", ex); - } - - return (instance); - } - - - /** * Returns an XMLCipher that implements the specified * transformation, operates on the specified context document and serializes @@ -380,6 +339,45 @@ return instance; } + public static XMLCipher getInstance(String transformation,Cipher cipher) throws XMLEncryptionException { + // sanity checks + logger.log(java.util.logging.Level.FINE, "Getting XMLCipher..."); + if (null == transformation) + logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null..."); + if(!isValidEncryptionAlgorithm(transformation)) + logger.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS); + + XMLCipher instance = new XMLCipher(); + + instance._algorithm = transformation; + instance._key = null; + instance._kek = null; + + + /* Create a canonicaliser - used when serialising DOM to octets + * prior to encryption (and for the reverse) */ + + try { + instance._canon = Canonicalizer.getInstance + (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); + + } catch (InvalidCanonicalizerException ice) { + throw new XMLEncryptionException("empty", ice); + } + + String jceAlgorithm = JCEMapper.translateURItoJCEID(transformation); + + try { + instance._contextCipher = cipher; + //Cipher.getInstance(jceAlgorithm); + logger.log(java.util.logging.Level.FINE, "cihper.algoritm = " + + instance._contextCipher.getAlgorithm()); + }catch(Exception ex) { + throw new XMLEncryptionException("empty", ex); + } + + return (instance); + } /** * Returns an XMLCipher that implements the specified @@ -396,7 +394,7 @@ public static XMLCipher getProviderInstance(String transformation, String provider) throws XMLEncryptionException { // sanity checks - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Getting XMLCipher..."); + logger.log(java.util.logging.Level.FINE, "Getting XMLCipher..."); if (null == transformation) logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null..."); if(null == provider) @@ -429,9 +427,9 @@ instance._contextCipher = Cipher.getInstance(jceAlgorithm, provider); - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "cipher._algorithm = " + + logger.log(java.util.logging.Level.FINE, "cipher._algorithm = " + instance._contextCipher.getAlgorithm()); - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "provider.name = " + provider); + logger.log(java.util.logging.Level.FINE, "provider.name = " + provider); } catch (NoSuchAlgorithmException nsae) { throw new XMLEncryptionException("empty", nsae); } catch (NoSuchProviderException nspre) { @@ -490,7 +488,7 @@ public static XMLCipher getInstance() throws XMLEncryptionException { // sanity checks - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Getting XMLCipher for no transformation..."); + logger.log(java.util.logging.Level.FINE, "Getting XMLCipher for no transformation..."); XMLCipher instance = new XMLCipher(); @@ -532,7 +530,7 @@ throws XMLEncryptionException { // sanity checks - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Getting XMLCipher, provider but no transformation"); + logger.log(java.util.logging.Level.FINE, "Getting XMLCipher, provider but no transformation"); if(null == provider) logger.log(java.util.logging.Level.SEVERE, "Provider unexpectedly null.."); if("" == provider) @@ -578,7 +576,7 @@ */ public void init(int opmode, Key key) throws XMLEncryptionException { // sanity checks - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Initializing XMLCipher..."); + logger.log(java.util.logging.Level.FINE, "Initializing XMLCipher..."); _ek = null; _ed = null; @@ -586,18 +584,18 @@ switch (opmode) { case ENCRYPT_MODE : - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "opmode = ENCRYPT_MODE"); + logger.log(java.util.logging.Level.FINE, "opmode = ENCRYPT_MODE"); _ed = createEncryptedData(CipherData.VALUE_TYPE, "NO VALUE YET"); break; case DECRYPT_MODE : - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "opmode = DECRYPT_MODE"); + logger.log(java.util.logging.Level.FINE, "opmode = DECRYPT_MODE"); break; case WRAP_MODE : - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "opmode = WRAP_MODE"); + logger.log(java.util.logging.Level.FINE, "opmode = WRAP_MODE"); _ek = createEncryptedKey(CipherData.VALUE_TYPE, "NO VALUE YET"); break; case UNWRAP_MODE : - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "opmode = UNWRAP_MODE"); + logger.log(java.util.logging.Level.FINE, "opmode = UNWRAP_MODE"); break; default : logger.log(java.util.logging.Level.SEVERE, "Mode unexpectedly invalid"); @@ -622,7 +620,7 @@ public EncryptedData getEncryptedData() { // Sanity checks - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Returning EncryptedData"); + logger.log(java.util.logging.Level.FINE, "Returning EncryptedData"); return _ed; } @@ -640,7 +638,7 @@ public EncryptedKey getEncryptedKey() { // Sanity checks - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Returning EncryptedKey"); + logger.log(java.util.logging.Level.FINE, "Returning EncryptedKey"); return _ek; } @@ -750,11 +748,11 @@ */ private Document encryptElement(Element element) throws Exception{ - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Encrypting element..."); + logger.log(java.util.logging.Level.FINE, "Encrypting element..."); if(null == element) logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); if(_cipherMode != ENCRYPT_MODE) - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); if (_algorithm == null) { throw new XMLEncryptionException("XMLCipher instance without transformation specified"); @@ -785,11 +783,11 @@ */ private Document encryptElementContent(Element element) throws /* XMLEncryption */Exception { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Encrypting element content..."); + logger.log(java.util.logging.Level.FINE, "Encrypting element content..."); if(null == element) logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); if(_cipherMode != ENCRYPT_MODE) - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); if (_algorithm == null) { throw new XMLEncryptionException("XMLCipher instance without transformation specified"); @@ -815,7 +813,7 @@ */ public Document doFinal(Document context, Document source) throws /* XMLEncryption */Exception { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Processing source document..."); + logger.log(java.util.logging.Level.FINE, "Processing source document..."); if(null == context) logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); if(null == source) @@ -855,7 +853,7 @@ */ public Document doFinal(Document context, Element element) throws /* XMLEncryption */Exception { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Processing source element..."); + logger.log(java.util.logging.Level.FINE, "Processing source element..."); if(null == context) logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); if(null == element) @@ -898,7 +896,7 @@ */ public Document doFinal(Document context, Element element, boolean content) throws /* XMLEncryption*/ Exception { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Processing source element..."); + logger.log(java.util.logging.Level.FINE, "Processing source element..."); if(null == context) logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); if(null == element) @@ -954,6 +952,34 @@ /** * Returns an EncryptedData interface. Use this operation if + * you want to have full control over the serialization of the element + * or element content. + * + * This does not change the source document in any way. + * + * @param context the context Document. + * @param type a URI identifying type information about the plaintext form + * of the encrypted content (may be null) + * @param serializedData the serialized data + * @return the EncryptedData + * @throws Exception + */ + public EncryptedData encryptData(Document context, String type, + InputStream serializedData) throws Exception { + + logger.log(java.util.logging.Level.FINE, "Encrypting element..."); + if (null == context) + logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); + if (null == serializedData) + logger.log(java.util.logging.Level.SEVERE, "Serialized data unexpectedly null..."); + if (_cipherMode != ENCRYPT_MODE) + logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + + return encryptData(context, null, type, serializedData); + } + + /** + * Returns an EncryptedData interface. Use this operation if * you want to have full control over the contents of the * EncryptedData structure. * @@ -966,160 +992,60 @@ * @return the EncryptedData * @throws Exception */ - public EncryptedData encryptData(Document context, Element element, boolean contentMode) throws - /* XMLEncryption */ Exception { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Encrypting element..."); - if (null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if (null == element) - logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); - if (_cipherMode != ENCRYPT_MODE) - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); - - _contextDocument = context; - - if (_algorithm == null) { - throw new XMLEncryptionException("XMLCipher instance without transformation specified"); - } - - String serializedOctets = null; - if (contentMode) { - NodeList children = element.getChildNodes(); - if ((null != children)) { - serializedOctets = _serializer.serialize(children); - } else { - Object exArgs[] = { "Element has no content." }; - throw new XMLEncryptionException("empty", exArgs); - } - } else { - serializedOctets = _serializer.serialize(element); - } - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Serialized octets:\n" + serializedOctets); - - byte[] encryptedBytes = null; - - // Now create the working cipher if none was created already - Cipher c; - if (_contextCipher == null) { - String jceAlgorithm = - JCEMapper.translateURItoJCEID(_algorithm); - - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm); - - try { - if (_requestedJCEProvider == null) - c = Cipher.getInstance(jceAlgorithm); - else - c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); - } catch (NoSuchProviderException nspre) { - throw new XMLEncryptionException("empty", nspre); - } catch (NoSuchPaddingException nspae) { - throw new XMLEncryptionException("empty", nspae); - } - } - else { - c = _contextCipher; - } - // Now perform the encryption - - try { - // Should internally generate an IV - // todo - allow user to set an IV - c.init(_cipherMode, _key); - } catch (InvalidKeyException ike) { - throw new XMLEncryptionException("empty", ike); - } - - try { - encryptedBytes = - c.doFinal(serializedOctets.getBytes("UTF-8")); - - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " + - Integer.toString(c.getOutputSize( - serializedOctets.getBytes().length))); - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = " + - Integer.toString(encryptedBytes.length)); - } catch (IllegalStateException ise) { - throw new XMLEncryptionException("empty", ise); - } catch (IllegalBlockSizeException ibse) { - throw new XMLEncryptionException("empty", ibse); - } catch (BadPaddingException bpe) { - throw new XMLEncryptionException("empty", bpe); - } catch (UnsupportedEncodingException uee) { - throw new XMLEncryptionException("empty", uee); - } - - // Now build up to a properly XML Encryption encoded octet stream - // IvParameterSpec iv; - - byte[] iv = c.getIV(); - byte[] finalEncryptedBytes = - new byte[iv.length + encryptedBytes.length]; - System.arraycopy(iv, 0, finalEncryptedBytes, 0, - iv.length); - System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, - iv.length, - encryptedBytes.length); - - String base64EncodedEncryptedOctets = Base64.encode(finalEncryptedBytes); - - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Encrypted octets length = " + - base64EncodedEncryptedOctets.length()); - - try { - CipherData cd = _ed.getCipherData(); - CipherValue cv = cd.getCipherValue(); - // cv.setValue(base64EncodedEncryptedOctets.getBytes()); - cv.setValue(base64EncodedEncryptedOctets); - - if (contentMode) { - _ed.setType( - new URI(EncryptionConstants.TYPE_CONTENT).toString()); - } else { - _ed.setType( - new URI(EncryptionConstants.TYPE_ELEMENT).toString()); - } - EncryptionMethod method = - _factory.newEncryptionMethod(new URI(_algorithm).toString()); - _ed.setEncryptionMethod(method); - } catch (URI.MalformedURIException mfue) { - throw new XMLEncryptionException("empty", mfue); - } - return (_ed); - } - - - - public EncryptedData encryptData(Document context, byte [] serializedOctets, boolean contentMode) throws - /* XMLEncryption */ Exception { + public EncryptedData encryptData( + Document context, Element element, boolean contentMode) + throws /* XMLEncryption */ Exception { + logger.log(java.util.logging.Level.FINE, "Encrypting element..."); if (null == context) logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if (null == serializedOctets) - logger.log(java.util.logging.Level.SEVERE, "Canonicalized Data is unexpectedly null..."); + if (null == element) + logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); if (_cipherMode != ENCRYPT_MODE) logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + if (contentMode) { + return encryptData + (context, element, EncryptionConstants.TYPE_CONTENT, null); + } else { + return encryptData + (context, element, EncryptionConstants.TYPE_ELEMENT, null); + } + } + + private EncryptedData encryptData( + Document context, Element element, String type, + InputStream serializedData) throws /* XMLEncryption */ Exception { + _contextDocument = context; if (_algorithm == null) { - throw new XMLEncryptionException("XMLCipher instance without transformation specified"); + throw new XMLEncryptionException + ("XMLCipher instance without transformation specified"); } - - logger.log(java.util.logging.Level.FINE, "Serialized octets:\n" + serializedOctets); + String serializedOctets = null; + if (serializedData == null) { + if (type == EncryptionConstants.TYPE_CONTENT) { + NodeList children = element.getChildNodes(); + if (null != children) { + serializedOctets = _serializer.serialize(children); + } else { + Object exArgs[] = { "Element has no content." }; + throw new XMLEncryptionException("empty", exArgs); + } + } else { + serializedOctets = _serializer.serialize(element); + } + logger.log(java.util.logging.Level.FINE, "Serialized octets:\n" + serializedOctets); + } byte[] encryptedBytes = null; // Now create the working cipher if none was created already Cipher c; if (_contextCipher == null) { - String jceAlgorithm = - JCEMapper.translateURItoJCEID(_algorithm); - + String jceAlgorithm = JCEMapper.translateURItoJCEID(_algorithm); logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm); try { @@ -1148,41 +1074,47 @@ } try { - encryptedBytes = - c.doFinal(serializedOctets); - - logger.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " + + if (serializedData != null) { + int numBytes; + byte[] buf = new byte[8192]; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + while ((numBytes = serializedData.read(buf)) != -1) { + byte[] data = c.update(buf, 0, numBytes); + baos.write(data); + } + baos.write(c.doFinal()); + encryptedBytes = baos.toByteArray(); + } else { + encryptedBytes = c.doFinal(serializedOctets.getBytes("UTF-8")); + logger.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " + Integer.toString(c.getOutputSize( - serializedOctets.length))); + serializedOctets.getBytes().length))); + } logger.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = " + - Integer.toString(encryptedBytes.length)); + Integer.toString(encryptedBytes.length)); } catch (IllegalStateException ise) { throw new XMLEncryptionException("empty", ise); } catch (IllegalBlockSizeException ibse) { throw new XMLEncryptionException("empty", ibse); } catch (BadPaddingException bpe) { throw new XMLEncryptionException("empty", bpe); - } catch (Exception uee) { + } catch (UnsupportedEncodingException uee) { throw new XMLEncryptionException("empty", uee); } // Now build up to a properly XML Encryption encoded octet stream // IvParameterSpec iv; - byte[] iv = c.getIV(); byte[] finalEncryptedBytes = new byte[iv.length + encryptedBytes.length]; - System.arraycopy(iv, 0, finalEncryptedBytes, 0, - iv.length); - System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, - iv.length, - encryptedBytes.length); - + System.arraycopy(iv, 0, finalEncryptedBytes, 0, iv.length); + System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length, + encryptedBytes.length); String base64EncodedEncryptedOctets = Base64.encode(finalEncryptedBytes); logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); logger.log(java.util.logging.Level.FINE, "Encrypted octets length = " + - base64EncodedEncryptedOctets.length()); + base64EncodedEncryptedOctets.length()); try { CipherData cd = _ed.getCipherData(); @@ -1190,15 +1122,11 @@ // cv.setValue(base64EncodedEncryptedOctets.getBytes()); cv.setValue(base64EncodedEncryptedOctets); - if (contentMode) { - _ed.setType( - new URI(EncryptionConstants.TYPE_CONTENT).toString()); - } else { - _ed.setType( - new URI(EncryptionConstants.TYPE_ELEMENT).toString()); + if (type != null) { + _ed.setType(new URI(type).toString()); } EncryptionMethod method = - _factory.newEncryptionMethod(new URI(_algorithm).toString()); + _factory.newEncryptionMethod(new URI(_algorithm).toString()); _ed.setEncryptionMethod(method); } catch (URI.MalformedURIException mfue) { throw new XMLEncryptionException("empty", mfue); @@ -1206,7 +1134,6 @@ return (_ed); } - /** * Returns an EncryptedData interface. Use this operation if * you want to load an EncryptedData structure from a DOM @@ -1219,7 +1146,7 @@ */ public EncryptedData loadEncryptedData(Document context, Element element) throws XMLEncryptionException { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Loading encrypted element..."); + logger.log(java.util.logging.Level.FINE, "Loading encrypted element..."); if(null == context) logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); if(null == element) @@ -1246,13 +1173,13 @@ public EncryptedKey loadEncryptedKey(Document context, Element element) throws XMLEncryptionException { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Loading encrypted key..."); + logger.log(java.util.logging.Level.FINE, "Loading encrypted key..."); if(null == context) logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); if(null == element) logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); if(_cipherMode != UNWRAP_MODE && _cipherMode != DECRYPT_MODE) - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE or DECRYPT_MODE..."); + logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE or DECRYPT_MODE..."); _contextDocument = context; _ek = _factory.newEncryptedKey(element); @@ -1290,12 +1217,12 @@ public EncryptedKey encryptKey(Document doc, Key key) throws XMLEncryptionException { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Encrypting key ..."); + logger.log(java.util.logging.Level.FINE, "Encrypting key ..."); if(null == key) logger.log(java.util.logging.Level.SEVERE, "Key unexpectedly null..."); if(_cipherMode != WRAP_MODE) - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE..."); + logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE..."); if (_algorithm == null) { @@ -1313,7 +1240,7 @@ String jceAlgorithm = JCEMapper.translateURItoJCEID(_algorithm); - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm); + logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm); try { if (_requestedJCEProvider == null) @@ -1345,8 +1272,8 @@ String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes); - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets); - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Encrypted key octets length = " + + logger.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets); + logger.log(java.util.logging.Level.FINE, "Encrypted key octets length = " + base64EncodedEncryptedOctets.length()); CipherValue cv = _ek.getCipherData().getCipherValue(); @@ -1376,10 +1303,10 @@ public Key decryptKey(EncryptedKey encryptedKey, String algorithm) throws XMLEncryptionException { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey..."); + logger.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey..."); if(_cipherMode != UNWRAP_MODE) - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE..."); + logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE..."); if (algorithm == null) { throw new XMLEncryptionException("Cannot decrypt a key without knowing the algorithm"); @@ -1387,7 +1314,7 @@ if (_key == null) { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Trying to find a KEK via key resolvers"); + logger.log(java.util.logging.Level.FINE, "Trying to find a KEK via key resolvers"); KeyInfo ki = encryptedKey.getKeyInfo(); if (ki != null) { @@ -1418,7 +1345,7 @@ JCEMapper.translateURItoJCEID( encryptedKey.getEncryptionMethod().getAlgorithm()); - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm); + logger.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm); try { if (_requestedJCEProvider == null) @@ -1448,7 +1375,7 @@ throw new XMLEncryptionException("empty", nsae); } - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK"); + logger.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK"); return ret; @@ -1478,14 +1405,9 @@ * * @param node the Node to clear. */ - private void removeContent(Node node) { - NodeList list = node.getChildNodes(); - if (list.getLength() > 0) { - Node n = list.item(0); - if (null != n) { - n.getParentNode().removeChild(n); - } - removeContent(node); + private static void removeContent(Node node) { + while (node.hasChildNodes()) { + node.removeChild(node.getFirstChild()); } } @@ -1499,7 +1421,7 @@ private Document decryptElement(Element element) throws XMLEncryptionException { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Decrypting element..."); + logger.log(java.util.logging.Level.FINE, "Decrypting element..."); if(_cipherMode != DECRYPT_MODE) logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); @@ -1512,7 +1434,7 @@ } - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + octets); + logger.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + octets); Node sourceParent = element.getParentNode(); @@ -1573,7 +1495,7 @@ public byte[] decryptToByteArray(Element element) throws XMLEncryptionException { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Decrypting to ByteArray..."); + logger.log(java.util.logging.Level.FINE, "Decrypting to ByteArray..."); if(_cipherMode != DECRYPT_MODE) logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); @@ -2226,7 +2148,7 @@ AgreementMethod newAgreementMethod(Element element) throws XMLEncryptionException { if (null == element) { - //complain + throw new NullPointerException("element is null"); } String algorithm = element.getAttributeNS(null, @@ -2292,7 +2214,7 @@ CipherData newCipherData(Element element) throws XMLEncryptionException { if (null == element) { - // complain + throw new NullPointerException("element is null"); } int type = 0; @@ -2352,7 +2274,7 @@ (Element) transformsElements.item(0); if (transformsElement != null) { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element"); + logger.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element"); try { result.setTransforms(new TransformsImpl(transformsElement)); } @@ -2411,34 +2333,28 @@ XMLEncryptionException { EncryptedData result = null; - NodeList dataElements = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERDATA); - - // Need to get the last CipherData found, as earlier ones will - // be for elements in the KeyInfo lists + NodeList dataElements = element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_CIPHERDATA); + + // Need to get the last CipherData found, as earlier ones will + // be for elements in the KeyInfo lists Element dataElement = - (Element) dataElements.item(dataElements.getLength() - 1); + (Element) dataElements.item(dataElements.getLength() - 1); CipherData data = newCipherData(dataElement); result = newEncryptedData(data); - try { - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); - result.setType(new URI( - element.getAttributeNS( - null, EncryptionConstants._ATT_TYPE)).toString()); - result.setMimeType(element.getAttributeNS( - null, EncryptionConstants._ATT_MIMETYPE)); - result.setEncoding(new URI( - element.getAttributeNS( - null, Constants._ATT_ENCODING)).toString()); - } catch (URI.MalformedURIException mfue) { - // do nothing - } + result.setId(element.getAttributeNS( + null, EncryptionConstants._ATT_ID)); + result.setType( + element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); + result.setMimeType(element.getAttributeNS( + null, EncryptionConstants._ATT_MIMETYPE)); + result.setEncoding( + element.getAttributeNS(null, Constants._ATT_ENCODING)); Element encryptionMethodElement = (Element) element.getElementsByTagNameNS( @@ -2450,18 +2366,18 @@ } // BFL 16/7/03 - simple implementation - // TODO: Work out how to handle relative URI + // TODO: Work out how to handle relative URI Element keyInfoElement = (Element) element.getElementsByTagNameNS( Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0); if (null != keyInfoElement) { - try { - result.setKeyInfo(new KeyInfo(keyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("Error loading Key Info", - xse); - } + try { + result.setKeyInfo(new KeyInfo(keyInfoElement, null)); + } catch (XMLSecurityException xse) { + throw new XMLEncryptionException("Error loading Key Info", + xse); + } } // TODO: Implement @@ -2511,31 +2427,25 @@ EncryptedKey newEncryptedKey(Element element) throws XMLEncryptionException { EncryptedKey result = null; - NodeList dataElements = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERDATA); + NodeList dataElements = element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_CIPHERDATA); Element dataElement = - (Element) dataElements.item(dataElements.getLength() - 1); + (Element) dataElements.item(dataElements.getLength() - 1); CipherData data = newCipherData(dataElement); result = newEncryptedKey(data); - try { - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); - result.setType(new URI( - element.getAttributeNS( - null, EncryptionConstants._ATT_TYPE)).toString()); - result.setMimeType(element.getAttributeNS( - null, EncryptionConstants._ATT_MIMETYPE)); - result.setEncoding(new URI( - element.getAttributeNS( - null, Constants._ATT_ENCODING)).toString()); - result.setRecipient(element.getAttributeNS( - null, EncryptionConstants._ATT_RECIPIENT)); - } catch (URI.MalformedURIException mfue) { - // do nothing - } + result.setId(element.getAttributeNS( + null, EncryptionConstants._ATT_ID)); + result.setType( + element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); + result.setMimeType(element.getAttributeNS( + null, EncryptionConstants._ATT_MIMETYPE)); + result.setEncoding( + element.getAttributeNS(null, Constants._ATT_ENCODING)); + result.setRecipient(element.getAttributeNS( + null, EncryptionConstants._ATT_RECIPIENT)); Element encryptionMethodElement = (Element) element.getElementsByTagNameNS( @@ -2550,12 +2460,12 @@ (Element) element.getElementsByTagNameNS( Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0); if (null != keyInfoElement) { - try { - result.setKeyInfo(new KeyInfo(keyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("Error loading Key Info", - xse); - } + try { + result.setKeyInfo(new KeyInfo(keyInfoElement, null)); + } catch (XMLSecurityException xse) { + throw new XMLEncryptionException + ("Error loading Key Info", xse); + } } // TODO: Implement @@ -2581,7 +2491,8 @@ EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CARRIEDKEYNAME).item(0); if (null != carriedNameElement) { - result.setCarriedName(carriedNameElement.getNodeValue()); + result.setCarriedName + (carriedNameElement.getFirstChild().getNodeValue()); } return (result); @@ -2680,13 +2591,8 @@ EncryptionProperty newEncryptionProperty(Element element) { EncryptionProperty result = newEncryptionProperty(); - try { - result.setTarget(new URI( - element.getAttributeNS( - null, EncryptionConstants._ATT_TARGET)).toString()); - } catch (URI.MalformedURIException mfue) { - // do nothing - } + result.setTarget( + element.getAttributeNS(null, EncryptionConstants._ATT_TARGET)); result.setId(element.getAttributeNS( null, EncryptionConstants._ATT_ID)); // TODO: Make this lot work... @@ -2943,7 +2849,7 @@ } catch (URI.MalformedURIException mfue) { //complain } - algorithm = tmpAlgorithm.toString(); + algorithmURI = tmpAlgorithm.toString(); } // @@ -3183,7 +3089,7 @@ _contextDocument, EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERVALUE); result.appendChild(_contextDocument.createTextNode( - new String(cipherValue))); + cipherValue)); return (result); } @@ -3247,8 +3153,7 @@ } if (null != super.getType()) { result.setAttributeNS( - null, EncryptionConstants._ATT_TYPE, - super.getType().toString()); + null, EncryptionConstants._ATT_TYPE, super.getType()); } if (null != super.getMimeType()) { result.setAttributeNS( @@ -3258,7 +3163,7 @@ if (null != super.getEncoding()) { result.setAttributeNS( null, EncryptionConstants._ATT_ENCODING, - super.getEncoding().toString()); + super.getEncoding()); } if (null != super.getEncryptionMethod()) { result.appendChild(((EncryptionMethodImpl) @@ -3383,8 +3288,7 @@ } if (null != super.getType()) { result.setAttributeNS( - null, EncryptionConstants._ATT_TYPE, - super.getType().toString()); + null, EncryptionConstants._ATT_TYPE, super.getType()); } if (null != super.getMimeType()) { result.setAttributeNS(null, @@ -3392,7 +3296,7 @@ } if (null != super.getEncoding()) { result.setAttributeNS(null, Constants._ATT_ENCODING, - super.getEncoding().toString()); + super.getEncoding()); } if (null != getRecipient()) { result.setAttributeNS(null, @@ -3468,13 +3372,17 @@ * @param type */ public void setType(String type) { - URI tmpType = null; - try { - tmpType = new URI(type); - } catch (URI.MalformedURIException mfue) { - // complain + if (type == null || type.length() == 0) { + this.type = null; + } else { + URI tmpType = null; + try { + tmpType = new URI(type); + } catch (URI.MalformedURIException mfue) { + // complain + } + this.type = tmpType.toString(); } - this.type = tmpType.toString(); } /** * @@ -3502,13 +3410,17 @@ * @param encoding */ public void setEncoding(String encoding) { - URI tmpEncoding = null; - try { - tmpEncoding = new URI(encoding); - } catch (URI.MalformedURIException mfue) { - // complain + if (encoding == null || encoding.length() == 0) { + this.encoding = null; + } else { + URI tmpEncoding = null; + try { + tmpEncoding = new URI(encoding); + } catch (URI.MalformedURIException mfue) { + // complain + } + this.encoding = tmpEncoding.toString(); } - this.encoding = tmpEncoding.toString(); } /** * @@ -3635,7 +3547,7 @@ _contextDocument, EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTIONMETHOD); result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM, - algorithm.toString()); + algorithm); if (keySize > 0) { result.appendChild( ElementProxy.createElementForFamily(_contextDocument, @@ -3735,8 +3647,7 @@ private class EncryptionPropertyImpl implements EncryptionProperty { private String target = null; private String id = null; - private String attributeName = null; - private String attributeValue = null; + private HashMap attributeMap = new HashMap(); private List encryptionInformation = null; /** @@ -3752,13 +3663,24 @@ } /** @inheritDoc */ public void setTarget(String target) { - URI tmpTarget = null; - try { - tmpTarget = new URI(target); - } catch (URI.MalformedURIException mfue) { - // complain + if (target == null || target.length() == 0) { + this.target = null; + } else if (target.startsWith("#")) { + /* + * This is a same document URI reference. Do not parse, + * because com.sun.org.apache.xml.internal.utils.URI considers this an + * illegal URI because it has no scheme. + */ + this.target = target; + } else { + URI tmpTarget = null; + try { + tmpTarget = new URI(target); + } catch (URI.MalformedURIException mfue) { + // complain + } + this.target = tmpTarget.toString(); } - this.target = tmpTarget.toString(); } /** @inheritDoc */ public String getId() { @@ -3770,12 +3692,11 @@ } /** @inheritDoc */ public String getAttribute(String attribute) { - return (attributeValue); + return (String) attributeMap.get(attribute); } /** @inheritDoc */ public void setAttribute(String attribute, String value) { - attributeName = attribute; - attributeValue = value; + attributeMap.put(attribute, value); } /** @inheritDoc */ public Iterator getEncryptionInformation() { @@ -3805,7 +3726,7 @@ EncryptionConstants._TAG_ENCRYPTIONPROPERTY); if (null != target) { result.setAttributeNS(null, EncryptionConstants._ATT_TARGET, - target.toString()); + target); } if (null != id) { result.setAttributeNS(null, EncryptionConstants._ATT_ID, @@ -3839,7 +3760,13 @@ * @param doc */ public TransformsImpl(Document doc) { - super(doc); + if (doc == null) { + throw new RuntimeException("Document is null"); + } + + this._doc = doc; + this._constructionElement = createElementForFamilyLocal(this._doc, + this.getBaseNamespace(), this.getBaseLocalName()); } /** * diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java Wed Jul 05 16:42:37 2017 +0200 @@ -108,84 +108,78 @@ return null; } - /** - * Internal method to get bytes in decryption mode + /** + * Internal method to get bytes in decryption mode * @return the decripted bytes * @throws XMLEncryptionException - */ + */ + private byte[] getDecryptBytes() throws XMLEncryptionException { - private byte[] getDecryptBytes() throws XMLEncryptionException { - - String base64EncodedEncryptedOctets = null; + String base64EncodedEncryptedOctets = null; if (_cipherData.getDataType() == CipherData.REFERENCE_TYPE) { - // Fun time! - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData"); - CipherReference cr = _cipherData.getCipherReference(); + // Fun time! + logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData"); + CipherReference cr = _cipherData.getCipherReference(); - // Need to wrap the uri in an Attribute node so that we can - // Pass to the resource resolvers + // Need to wrap the uri in an Attribute node so that we can + // Pass to the resource resolvers - Attr uriAttr = cr.getURIAsAttr(); - XMLSignatureInput input = null; + Attr uriAttr = cr.getURIAsAttr(); + XMLSignatureInput input = null; - try { - ResourceResolver resolver = - ResourceResolver.getInstance(uriAttr, null); - input = resolver.resolve(uriAttr, null); - } catch (ResourceResolverException ex) { - throw new XMLEncryptionException("empty", ex); - } + try { + ResourceResolver resolver = + ResourceResolver.getInstance(uriAttr, null); + input = resolver.resolve(uriAttr, null); + } catch (ResourceResolverException ex) { + throw new XMLEncryptionException("empty", ex); + } - if (input != null) { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\""); - } - else { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\""); - } + if (input != null) { + logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\""); + } else { + logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\""); + } - // Lets see if there are any transforms - Transforms transforms = cr.getTransforms(); - if (transforms != null) { - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Have transforms in cipher reference"); - try { - com.sun.org.apache.xml.internal.security.transforms.Transforms dsTransforms = - transforms.getDSTransforms(); - input = dsTransforms.performTransforms(input); - } catch (TransformationException ex) { - throw new XMLEncryptionException("empty", ex); - } - } + // Lets see if there are any transforms + Transforms transforms = cr.getTransforms(); + if (transforms != null) { + logger.log(java.util.logging.Level.FINE, "Have transforms in cipher reference"); + try { + com.sun.org.apache.xml.internal.security.transforms.Transforms dsTransforms = + transforms.getDSTransforms(); + input = dsTransforms.performTransforms(input); + } catch (TransformationException ex) { + throw new XMLEncryptionException("empty", ex); + } + } - try { - return input.getBytes(); - } - catch (IOException ex) { - throw new XMLEncryptionException("empty", ex); - } catch (CanonicalizationException ex) { - throw new XMLEncryptionException("empty", ex); - } + try { + return input.getBytes(); + } catch (IOException ex) { + throw new XMLEncryptionException("empty", ex); + } catch (CanonicalizationException ex) { + throw new XMLEncryptionException("empty", ex); + } - // retrieve the cipher text + // retrieve the cipher text } else if (_cipherData.getDataType() == CipherData.VALUE_TYPE) { - CipherValue cv = _cipherData.getCipherValue(); - base64EncodedEncryptedOctets = new String(cv.getValue()); + base64EncodedEncryptedOctets = + _cipherData.getCipherValue().getValue(); } else { - throw new XMLEncryptionException("CipherData.getDataType() returned unexpected value"); - } + throw new XMLEncryptionException("CipherData.getDataType() returned unexpected value"); + } - if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); + logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); byte[] encryptedBytes = null; - try { - encryptedBytes = Base64.decode(base64EncodedEncryptedOctets); + encryptedBytes = Base64.decode(base64EncodedEncryptedOctets); } catch (Base64DecodingException bde) { throw new XMLEncryptionException("empty", bde); } - return (encryptedBytes); - - } - + return (encryptedBytes); + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -28,7 +27,7 @@ /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class ContentHandlerAlreadyRegisteredException extends XMLSecurityException { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java Wed Jul 05 16:42:37 2017 +0200 @@ -25,6 +25,8 @@ import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; import java.util.List; import javax.crypto.SecretKey; @@ -88,15 +90,22 @@ * The containsXXX() methods return whether the KeyInfo * contains the corresponding type. * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class KeyInfo extends SignatureElementProxy { /** {@link java.util.logging} logging facility */ static java.util.logging.Logger log = java.util.logging.Logger.getLogger(KeyInfo.class.getName()); + List x509Datas=null; + List encryptedKeys=null; - + static final List nullList; + static { + List list = new ArrayList(); + list.add(null); + nullList = Collections.unmodifiableList(list); + } /** * Constructor KeyInfo @@ -108,7 +117,6 @@ XMLUtils.addReturnToElement(this._constructionElement); - } /** @@ -119,8 +127,8 @@ * @throws XMLSecurityException */ public KeyInfo(Element element, String BaseURI) throws XMLSecurityException { - super(element, BaseURI); + // _storageResolvers.add(null); } @@ -131,7 +139,7 @@ */ public void setId(String Id) { - if ((this._state == MODE_SIGN) && (Id != null)) { + if ((Id != null)) { this._constructionElement.setAttributeNS(null, Constants._ATT_ID, Id); IdResolver.registerElementById(this._constructionElement, Id); } @@ -162,10 +170,8 @@ */ public void add(KeyName keyname) { - if (this._state == MODE_SIGN) { this._constructionElement.appendChild(keyname.getElement()); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -219,11 +225,8 @@ * @param keyvalue */ public void add(KeyValue keyvalue) { - - if (this._state == MODE_SIGN) { this._constructionElement.appendChild(keyvalue.getElement()); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -241,11 +244,8 @@ * @param mgmtdata */ public void add(MgmtData mgmtdata) { - - if (this._state == MODE_SIGN) { this._constructionElement.appendChild(mgmtdata.getElement()); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -254,11 +254,8 @@ * @param pgpdata */ public void add(PGPData pgpdata) { - - if (this._state == MODE_SIGN) { this._constructionElement.appendChild(pgpdata.getElement()); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -279,11 +276,8 @@ * @param retrievalmethod */ public void add(RetrievalMethod retrievalmethod) { - - if (this._state == MODE_SIGN) { this._constructionElement.appendChild(retrievalmethod.getElement()); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -292,11 +286,8 @@ * @param spkidata */ public void add(SPKIData spkidata) { - - if (this._state == MODE_SIGN) { this._constructionElement.appendChild(spkidata.getElement()); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -305,11 +296,11 @@ * @param x509data */ public void add(X509Data x509data) { - - if (this._state == MODE_SIGN) { + if (x509Datas==null) + x509Datas=new ArrayList(); + x509Datas.add(x509data); this._constructionElement.appendChild(x509data.getElement()); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -321,12 +312,11 @@ public void add(EncryptedKey encryptedKey) throws XMLEncryptionException { - - if (this._state == MODE_SIGN) { + if (encryptedKeys==null) + encryptedKeys=new ArrayList(); + encryptedKeys.add(encryptedKey); XMLCipher cipher = XMLCipher.getInstance(); this._constructionElement.appendChild(cipher.martial(encryptedKey)); - } - } /** @@ -335,11 +325,8 @@ * @param element */ public void addUnknownElement(Element element) { - - if (this._state == MODE_SIGN) { this._constructionElement.appendChild(element); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -403,6 +390,9 @@ *@return the number of the X509Data tags */ public int lengthX509Data() { + if (x509Datas!=null) { + return x509Datas.size(); + } return this.length(Constants.SignatureSpecNS, Constants._TAG_X509DATA); } @@ -550,7 +540,9 @@ * @throws XMLSecurityException */ public X509Data itemX509Data(int i) throws XMLSecurityException { - + if (x509Datas!=null) { + return (X509Data) x509Datas.get(i); + } Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), Constants._TAG_X509DATA,i); @@ -569,7 +561,9 @@ */ public EncryptedKey itemEncryptedKey(int i) throws XMLSecurityException { - + if (encryptedKeys!=null) { + return (EncryptedKey) encryptedKeys.get(i); + } Element e = XMLUtils.selectXencNode(this._constructionElement.getFirstChild(), EncryptionConstants._TAG_ENCRYPTEDKEY,i); @@ -707,20 +701,20 @@ PublicKey pk = this.getPublicKeyFromInternalResolvers(); if (pk != null) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I could find a key using the per-KeyInfo key resolvers"); + log.log(java.util.logging.Level.FINE, "I could find a key using the per-KeyInfo key resolvers"); return pk; } - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I couldn't find a key using the per-KeyInfo key resolvers"); + log.log(java.util.logging.Level.FINE, "I couldn't find a key using the per-KeyInfo key resolvers"); pk = this.getPublicKeyFromStaticResolvers(); if (pk != null) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I could find a key using the system-wide key resolvers"); + log.log(java.util.logging.Level.FINE, "I could find a key using the system-wide key resolvers"); return pk; } - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I couldn't find a key using the system-wide key resolvers"); + log.log(java.util.logging.Level.FINE, "I couldn't find a key using the system-wide key resolvers"); return null; } @@ -732,46 +726,29 @@ * @throws KeyResolverException */ PublicKey getPublicKeyFromStaticResolvers() throws KeyResolverException { - - for (int i = 0; i < KeyResolver.length(); i++) { - KeyResolver keyResolver = KeyResolver.item(i); + int length=KeyResolver.length(); + int storageLength=this._storageResolvers.size(); + Iterator it= KeyResolver.iterator(); + for (int i = 0; i < length; i++) { + KeyResolverSpi keyResolver = (KeyResolverSpi) it.next(); Node currentChild=this._constructionElement.getFirstChild(); + String uri= this.getBaseURI(); while (currentChild!=null) { if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - if (this._storageResolvers.size() == 0) { - - // if we do not have storage resolvers, we verify with null - StorageResolver storage = null; - - if (keyResolver.canResolve((Element) currentChild, - this.getBaseURI(), storage)) { - PublicKey pk = - keyResolver.resolvePublicKey((Element) currentChild, - this.getBaseURI(), - storage); - - if (pk != null) { - return pk; - } - } - } else { - for (int k = 0; k < this._storageResolvers.size(); k++) { + for (int k = 0; k < storageLength; k++) { StorageResolver storage = (StorageResolver) this._storageResolvers.get(k); - if (keyResolver.canResolve((Element) currentChild, - this.getBaseURI(), storage)) { - PublicKey pk = - keyResolver.resolvePublicKey((Element) currentChild, - this.getBaseURI(), + PublicKey pk = + keyResolver.engineLookupAndResolvePublicKey((Element) currentChild, + uri, storage); - if (pk != null) { - return pk; - } + if (pk != null) { + KeyResolver.hit(it); + return pk; } } - } } currentChild=currentChild.getNextSibling(); } @@ -786,50 +763,27 @@ * @throws KeyResolverException */ PublicKey getPublicKeyFromInternalResolvers() throws KeyResolverException { - - for (int i = 0; i < this.lengthInternalKeyResolver(); i++) { + int length=lengthInternalKeyResolver(); + int storageLength=this._storageResolvers.size(); + for (int i = 0; i < length; i++) { KeyResolverSpi keyResolver = this.itemInternalKeyResolver(i); - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); Node currentChild=this._constructionElement.getFirstChild(); + String uri=this.getBaseURI(); while (currentChild!=null) { if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - if (this._storageResolvers.size() == 0) { - - // if we do not have storage resolvers, we verify with null - StorageResolver storage = null; - - if (keyResolver.engineCanResolve((Element) currentChild, - this.getBaseURI(), - storage)) { - PublicKey pk = - keyResolver - .engineResolvePublicKey((Element) currentChild, this - .getBaseURI(), storage); + for (int k = 0; k < storageLength; k++) { + StorageResolver storage = + (StorageResolver) this._storageResolvers.get(k); + PublicKey pk = keyResolver + .engineLookupAndResolvePublicKey((Element) currentChild, uri, storage); if (pk != null) { - return pk; + return pk; } } - } else { - for (int k = 0; k < this._storageResolvers.size(); k++) { - StorageResolver storage = - (StorageResolver) this._storageResolvers.get(k); - - if (keyResolver.engineCanResolve((Element) currentChild, - this.getBaseURI(), - storage)) { - PublicKey pk = keyResolver - .engineResolvePublicKey((Element) currentChild, this - .getBaseURI(), storage); - - if (pk != null) { - return pk; - } - } - } - } } currentChild=currentChild.getNextSibling(); } @@ -850,12 +804,12 @@ X509Certificate cert = this.getX509CertificateFromInternalResolvers(); if (cert != null) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, + log.log(java.util.logging.Level.FINE, "I could find a X509Certificate using the per-KeyInfo key resolvers"); return cert; } - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, + log.log(java.util.logging.Level.FINE, "I couldn't find a X509Certificate using the per-KeyInfo key resolvers"); @@ -863,12 +817,12 @@ cert = this.getX509CertificateFromStaticResolvers(); if (cert != null) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, + log.log(java.util.logging.Level.FINE, "I could find a X509Certificate using the system-wide key resolvers"); return cert; } - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, + log.log(java.util.logging.Level.FINE, "I couldn't find a X509Certificate using the system-wide key resolvers"); @@ -885,53 +839,44 @@ */ X509Certificate getX509CertificateFromStaticResolvers() throws KeyResolverException { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Start getX509CertificateFromStaticResolvers() with " + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Start getX509CertificateFromStaticResolvers() with " + KeyResolver.length() + " resolvers"); - - for (int i = 0; i < KeyResolver.length(); i++) { - KeyResolver keyResolver = KeyResolver.item(i); - Node currentChild=this._constructionElement.getFirstChild(); - while (currentChild!=null) { - if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - if (this._storageResolvers.size() == 0) { - - // if we do not have storage resolvers, we verify with null - StorageResolver storage = null; + String uri=this.getBaseURI(); + int length= KeyResolver.length(); + int storageLength=this._storageResolvers.size(); + Iterator it = KeyResolver.iterator(); + for (int i = 0; i com.sun.org.apache.xml.internal.security.keys package. * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class KeyUtils { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -28,7 +27,7 @@ /** * Empty interface just to identify Elements that can be cildren of ds:KeyInfo. * - * @author $Author: blautenb $ + * @author $Author: mullan $ */ public interface KeyInfoContent { } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,25 +20,18 @@ */ package com.sun.org.apache.xml.internal.security.keys.content; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class KeyName extends SignatureElementProxy implements KeyInfoContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(KeyName.class.getName()); - /** * Constructor KeyName * diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,11 +20,8 @@ */ package com.sun.org.apache.xml.internal.security.keys.content; - - import java.security.PublicKey; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.DSAKeyValue; import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.RSAKeyValue; @@ -34,140 +31,131 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * The KeyValue element contains a single public key that may be useful in * validating the signature. Structured formats for defining DSA (REQUIRED) * and RSA (RECOMMENDED) public keys are defined in Signature Algorithms * (section 6.4). The KeyValue element may include externally defined public - * keys values represented as PCDATA or element types from an external namespace. + * keys values represented as PCDATA or element types from an external + * namespace. * - * @author $Author: vishal $ + * @author $Author: mullan $ */ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(KeyValue.class.getName()); + /** + * Constructor KeyValue + * + * @param doc + * @param dsaKeyValue + */ + public KeyValue(Document doc, DSAKeyValue dsaKeyValue) { - /** - * Constructor KeyValue - * - * @param doc - * @param dsaKeyValue - */ - public KeyValue(Document doc, DSAKeyValue dsaKeyValue) { - - super(doc); + super(doc); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(dsaKeyValue.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + XMLUtils.addReturnToElement(this._constructionElement); + this._constructionElement.appendChild(dsaKeyValue.getElement()); + XMLUtils.addReturnToElement(this._constructionElement); + } - /** - * Constructor KeyValue - * - * @param doc - * @param rsaKeyValue - */ - public KeyValue(Document doc, RSAKeyValue rsaKeyValue) { + /** + * Constructor KeyValue + * + * @param doc + * @param rsaKeyValue + */ + public KeyValue(Document doc, RSAKeyValue rsaKeyValue) { - super(doc); + super(doc); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(rsaKeyValue.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + XMLUtils.addReturnToElement(this._constructionElement); + this._constructionElement.appendChild(rsaKeyValue.getElement()); + XMLUtils.addReturnToElement(this._constructionElement); + } - /** - * Constructor KeyValue - * - * @param doc - * @param unknownKeyValue - */ - public KeyValue(Document doc, Element unknownKeyValue) { + /** + * Constructor KeyValue + * + * @param doc + * @param unknownKeyValue + */ + public KeyValue(Document doc, Element unknownKeyValue) { - super(doc); + super(doc); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(unknownKeyValue); - XMLUtils.addReturnToElement(this._constructionElement); - } + XMLUtils.addReturnToElement(this._constructionElement); + this._constructionElement.appendChild(unknownKeyValue); + XMLUtils.addReturnToElement(this._constructionElement); + } - /** - * Constructor KeyValue - * - * @param doc - * @param pk - */ - public KeyValue(Document doc, PublicKey pk) { + /** + * Constructor KeyValue + * + * @param doc + * @param pk + */ + public KeyValue(Document doc, PublicKey pk) { - super(doc); + super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this._constructionElement); - if (pk instanceof java.security.interfaces.DSAPublicKey) { - DSAKeyValue dsa = new DSAKeyValue(this._doc, pk); + if (pk instanceof java.security.interfaces.DSAPublicKey) { + DSAKeyValue dsa = new DSAKeyValue(this._doc, pk); - this._constructionElement.appendChild(dsa.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } else if (pk instanceof java.security.interfaces.RSAPublicKey) { - RSAKeyValue rsa = new RSAKeyValue(this._doc, pk); + this._constructionElement.appendChild(dsa.getElement()); + XMLUtils.addReturnToElement(this._constructionElement); + } else if (pk instanceof java.security.interfaces.RSAPublicKey) { + RSAKeyValue rsa = new RSAKeyValue(this._doc, pk); - this._constructionElement.appendChild(rsa.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - } + this._constructionElement.appendChild(rsa.getElement()); + XMLUtils.addReturnToElement(this._constructionElement); + } + } - /** - * Constructor KeyValue - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public KeyValue(Element element, String BaseURI) + /** + * Constructor KeyValue + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public KeyValue(Element element, String BaseURI) throws XMLSecurityException { - super(element, BaseURI); - } + super(element, BaseURI); + } - /** - * Method getPublicKey - * - * @return the public key - * @throws XMLSecurityException - */ - public PublicKey getPublicKey() throws XMLSecurityException { - + /** + * Method getPublicKey + * + * @return the public key + * @throws XMLSecurityException + */ + public PublicKey getPublicKey() throws XMLSecurityException { - Element rsa = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_RSAKEYVALUE,0); + Element rsa = XMLUtils.selectDsNode + (this._constructionElement.getFirstChild(), + Constants._TAG_RSAKEYVALUE,0); - if (rsa != null) { - RSAKeyValue kv = new RSAKeyValue(rsa, - this._baseURI); - + if (rsa != null) { + RSAKeyValue kv = new RSAKeyValue(rsa, this._baseURI); return kv.getPublicKey(); - } + } - Element dsa = XMLUtils.selectDsNode(this._constructionElement, - Constants._TAG_DSAKEYVALUE,0); - + Element dsa = XMLUtils.selectDsNode + (this._constructionElement.getFirstChild(), + Constants._TAG_DSAKEYVALUE,0); - if (dsa != null) { - DSAKeyValue kv = new DSAKeyValue(dsa, - this._baseURI); - + if (dsa != null) { + DSAKeyValue kv = new DSAKeyValue(dsa, this._baseURI); return kv.getPublicKey(); - } - + } - return null; - } + return null; + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_KEYVALUE; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_KEYVALUE; + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,25 +20,18 @@ */ package com.sun.org.apache.xml.internal.security.keys.content; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class MgmtData extends SignatureElementProxy implements KeyInfoContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(MgmtData.class.getName()); - /** * Constructor MgmtData * diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,25 +20,18 @@ */ package com.sun.org.apache.xml.internal.security.keys.content; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Element; - /** * - * @author $Author: raul $ + * @author $Author: mullan $ * $todo$ Implement */ public class PGPData extends SignatureElementProxy implements KeyInfoContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(PGPData.class.getName()); - /** * Constructor PGPData * diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,9 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.keys.content; - - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; @@ -33,17 +30,13 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class RetrievalMethod extends SignatureElementProxy implements KeyInfoContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(RetrievalMethod.class.getName()); //J- /** DSA retrieval */ public static final String TYPE_DSA = Constants.SignatureSpecNS + "DSAKeyValue"; @@ -133,7 +126,7 @@ try { Element transformsElem = - XMLUtils.selectDsNode(this._constructionElement, + XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), Constants ._TAG_TRANSFORMS, 0); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,25 +20,18 @@ */ package com.sun.org.apache.xml.internal.security.keys.content; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Element; - /** * - * @author $Author: raul $ + * @author $Author: mullan $ * $todo$ implement */ public class SPKIData extends SignatureElementProxy implements KeyInfoContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(SPKIData.class.getName()); - /** * Constructor SPKIData * diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java Wed Jul 05 16:42:37 2017 +0200 @@ -41,7 +41,7 @@ /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class X509Data extends SignatureElementProxy implements KeyInfoContent { @@ -72,60 +72,17 @@ throws XMLSecurityException { super(element, BaseURI); - - boolean noElements=true; Node sibling=this._constructionElement.getFirstChild(); while (sibling!=null) { if (sibling.getNodeType()!=Node.ELEMENT_NODE) { sibling=sibling.getNextSibling(); continue; } - noElements=false; - Element currentElem = (Element) sibling; - sibling=sibling.getNextSibling(); - String localname = currentElem.getLocalName(); - - if (currentElem.getNamespaceURI().equals(Constants.SignatureSpecNS)) { - if (localname.equals(Constants._TAG_X509ISSUERSERIAL)) { - XMLX509IssuerSerial is = new XMLX509IssuerSerial(currentElem, - BaseURI); - - this.add(is); - } else if (localname.equals(Constants._TAG_X509SKI)) { - XMLX509SKI ski = new XMLX509SKI(currentElem, BaseURI); - - this.add(ski); - } else if (localname.equals(Constants._TAG_X509SUBJECTNAME)) { - XMLX509SubjectName sn = new XMLX509SubjectName(currentElem, - BaseURI); - - this.add(sn); - } else if (localname.equals(Constants._TAG_X509CERTIFICATE)) { - XMLX509Certificate cert = new XMLX509Certificate(currentElem, - BaseURI); - - this.add(cert); - } else if (localname.equals(Constants._TAG_X509CRL)) { - XMLX509CRL crl = new XMLX509CRL(currentElem, BaseURI); - - this.add(crl); - } else { - log.log(java.util.logging.Level.WARNING, "Found a " + currentElem.getTagName() + " element in " - + Constants._TAG_X509DATA); - this.addUnknownElement(currentElem); - } - } else { - log.log(java.util.logging.Level.WARNING, "Found a " + currentElem.getTagName() + " element in " - + Constants._TAG_X509DATA); - this.addUnknownElement(currentElem); - } + return; } - if (noElements) { - Object exArgs[] = { "Elements", Constants._TAG_X509DATA }; - - throw new XMLSecurityException("xml.WrongContent", exArgs); - } - + /* No Elements found */ + Object exArgs[] = { "Elements", Constants._TAG_X509DATA }; + throw new XMLSecurityException("xml.WrongContent", exArgs); } /** @@ -169,11 +126,9 @@ */ public void add(XMLX509IssuerSerial xmlX509IssuerSerial) { - if (this._state == MODE_SIGN) { this._constructionElement .appendChild(xmlX509IssuerSerial.getElement()); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -202,11 +157,8 @@ * @param xmlX509SKI */ public void add(XMLX509SKI xmlX509SKI) { - - if (this._state == MODE_SIGN) { this._constructionElement.appendChild(xmlX509SKI.getElement()); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -233,11 +185,8 @@ * @param xmlX509SubjectName */ public void add(XMLX509SubjectName xmlX509SubjectName) { - - if (this._state == MODE_SIGN) { this._constructionElement.appendChild(xmlX509SubjectName.getElement()); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -266,11 +215,8 @@ * @param xmlX509Certificate */ public void add(XMLX509Certificate xmlX509Certificate) { - - if (this._state == MODE_SIGN) { this._constructionElement.appendChild(xmlX509Certificate.getElement()); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -288,11 +234,8 @@ * @param xmlX509CRL */ public void add(XMLX509CRL xmlX509CRL) { - - if (this._state == MODE_SIGN) { this._constructionElement.appendChild(xmlX509CRL.getElement()); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -301,11 +244,8 @@ * @param element */ public void addUnknownElement(Element element) { - - if (this._state == MODE_SIGN) { this._constructionElement.appendChild(element); XMLUtils.addReturnToElement(this._constructionElement); - } } /** @@ -479,7 +419,7 @@ * TODO implement **/ public Element itemUnknownElement(int i) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "itemUnknownElement not implemented:"+i); + log.log(java.util.logging.Level.FINE, "itemUnknownElement not implemented:"+i); return null; } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,8 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.keys.content.keyvalues; - - import java.math.BigInteger; import java.security.Key; import java.security.KeyFactory; @@ -39,18 +37,13 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class DSAKeyValue extends SignatureElementProxy implements KeyValueContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(DSAKeyValue.class.getName()); - /** * Constructor DSAKeyValue * diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -32,7 +31,7 @@ * * * - * @author $Author: raul $ + * @author $Author: mullan $ * */ public interface KeyValueContent { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,8 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.keys.content.keyvalues; - - import java.math.BigInteger; import java.security.Key; import java.security.KeyFactory; @@ -39,19 +37,13 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class RSAKeyValue extends SignatureElementProxy implements KeyValueContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - RSAKeyValue.class.getName()); - /** * Constructor RSAKeyValue * diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,30 +20,20 @@ */ package com.sun.org.apache.xml.internal.security.keys.content.x509; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * - * - * - * - * @author $Author: raul $ + * @author $Author: mullan $ * */ public class XMLX509CRL extends SignatureElementProxy implements XMLX509DataContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(XMLX509CRL.class.getName()); - /** * Constructor XMLX509CRL * diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,8 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.keys.content.x509; - - import java.io.ByteArrayInputStream; import java.security.PublicKey; import java.security.cert.CertificateException; @@ -34,18 +32,13 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class XMLX509Certificate extends SignatureElementProxy implements XMLX509DataContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(XMLX509Certificate.class.getName()); - /** Field JCA_CERT_ID */ public static final String JCA_CERT_ID = "X.509"; @@ -146,23 +139,25 @@ return null; } - /** @inheritDoc */ - public boolean equals(Object obj) { - - try { - if (!obj.getClass().getName().equals(this.getClass().getName())) { - return false; - } + /** @inheritDoc */ + public boolean equals(Object obj) { - XMLX509Certificate other = (XMLX509Certificate) obj; + if (obj == null) { + return false; + } + if (!this.getClass().getName().equals(obj.getClass().getName())) { + return false; + } + XMLX509Certificate other = (XMLX509Certificate) obj; + try { - /** $todo$ or should be create X509Certificates and use the equals() from the Certs */ - return java.security.MessageDigest.isEqual(other.getCertificateBytes(), - this.getCertificateBytes()); - } catch (XMLSecurityException ex) { - return false; - } - } + /** $todo$ or should be create X509Certificates and use the equals() from the Certs */ + return java.security.MessageDigest.isEqual + (other.getCertificateBytes(), this.getCertificateBytes()); + } catch (XMLSecurityException ex) { + return false; + } + } /** @inheritDoc */ public String getBaseLocalName() { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -28,7 +27,7 @@ /** * Just used for tagging contents that are allowed inside a ds:X509Data Element. * - * @author $Author: blautenb $ + * @author $Author: mullan $ */ public interface XMLX509DataContent { } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,8 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.keys.content.x509; - - import java.math.BigInteger; import java.security.cert.X509Certificate; @@ -33,148 +31,139 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class XMLX509IssuerSerial extends SignatureElementProxy implements XMLX509DataContent { - /** {@link java.util.logging} logging facility */ + /** {@link java.util.logging} logging facility */ static java.util.logging.Logger log = java.util.logging.Logger.getLogger( XMLX509IssuerSerial.class.getName()); - /** - * Constructor XMLX509IssuerSerial - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public XMLX509IssuerSerial(Element element, String BaseURI) + /** + * Constructor XMLX509IssuerSerial + * + * @param element + * @param baseURI + * @throws XMLSecurityException + */ + public XMLX509IssuerSerial(Element element, String baseURI) throws XMLSecurityException { - super(element, BaseURI); - } + super(element, baseURI); + } - /** - * Constructor XMLX509IssuerSerial - * - * @param doc - * @param X509IssuerName - * @param X509SerialNumber - */ - public XMLX509IssuerSerial(Document doc, String X509IssuerName, - BigInteger X509SerialNumber) { + /** + * Constructor XMLX509IssuerSerial + * + * @param doc + * @param x509IssuerName + * @param x509SerialNumber + */ + public XMLX509IssuerSerial(Document doc, String x509IssuerName, + BigInteger x509SerialNumber) { - super(doc); - - XMLUtils.addReturnToElement(this._constructionElement); - this.addTextElement(X509IssuerName, Constants._TAG_X509ISSUERNAME); - XMLUtils.addReturnToElement(this._constructionElement); - this.addTextElement(X509SerialNumber.toString(), Constants._TAG_X509SERIALNUMBER); - } + super(doc); + XMLUtils.addReturnToElement(this._constructionElement); + addTextElement(x509IssuerName, Constants._TAG_X509ISSUERNAME); + addTextElement(x509SerialNumber.toString(), Constants._TAG_X509SERIALNUMBER); + } - /** - * Constructor XMLX509IssuerSerial - * - * @param doc - * @param X509IssuerName - * @param X509SerialNumber - */ - public XMLX509IssuerSerial(Document doc, String X509IssuerName, - String X509SerialNumber) { - this(doc, X509IssuerName, new BigInteger(X509SerialNumber)); - } + /** + * Constructor XMLX509IssuerSerial + * + * @param doc + * @param x509IssuerName + * @param x509SerialNumber + */ + public XMLX509IssuerSerial(Document doc, String x509IssuerName, + String x509SerialNumber) { + this(doc, x509IssuerName, new BigInteger(x509SerialNumber)); + } - /** - * Constructor XMLX509IssuerSerial - * - * @param doc - * @param X509IssuerName - * @param X509SerialNumber - */ - public XMLX509IssuerSerial(Document doc, String X509IssuerName, - int X509SerialNumber) { - this(doc, X509IssuerName, - new BigInteger(Integer.toString(X509SerialNumber))); - } + /** + * Constructor XMLX509IssuerSerial + * + * @param doc + * @param x509IssuerName + * @param x509SerialNumber + */ + public XMLX509IssuerSerial(Document doc, String x509IssuerName, + int x509SerialNumber) { + this(doc, x509IssuerName, + new BigInteger(Integer.toString(x509SerialNumber))); + } - /** - * Constructor XMLX509IssuerSerial - * - * @param doc - * @param x509certificate - */ - public XMLX509IssuerSerial(Document doc, X509Certificate x509certificate) { + /** + * Constructor XMLX509IssuerSerial + * + * @param doc + * @param x509certificate + */ + public XMLX509IssuerSerial(Document doc, X509Certificate x509certificate) { - this(doc, - RFC2253Parser.normalize(x509certificate.getIssuerDN().getName()), - x509certificate.getSerialNumber()); - } + this(doc, + RFC2253Parser.normalize(x509certificate.getIssuerDN().getName()), + x509certificate.getSerialNumber()); + } - /** - * Method getSerialNumber - * - * - * @return the serial number - */ - public BigInteger getSerialNumber() { + /** + * Method getSerialNumber + * + * @return the serial number + */ + public BigInteger getSerialNumber() { - String text = - this.getTextFromChildElement(Constants._TAG_X509SERIALNUMBER, - Constants.SignatureSpecNS); - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "In dem X509SerialNumber wurde gefunden: " + text); + String text = this.getTextFromChildElement + (Constants._TAG_X509SERIALNUMBER, Constants.SignatureSpecNS); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "X509SerialNumber text: " + text); - return new BigInteger(text); - } + return new BigInteger(text); + } - /** - * Method getSerialNumberInteger - * - * - * @return the serial number as plain int - */ - public int getSerialNumberInteger() { - return this.getSerialNumber().intValue(); - } + /** + * Method getSerialNumberInteger + * + * @return the serial number as plain int + */ + public int getSerialNumberInteger() { + return this.getSerialNumber().intValue(); + } - /** - * Method getIssuerName - * - * - * @return the issuer name - */ - public String getIssuerName() { + /** + * Method getIssuerName + * + * @return the issuer name + */ + public String getIssuerName() { - return RFC2253Parser - .normalize(this - .getTextFromChildElement(Constants._TAG_X509ISSUERNAME, - Constants.SignatureSpecNS)); - } + return RFC2253Parser + .normalize(this + .getTextFromChildElement(Constants._TAG_X509ISSUERNAME, + Constants.SignatureSpecNS)); + } - /** @inheritDoc */ - public boolean equals(Object obj) { + /** @inheritDoc */ + public boolean equals(Object obj) { - if (!obj.getClass().getName().equals(this.getClass().getName())) { - return false; - } + if (obj == null) { + return false; + } + if (!this.getClass().getName().equals(obj.getClass().getName())) { + return false; + } - XMLX509IssuerSerial other = (XMLX509IssuerSerial) obj; - + XMLX509IssuerSerial other = (XMLX509IssuerSerial) obj; - if (other.getSerialNumber().equals(this.getSerialNumber()) - && other.getIssuerName().equals(this.getIssuerName())) { - return true; - } + return this.getSerialNumber().equals(other.getSerialNumber()) + && this.getIssuerName().equals(other.getIssuerName()); + } - return false; - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509ISSUERSERIAL; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509ISSUERSERIAL; + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,8 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.keys.content.x509; - - import java.io.IOException; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -36,192 +34,143 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; -import sun.security.util.DerValue; - - /** * Handles SubjectKeyIdentifier (SKI) for X.509v3. * - * @author $Author: raul $ - * @see Interface X509Extension + * @author $Author: mullan $ + * @see Interface X509Extension */ public class XMLX509SKI extends SignatureElementProxy implements XMLX509DataContent { - /** {@link java.util.logging} logging facility */ + /** {@link java.util.logging} logging facility */ static java.util.logging.Logger log = java.util.logging.Logger.getLogger(XMLX509SKI.class.getName()); - /** - * SubjectKeyIdentifier (id-ce-subjectKeyIdentifier) (2.5.29.14): - * This extension identifies the public key being certified. It enables - * distinct keys used by the same subject to be differentiated - * (e.g., as key updating occurs). - *
- * A key identifer shall be unique with respect to all key identifiers - * for the subject with which it is used. This extension is always non-critical. - */ - public static final String SKI_OID = "2.5.29.14"; - - /** - * Constructor X509SKI - * - * @param doc - * @param skiBytes - */ - public XMLX509SKI(Document doc, byte[] skiBytes) { + /** + * SubjectKeyIdentifier (id-ce-subjectKeyIdentifier) (2.5.29.14): + * This extension identifies the public key being certified. It enables + * distinct keys used by the same subject to be differentiated + * (e.g., as key updating occurs). + *
+ * A key identifer shall be unique with respect to all key identifiers + * for the subject with which it is used. This extension is always non-critical. + */ + public static final String SKI_OID = "2.5.29.14"; - super(doc); - - this.addBase64Text(skiBytes); - } + /** + * Constructor X509SKI + * + * @param doc + * @param skiBytes + */ + public XMLX509SKI(Document doc, byte[] skiBytes) { + super(doc); + this.addBase64Text(skiBytes); + } - /** - * Constructor XMLX509SKI - * - * @param doc - * @param x509certificate - * @throws XMLSecurityException - */ - public XMLX509SKI(Document doc, X509Certificate x509certificate) + /** + * Constructor XMLX509SKI + * + * @param doc + * @param x509certificate + * @throws XMLSecurityException + */ + public XMLX509SKI(Document doc, X509Certificate x509certificate) throws XMLSecurityException { - - super(doc); - - this.addBase64Text(XMLX509SKI.getSKIBytesFromCert(x509certificate)); - } + super(doc); + this.addBase64Text(XMLX509SKI.getSKIBytesFromCert(x509certificate)); + } - /** - * Constructor XMLX509SKI - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public XMLX509SKI(Element element, String BaseURI) + /** + * Constructor XMLX509SKI + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public XMLX509SKI(Element element, String BaseURI) throws XMLSecurityException { - super(element, BaseURI); - } - - /** - * Method getSKIBytes - * - * @return the skibytes - * @throws XMLSecurityException - */ - public byte[] getSKIBytes() throws XMLSecurityException { - return this.getBytesFromTextChild(); - } + super(element, BaseURI); + } - /** - * Method getSKIBytesFromCert - * - * @param cert - * @return sky bytes from the given certificate - * - * @throws XMLSecurityException - * @see java.security.cert.X509Extension#getExtensionValue(java.lang.String) - */ - public static byte[] getSKIBytesFromCert(X509Certificate cert) - throws XMLSecurityException { + /** + * Method getSKIBytes + * + * @return the skibytes + * @throws XMLSecurityException + */ + public byte[] getSKIBytes() throws XMLSecurityException { + return this.getBytesFromTextChild(); + } - try { + /** + * Method getSKIBytesFromCert + * + * @param cert + * @return ski bytes from the given certificate + * + * @throws XMLSecurityException + * @see java.security.cert.X509Extension#getExtensionValue(java.lang.String) + */ + public static byte[] getSKIBytesFromCert(X509Certificate cert) + throws XMLSecurityException { - /* - * Gets the DER-encoded OCTET string for the extension value (extnValue) - * identified by the passed-in oid String. The oid string is - * represented by a set of positive whole numbers separated by periods. - */ - byte[] derEncodedValue = cert.getExtensionValue(XMLX509SKI.SKI_OID); - - if (cert.getVersion() < 3) { + if (cert.getVersion() < 3) { Object exArgs[] = { new Integer(cert.getVersion()) }; - throw new XMLSecurityException("certificate.noSki.lowVersion", exArgs); - } + } - byte[] extensionValue = null; + /* + * Gets the DER-encoded OCTET string for the extension value + * (extnValue) identified by the passed-in oid String. The oid + * string is represented by a set of positive whole numbers + * separated by periods. + */ + byte[] extensionValue = cert.getExtensionValue(XMLX509SKI.SKI_OID); + if (extensionValue == null) { + throw new XMLSecurityException("certificate.noSki.null"); + } - /** - * Use sun.security.util.DerValue if it is present. - */ - try { - DerValue dervalue = new DerValue(derEncodedValue); - if (dervalue == null) { - throw new XMLSecurityException("certificate.noSki.null"); - } - if (dervalue.tag != DerValue.tag_OctetString) { - throw new XMLSecurityException("certificate.noSki.notOctetString"); - } - extensionValue = dervalue.getOctetString(); - } catch (NoClassDefFoundError e) { - } + /** + * Strip away first four bytes from the extensionValue + * The first two bytes are the tag and length of the extensionValue + * OCTET STRING, and the next two bytes are the tag and length of + * the skid OCTET STRING. + */ + byte skidValue[] = new byte[extensionValue.length - 4]; + + System.arraycopy(extensionValue, 4, skidValue, 0, skidValue.length); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Base64 of SKI is " + Base64.encode(skidValue)); + } - /** - * Fall back to org.bouncycastle.asn1.DERInputStream - */ - if (extensionValue == null) { - try { - Class clazz = Class.forName("org.bouncycastle.asn1.DERInputStream"); - if (clazz != null) { - Constructor constructor = clazz.getConstructor(new Class[]{InputStream.class}); - InputStream is = (InputStream) constructor.newInstance(new Object[]{new ByteArrayInputStream(derEncodedValue)}); - Method method = clazz.getMethod("readObject", new Class[]{}); - Object obj = method.invoke(is, new Object[]{}); - if (obj == null) { - throw new XMLSecurityException("certificate.noSki.null"); - } - Class clazz2 = Class.forName("org.bouncycastle.asn1.ASN1OctetString"); - if (!clazz2.isInstance(obj)) { - throw new XMLSecurityException("certificate.noSki.notOctetString"); - } - Method method2 = clazz2.getMethod("getOctets", new Class[]{}); - extensionValue = (byte[]) method2.invoke(obj, new Object[]{}); - } - } catch (Throwable t) { - } - } + return skidValue; + } - /** - * Strip away first two bytes from the DerValue (tag and length) - */ - byte abyte0[] = new byte[extensionValue.length - 2]; + /** @inheritDoc */ + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!this.getClass().getName().equals(obj.getClass().getName())) { + return false; + } - System.arraycopy(extensionValue, 2, abyte0, 0, abyte0.length); + XMLX509SKI other = (XMLX509SKI) obj; - /* - byte abyte0[] = new byte[derEncodedValue.length - 4]; - System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length); - */ - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Base64 of SKI is " + Base64.encode(abyte0)); - - return abyte0; - } catch (IOException ex) { - throw new XMLSecurityException("generic.EmptyMessage", ex); - } - } - - /** @inheritDoc */ - public boolean equals(Object obj) { + try { + return java.security.MessageDigest.isEqual(other.getSKIBytes(), + this.getSKIBytes()); + } catch (XMLSecurityException ex) { + return false; + } + } - if (!obj.getClass().getName().equals(this.getClass().getName())) { - return false; - } - - XMLX509SKI other = (XMLX509SKI) obj; - - try { - return java.security.MessageDigest.isEqual(other.getSKIBytes(), - this.getSKIBytes()); - } catch (XMLSecurityException ex) { - return false; - } - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509SKI; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509SKI; + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,8 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.keys.content.x509; - - import java.security.cert.X509Certificate; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; @@ -33,15 +31,11 @@ /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class XMLX509SubjectName extends SignatureElementProxy implements XMLX509DataContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(XMLX509SubjectName.class.getName()); - /** * Constructor X509SubjectName * @@ -88,23 +82,21 @@ return RFC2253Parser.normalize(this.getTextFromTextChild()); } - /** @inheritDoc */ - public boolean equals(Object obj) { - - if (!obj.getClass().getName().equals(this.getClass().getName())) { - return false; - } + /** @inheritDoc */ + public boolean equals(Object obj) { + if (obj == null) { + return false; + } - XMLX509SubjectName other = (XMLX509SubjectName) obj; - String otherSubject = other.getSubjectName(); - String thisSubject = this.getSubjectName(); + if (!this.getClass().getName().equals(obj.getClass().getName())) { + return false; + } - if (otherSubject.equals(thisSubject)) { - return true; - } + XMLX509SubjectName other = (XMLX509SubjectName) obj; + String otherSubject = other.getSubjectName(); + String thisSubject = this.getSubjectName(); - return false; - + return thisSubject.equals(otherSubject); } /** @inheritDoc */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -29,7 +28,7 @@ /** * * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class InvalidKeyResolverException extends XMLSecurityException { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -26,6 +25,7 @@ import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import javax.crypto.SecretKey; @@ -39,7 +39,8 @@ * KeyResolver is factory class for subclass of KeyResolverSpi that * represent child element of KeyInfo. * - * @author $Author: raul $ + * @author $Author: mullan $ + * @version %I%, %G% */ public class KeyResolver { @@ -72,6 +73,7 @@ InstantiationException { this._resolverSpi = (KeyResolverSpi) Class.forName(className).newInstance(); + this._resolverSpi.setGlobalResolver(true); } /** @@ -83,21 +85,17 @@ return KeyResolver._resolverVector.size(); } - /** - * Method item - * - * @param i - * @return the number i resolver registerd - * @throws KeyResolverException - */ - public static KeyResolver item(int i) throws KeyResolverException { - - KeyResolver resolver = (KeyResolver) KeyResolver._resolverVector.get(i); - if (resolver==null) { - throw new KeyResolverException("utils.resolver.noClass"); - } - - return resolver; + public static void hit(Iterator hintI) { + ResolverIterator hint = (ResolverIterator) hintI; + int i = hint.i; + if (i!=1 && hint.res ==_resolverVector) { + List resolverVector=(List)((ArrayList)_resolverVector).clone(); + Object ob=resolverVector.remove(i-1); + resolverVector.add(0,ob); + _resolverVector=resolverVector; + } else { + //System.out.println("KeyResolver hitting"); + } } /** @@ -106,17 +104,19 @@ * @param element * @param BaseURI * @param storage - * @return the instance that happends to implement the thing. + * @return The certificate represented by the element. * * @throws KeyResolverException */ - public static final KeyResolver getInstance( + public static final X509Certificate getX509Certificate( Element element, String BaseURI, StorageResolver storage) throws KeyResolverException { - for (int i = 0; i < KeyResolver._resolverVector.size(); i++) { + // use the old vector to not be hit by updates + List resolverVector = KeyResolver._resolverVector; + for (int i = 0; i < resolverVector.size(); i++) { KeyResolver resolver= - (KeyResolver) KeyResolver._resolverVector.get(i); + (KeyResolver) resolverVector.get(i); if (resolver==null) { Object exArgs[] = { @@ -127,11 +127,63 @@ throw new KeyResolverException("utils.resolver.noClass", exArgs); } - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver.getClass()); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver.getClass()); + + X509Certificate cert=resolver.resolveX509Certificate(element, BaseURI, storage); + if (cert!=null) { + return cert; + } + } + + Object exArgs[] = { + (((element != null) && (element.getNodeType() == Node.ELEMENT_NODE)) + ? element.getTagName() + : "null") }; - if (resolver.canResolve(element, BaseURI, storage)) { - return resolver; + throw new KeyResolverException("utils.resolver.noClass", exArgs); + } + /** + * Method getInstance + * + * @param element + * @param BaseURI + * @param storage + * @return the public key contained in the element + * + * @throws KeyResolverException + */ + public static final PublicKey getPublicKey( + Element element, String BaseURI, StorageResolver storage) + throws KeyResolverException { + + List resolverVector = KeyResolver._resolverVector; + for (int i = 0; i < resolverVector.size(); i++) { + KeyResolver resolver= + (KeyResolver) resolverVector.get(i); + + if (resolver==null) { + Object exArgs[] = { + (((element != null) + && (element.getNodeType() == Node.ELEMENT_NODE)) + ? element.getTagName() + : "null") }; + + throw new KeyResolverException("utils.resolver.noClass", exArgs); + } + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver.getClass()); + + PublicKey cert=resolver.resolvePublicKey(element, BaseURI, storage); + if (cert!=null) { + if (i!=0 && resolverVector==_resolverVector) { + //update resolver. + resolverVector=(List)((ArrayList)_resolverVector).clone(); + Object ob=resolverVector.remove(i); + resolverVector.add(0,ob); + _resolverVector=resolverVector; + } + return cert; } } @@ -182,34 +234,6 @@ KeyResolver._resolverVector.add(0, className); } - /* - * Method resolve - * - * @param element - * - * @throws KeyResolverException - */ - - /** - * Method resolveStatic - * - * @param element - * @param BaseURI - * @param storage - * @return resolve from the static register an element - * - * @throws KeyResolverException - */ - public static PublicKey resolveStatic( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - - KeyResolver myResolver = KeyResolver.getInstance(element, BaseURI, - storage); - - return myResolver.resolvePublicKey(element, BaseURI, storage); - } - /** * Method resolve * @@ -223,7 +247,7 @@ public PublicKey resolvePublicKey( Element element, String BaseURI, StorageResolver storage) throws KeyResolverException { - return this._resolverSpi.engineResolvePublicKey(element, BaseURI, storage); + return this._resolverSpi.engineLookupAndResolvePublicKey(element, BaseURI, storage); } /** @@ -239,7 +263,7 @@ public X509Certificate resolveX509Certificate( Element element, String BaseURI, StorageResolver storage) throws KeyResolverException { - return this._resolverSpi.engineResolveX509Certificate(element, BaseURI, + return this._resolverSpi.engineLookupResolveX509Certificate(element, BaseURI, storage); } @@ -253,7 +277,7 @@ public SecretKey resolveSecretKey( Element element, String BaseURI, StorageResolver storage) throws KeyResolverException { - return this._resolverSpi.engineResolveSecretKey(element, BaseURI, + return this._resolverSpi.engineLookupAndResolveSecretKey(element, BaseURI, storage); } @@ -277,14 +301,6 @@ return this._resolverSpi.engineGetProperty(key); } - /** - * Method getPropertyKeys - * - * @return the properties key registerd in this resolver - */ - public String[] getPropertyKeys() { - return this._resolverSpi.engineGetPropertyKeys(); - } /** * Method understandsProperty @@ -296,18 +312,6 @@ return this._resolverSpi.understandsProperty(propertyToTest); } - /** - * Method canResolve - * - * @param element - * @param BaseURI - * @param storage - * @return true if can resolve the key in the element - */ - public boolean canResolve(Element element, String BaseURI, - StorageResolver storage) { - return this._resolverSpi.engineCanResolve(element, BaseURI, storage); - } /** * Method resolverClassName @@ -317,4 +321,37 @@ public String resolverClassName() { return this._resolverSpi.getClass().getName(); } + + static class ResolverIterator implements Iterator { + List res; + Iterator it; + int i; + public ResolverIterator(List list) { + res = list; + it = res.iterator(); + } + public boolean hasNext() { + // TODO Auto-generated method stub + return it.hasNext(); + } + + public Object next() { + i++; + KeyResolver resolver = (KeyResolver) it.next(); + if (resolver==null) { + throw new RuntimeException("utils.resolver.noClass"); + } + + return resolver._resolverSpi; + } + + public void remove() { + // TODO Auto-generated method stub + + } + + }; + public static Iterator iterator() { + return new ResolverIterator(_resolverVector); + } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -31,7 +30,7 @@ * * * - * @author $Author: raul $ + * @author $Author: mullan $ * */ public class KeyResolverException extends XMLSecurityException { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java Wed Jul 05 16:42:37 2017 +0200 @@ -20,17 +20,15 @@ */ package com.sun.org.apache.xml.internal.security.keys.keyresolver; - - import java.security.PublicKey; import java.security.cert.X509Certificate; +import java.util.HashMap; import javax.crypto.SecretKey; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; import org.w3c.dom.Element; - /** * This class is abstract class for a child KeyInfo Elemnet. * @@ -41,14 +39,10 @@ * JAVACLASS="MyPackage.MyKeyValueImpl"//gt; * * - * @author $Author: raul $ + * @author $Author: mullan $ + * @version $Revision: 1.5 $ */ public abstract class KeyResolverSpi { - - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(KeyResolverSpi.class.getName()); - /** * This method helps the {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver} to decide whether a * {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi} is able to perform the requested action. @@ -56,10 +50,28 @@ * @param element * @param BaseURI * @param storage - * @return true if can resolve the key in the element + * @return */ - abstract public boolean engineCanResolve(Element element, String BaseURI, - StorageResolver storage); + public boolean engineCanResolve(Element element, String BaseURI, + StorageResolver storage) { + throw new UnsupportedOperationException(); + } + + /** + * Method engineResolvePublicKey + * + * @param element + * @param BaseURI + * @param storage + * @return resolved public key from the registered from the element. + * + * @throws KeyResolverException + */ + public PublicKey engineResolvePublicKey( + Element element, String BaseURI, StorageResolver storage) + throws KeyResolverException { + throw new UnsupportedOperationException(); + }; /** * Method engineResolvePublicKey @@ -71,9 +83,44 @@ * * @throws KeyResolverException */ - abstract public PublicKey engineResolvePublicKey( + public PublicKey engineLookupAndResolvePublicKey( Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException; + throws KeyResolverException { + KeyResolverSpi tmp = cloneIfNeeded(); + if (!tmp.engineCanResolve(element, BaseURI, storage)) + return null; + return tmp.engineResolvePublicKey(element, BaseURI, storage); + } + + private KeyResolverSpi cloneIfNeeded() throws KeyResolverException { + KeyResolverSpi tmp=this; + if (globalResolver) { + try { + tmp = (KeyResolverSpi) getClass().newInstance(); + } catch (InstantiationException e) { + throw new KeyResolverException("",e); + } catch (IllegalAccessException e) { + throw new KeyResolverException("",e); + } + } + return tmp; + } + + /** + * Method engineResolveCertificate + * + * @param element + * @param BaseURI + * @param storage + * @return resolved X509Certificate key from the registered from the elements + * + * @throws KeyResolverException + */ + public X509Certificate engineResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage) + throws KeyResolverException{ + throw new UnsupportedOperationException(); + }; /** * Method engineResolveCertificate @@ -85,9 +132,30 @@ * * @throws KeyResolverException */ - abstract public X509Certificate engineResolveX509Certificate( + public X509Certificate engineLookupResolveX509Certificate( Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException; + throws KeyResolverException { + KeyResolverSpi tmp = cloneIfNeeded(); + if (!tmp.engineCanResolve(element, BaseURI, storage)) + return null; + return tmp.engineResolveX509Certificate(element, BaseURI, storage); + + } + /** + * Method engineResolveSecretKey + * + * @param element + * @param BaseURI + * @param storage + * @return resolved SecretKey key from the registered from the elements + * + * @throws KeyResolverException + */ + public SecretKey engineResolveSecretKey( + Element element, String BaseURI, StorageResolver storage) + throws KeyResolverException{ + throw new UnsupportedOperationException(); + }; /** * Method engineResolveSecretKey @@ -99,12 +167,19 @@ * * @throws KeyResolverException */ - abstract public SecretKey engineResolveSecretKey( + public SecretKey engineLookupAndResolveSecretKey( Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException; + throws KeyResolverException { + KeyResolverSpi tmp = cloneIfNeeded(); + if (!tmp.engineCanResolve(element, BaseURI, storage)) + return null; + return tmp.engineResolveSecretKey(element, BaseURI, storage); + } /** Field _properties */ - protected java.util.Map _properties = new java.util.HashMap(10); + protected java.util.Map _properties = null; + + protected boolean globalResolver=false; /** * Method engineSetProperty @@ -113,19 +188,8 @@ * @param value */ public void engineSetProperty(String key, String value) { - - java.util.Iterator i = this._properties.keySet().iterator(); - - while (i.hasNext()) { - String c = (String) i.next(); - - if (c.equals(key)) { - key = c; - - break; - } - } - + if (_properties==null) + _properties=new HashMap(); this._properties.put(key, value); } @@ -136,49 +200,26 @@ * @return obtain the property appointed by key */ public String engineGetProperty(String key) { - - java.util.Iterator i = this._properties.keySet().iterator(); - - while (i.hasNext()) { - String c = (String) i.next(); - - if (c.equals(key)) { - key = c; - - break; - } - } + if (_properties==null) + return null; return (String) this._properties.get(key); } /** - * Method engineGetPropertyKeys - * - * @return the keys of properties known by this resolver - */ - public String[] engineGetPropertyKeys() { - return new String[0]; - } - - /** * Method understandsProperty * * @param propertyToTest * @return true if understood the property */ public boolean understandsProperty(String propertyToTest) { - - String[] understood = this.engineGetPropertyKeys(); + if (_properties==null) + return false; - if (understood != null) { - for (int i = 0; i < understood.length; i++) { - if (understood[i].equals(propertyToTest)) { - return true; - } - } - } + return this._properties.get(propertyToTest)!=null; + } + public void setGlobalResolver(boolean globalResolver) { + this.globalResolver = globalResolver; + } - return false; - } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java Wed Jul 05 16:42:37 2017 +0200 @@ -37,46 +37,10 @@ /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class DSAKeyValueResolver extends KeyResolverSpi { - /** Field _dsaKeyElement */ - private Element _dsaKeyElement = null; - - /** @inheritDoc */ - public boolean engineCanResolve(Element element, String BaseURI, - StorageResolver storage) { - - if (element == null) { - return false; - } - - boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_KEYVALUE); - boolean isDSAKeyValue = XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_DSAKEYVALUE); - - if (isKeyValue) { - - this._dsaKeyElement = - XMLUtils.selectDsNode(element.getFirstChild(),Constants._TAG_DSAKEYVALUE,0); - - if (this._dsaKeyElement != null) { - return true; - } - } else if (isDSAKeyValue) { - - // this trick is needed to allow the RetrievalMethodResolver to eat a - // ds:DSAKeyValue directly (without KeyValue) - this._dsaKeyElement = element; - - return true; - } - - return false; - } - /** * Method engineResolvePublicKey * @@ -85,20 +49,30 @@ * @param storage * @return null if no {@link PublicKey} could be obtained */ - public PublicKey engineResolvePublicKey( + public PublicKey engineLookupAndResolvePublicKey( Element element, String BaseURI, StorageResolver storage) { + if (element == null) { + return null; + } + Element dsaKeyElement=null; + boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, + Constants._TAG_KEYVALUE); + if (isKeyValue) { + dsaKeyElement = + XMLUtils.selectDsNode(element.getFirstChild(),Constants._TAG_DSAKEYVALUE,0); + } else if (XMLUtils.elementIsInSignatureSpace(element, + Constants._TAG_DSAKEYVALUE)) { + // this trick is needed to allow the RetrievalMethodResolver to eat a + // ds:DSAKeyValue directly (without KeyValue) + dsaKeyElement = element; + } - if (this._dsaKeyElement == null) { - boolean weCanResolve = this.engineCanResolve(element, BaseURI, - storage); - - if (!weCanResolve || (this._dsaKeyElement == null)) { - return null; - } + if (dsaKeyElement == null) { + return null; } try { - DSAKeyValue dsaKeyValue = new DSAKeyValue(this._dsaKeyElement, + DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, BaseURI); PublicKey pk = dsaKeyValue.getPublicKey(); @@ -112,13 +86,13 @@ /** @inheritDoc */ - public X509Certificate engineResolveX509Certificate( + public X509Certificate engineLookupResolveX509Certificate( Element element, String BaseURI, StorageResolver storage) { return null; } /** @inheritDoc */ - public javax.crypto.SecretKey engineResolveSecretKey( + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( Element element, String BaseURI, StorageResolver storage){ return null; } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java Wed Jul 05 16:42:37 2017 +0200 @@ -56,7 +56,6 @@ RSAKeyValueResolver.class.getName()); - Key _key; Key _kek; String _algorithm; @@ -66,7 +65,6 @@ * @param algorithm */ public EncryptedKeyResolver(String algorithm) { - _key = null; _kek = null; _algorithm=algorithm; } @@ -78,64 +76,49 @@ */ public EncryptedKeyResolver(String algorithm, Key kek) { - _key = null; _algorithm = algorithm; _kek = kek; } - /** - * Method engineCanResolve - * - * @param element - * @param BaseURI - * @param storage - * @return true if can resolve the key in the element - * - */ - - public boolean engineCanResolve(Element element, String BaseURI, - StorageResolver storage) { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName()); - - if (element == null) { - return false; - } - - boolean isEncryptedKey = XMLUtils.elementIsInEncryptionSpace(element, - EncryptionConstants._TAG_ENCRYPTEDKEY); - - if (isEncryptedKey) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Passed an Encrypted Key"); - try { - XMLCipher cipher = XMLCipher.getInstance(); - cipher.init(XMLCipher.UNWRAP_MODE, _kek); - EncryptedKey ek = cipher.loadEncryptedKey(element); - _key = cipher.decryptKey(ek, _algorithm); - } - catch (Exception e) {} - } - - return (_key != null); - } - /** @inheritDoc */ - public PublicKey engineResolvePublicKey( + public PublicKey engineLookupAndResolvePublicKey( Element element, String BaseURI, StorageResolver storage) { return null; } /** @inheritDoc */ - public X509Certificate engineResolveX509Certificate( + public X509Certificate engineLookupResolveX509Certificate( Element element, String BaseURI, StorageResolver storage) { return null; } /** @inheritDoc */ - public javax.crypto.SecretKey engineResolveSecretKey( + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( Element element, String BaseURI, StorageResolver storage) { - return (SecretKey) _key; + SecretKey key=null; + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName()); + + if (element == null) { + return null; + } + + boolean isEncryptedKey = XMLUtils.elementIsInEncryptionSpace(element, + EncryptionConstants._TAG_ENCRYPTEDKEY); + + if (isEncryptedKey) { + log.log(java.util.logging.Level.FINE, "Passed an Encrypted Key"); + try { + XMLCipher cipher = XMLCipher.getInstance(); + cipher.init(XMLCipher.UNWRAP_MODE, _kek); + EncryptedKey ek = cipher.loadEncryptedKey(element); + key = (SecretKey) cipher.decryptKey(ek, _algorithm); + } + catch (Exception e) {} + } + + return key; } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -38,7 +37,7 @@ /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class RSAKeyValueResolver extends KeyResolverSpi { @@ -48,75 +47,55 @@ RSAKeyValueResolver.class.getName()); /** Field _rsaKeyElement */ - private Element _rsaKeyElement = null; + /** @inheritDoc */ - public boolean engineCanResolve(Element element, String BaseURI, - StorageResolver storage) { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); - + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage) { + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); if (element == null) { - return false; + return null; } - boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_KEYVALUE); - boolean isRSAKeyValue = XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_RSAKEYVALUE); - - if (isKeyValue) { - this._rsaKeyElement = XMLUtils.selectDsNode(element.getFirstChild(), - Constants._TAG_RSAKEYVALUE, 0); - - if (this._rsaKeyElement != null) { - return true; - } - } else if (isRSAKeyValue) { - + boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, + Constants._TAG_KEYVALUE); + Element rsaKeyElement=null; + if (isKeyValue) { + rsaKeyElement = XMLUtils.selectDsNode(element.getFirstChild(), + Constants._TAG_RSAKEYVALUE, 0); + } else if (XMLUtils.elementIsInSignatureSpace(element, + Constants._TAG_RSAKEYVALUE)) { // this trick is needed to allow the RetrievalMethodResolver to eat a // ds:RSAKeyValue directly (without KeyValue) - this._rsaKeyElement = element; - - return true; - } - - return false; - } + rsaKeyElement = element; + } - /** @inheritDoc */ - public PublicKey engineResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) { - if (this._rsaKeyElement == null) { - boolean weCanResolve = this.engineCanResolve(element, BaseURI, - storage); - - if (!weCanResolve || (this._rsaKeyElement == null)) { - return null; - } + if (rsaKeyElement == null) { + return null; } try { - RSAKeyValue rsaKeyValue = new RSAKeyValue(this._rsaKeyElement, + RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, BaseURI); return rsaKeyValue.getPublicKey(); } catch (XMLSecurityException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); } return null; } /** @inheritDoc */ - public X509Certificate engineResolveX509Certificate( + public X509Certificate engineLookupResolveX509Certificate( Element element, String BaseURI, StorageResolver storage) { return null; } /** @inheritDoc */ - public javax.crypto.SecretKey engineResolveSecretKey( + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( Element element, String BaseURI, StorageResolver storage) { return null; } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java Wed Jul 05 16:42:37 2017 +0200 @@ -28,7 +28,15 @@ import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; +import javax.xml.parsers.ParserConfigurationException; + +import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.RetrievalMethod; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate; @@ -44,6 +52,7 @@ import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.Node; +import org.xml.sax.SAXException; /** @@ -55,7 +64,7 @@ * RetrievalMethodResolver cannot handle itself, resolving of the extracted * element is delegated back to the KeyResolver mechanism. * - * @author $Author: raul $ + * @author $Author: mullan $ modified by Dave Garcia */ public class RetrievalMethodResolver extends KeyResolverSpi { @@ -65,26 +74,6 @@ RetrievalMethodResolver.class.getName()); /** - * Method engineCanResolve - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public boolean engineCanResolve(Element element, String BaseURI, - StorageResolver storage) { - - if - (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_RETRIEVALMETHOD)) { - return false; - } - - return true; - } - - /** * Method engineResolvePublicKey * @inheritDoc * @param element @@ -92,82 +81,59 @@ * @param storage * */ - public PublicKey engineResolvePublicKey( + public PublicKey engineLookupAndResolvePublicKey( Element element, String BaseURI, StorageResolver storage) { + if (!XMLUtils.elementIsInSignatureSpace(element, + Constants._TAG_RETRIEVALMETHOD)) { + return null; + } try { - RetrievalMethod rm = new RetrievalMethod(element, BaseURI); - Attr uri = rm.getURIAttr(); - - // type can be null because it's optional - String type = rm.getType(); - Transforms transforms = rm.getTransforms(); - ResourceResolver resRes = ResourceResolver.getInstance(uri, BaseURI); - - if (resRes != null) { - XMLSignatureInput resource = resRes.resolve(uri, BaseURI); - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Before applying Transforms, resource has " - + resource.getBytes().length + "bytes"); - - if (transforms != null) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "We have Transforms"); - - resource = transforms.performTransforms(resource); - } - if (true) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "After applying Transforms, resource has " - + resource.getBytes().length + "bytes"); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Resolved to resource " + resource.getSourceURI()); - } - - byte inputBytes[] = resource.getBytes(); - - if ((type != null) && type.equals(RetrievalMethod.TYPE_RAWX509)) { + //Create a retrieval method over the given element + RetrievalMethod rm = new RetrievalMethod(element, BaseURI); + String type = rm.getType(); + XMLSignatureInput resource=resolveInput(rm,BaseURI); + if (RetrievalMethod.TYPE_RAWX509.equals(type)) { + //a raw certificate, direct parsing is done! + X509Certificate cert=getRawCertificate(resource); + if (cert != null) { + return cert.getPublicKey(); + } + return null; + }; + Element e = obtainRefrenceElement(resource); + return resolveKey(e,BaseURI,storage); + } catch (XMLSecurityException ex) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } catch (CertificateException ex) { + log.log(java.util.logging.Level.FINE, "CertificateException", ex); + } catch (IOException ex) { + log.log(java.util.logging.Level.FINE, "IOException", ex); + } catch (ParserConfigurationException e) { + log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); + } catch (SAXException e) { + log.log(java.util.logging.Level.FINE, "SAXException", e); + } + return null; + } - // if the resource stores a raw certificate, we have to handle it - CertificateFactory certFact = - CertificateFactory - .getInstance(XMLX509Certificate.JCA_CERT_ID); - X509Certificate cert = - (X509Certificate) certFact - .generateCertificate(new ByteArrayInputStream(inputBytes)); - - if (cert != null) { - return cert.getPublicKey(); - } - } else { - - // otherwise, we parse the resource, create an Element and delegate - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes"); - - Element e = this.getDocFromBytes(inputBytes); - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}" - + e.getLocalName() + " Element"); - - if (e != null) { - KeyResolver newKeyResolver = KeyResolver.getInstance(getFirstElementChild(e), - BaseURI, storage); - - if (newKeyResolver != null) { - return newKeyResolver.resolvePublicKey(getFirstElementChild(e), BaseURI, - storage); - } - } - } - } - } catch (XMLSecurityException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } catch (CertificateException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "CertificateException", ex); - } catch (IOException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "IOException", ex); - } - - return null; + static private Element obtainRefrenceElement(XMLSignatureInput resource) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException, KeyResolverException { + Element e; + if (resource.isElement()){ + e=(Element) resource.getSubNode(); + } else if (resource.isNodeSet()) { + //Retrieved resource is a nodeSet + e=getDocumentElement(resource.getNodeSet()); + } else { + //Retrieved resource is an inputStream + byte inputBytes[] = resource.getBytes(); + e = getDocFromBytes(inputBytes); + //otherwise, we parse the resource, create an Element and delegate + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes"); + } + return e; } /** @@ -178,85 +144,100 @@ * @param storage * */ - public X509Certificate engineResolveX509Certificate( + public X509Certificate engineLookupResolveX509Certificate( Element element, String BaseURI, StorageResolver storage) { - - try { - RetrievalMethod rm = new RetrievalMethod(element, BaseURI); - Attr uri = rm.getURIAttr(); - Transforms transforms = rm.getTransforms(); - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Asked to resolve URI " + uri); - - ResourceResolver resRes = ResourceResolver.getInstance(uri, BaseURI); - - if (resRes != null) { - XMLSignatureInput resource = resRes.resolve(uri, BaseURI); - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Before applying Transforms, resource has " - + resource.getBytes().length + "bytes"); + if (!XMLUtils.elementIsInSignatureSpace(element, + Constants._TAG_RETRIEVALMETHOD)) { + return null; + } - if (transforms != null) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "We have Transforms"); - - resource = transforms.performTransforms(resource); - } - - if (true) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "After applying Transforms, resource has " - + resource.getBytes().length + "bytes"); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Resolved to resource " + resource.getSourceURI()); - } - - byte inputBytes[] = resource.getBytes(); - - if ((rm.getType() != null) - && rm.getType().equals(RetrievalMethod.TYPE_RAWX509)) { + try { + RetrievalMethod rm = new RetrievalMethod(element, BaseURI); + String type = rm.getType(); + XMLSignatureInput resource=resolveInput(rm,BaseURI); + if (RetrievalMethod.TYPE_RAWX509.equals(type)) { + X509Certificate cert=getRawCertificate(resource); + return cert; + } + Element e = obtainRefrenceElement(resource); + return resolveCertificate(e,BaseURI,storage); + } catch (XMLSecurityException ex) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } catch (CertificateException ex) { + log.log(java.util.logging.Level.FINE, "CertificateException", ex); + } catch (IOException ex) { + log.log(java.util.logging.Level.FINE, "IOException", ex); + } catch (ParserConfigurationException e) { + log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); + } catch (SAXException e) { + log.log(java.util.logging.Level.FINE, "SAXException", e); + } + return null; + } - // if the resource stores a raw certificate, we have to handle it - CertificateFactory certFact = - CertificateFactory - .getInstance(XMLX509Certificate.JCA_CERT_ID); - X509Certificate cert = - (X509Certificate) certFact - .generateCertificate(new ByteArrayInputStream(inputBytes)); - - if (cert != null) { - return cert; - } - } else { - - // otherwise, we parse the resource, create an Element and delegate - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes"); - - Element e = this.getDocFromBytes(inputBytes); + /** + * Retrieves a x509Certificate from the given information + * @param e + * @param BaseURI + * @param storage + * @return + * @throws KeyResolverException + */ + static private X509Certificate resolveCertificate(Element e,String BaseURI,StorageResolver storage) throws KeyResolverException{ + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"+ e.getLocalName() + " Element"); + //An element has been provided + if (e != null) { + return KeyResolver.getX509Certificate(e,BaseURI, storage); + } + return null; + } - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}" - + e.getLocalName() + " Element"); - - if (e != null) { - KeyResolver newKeyResolver = KeyResolver.getInstance(getFirstElementChild(e), - BaseURI, storage); - - if (newKeyResolver != null) { - return newKeyResolver.resolveX509Certificate(getFirstElementChild(e), BaseURI, - storage); + /** + * Retrieves a x509Certificate from the given information + * @param e + * @param BaseURI + * @param storage + * @return + * @throws KeyResolverException + */ + static private PublicKey resolveKey(Element e,String BaseURI,StorageResolver storage) throws KeyResolverException{ + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"+ e.getLocalName() + " Element"); + //An element has been provided + if (e != null) { + return KeyResolver.getPublicKey(e,BaseURI, storage); } - } - } - } - } catch (XMLSecurityException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } catch (CertificateException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "CertificateException", ex); - } catch (IOException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "IOException", ex); - } + return null; + } - return null; + static private X509Certificate getRawCertificate(XMLSignatureInput resource) throws CanonicalizationException, IOException, CertificateException{ + byte inputBytes[] = resource.getBytes(); + // if the resource stores a raw certificate, we have to handle it + CertificateFactory certFact =CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); + X509Certificate cert =(X509Certificate) certFact.generateCertificate(new ByteArrayInputStream(inputBytes)); + return cert; + } + /** + * Resolves the input from the given retrieval method + * @return + * @throws XMLSecurityException + */ + static private XMLSignatureInput resolveInput(RetrievalMethod rm,String BaseURI) throws XMLSecurityException{ + Attr uri = rm.getURIAttr(); + //Apply the trnasforms + Transforms transforms = rm.getTransforms(); + ResourceResolver resRes = ResourceResolver.getInstance(uri, BaseURI); + if (resRes != null) { + XMLSignatureInput resource = resRes.resolve(uri, BaseURI); + if (transforms != null) { + log.log(java.util.logging.Level.FINE, "We have Transforms"); + resource = transforms.performTransforms(resource); + } + return resource; + } + return null; } /** @@ -266,18 +247,13 @@ * @return the Document Element after parsing bytes * @throws KeyResolverException if something goes wrong */ - Element getDocFromBytes(byte[] bytes) throws KeyResolverException { - + static Element getDocFromBytes(byte[] bytes) throws KeyResolverException { try { - javax.xml.parsers.DocumentBuilderFactory dbf = - javax.xml.parsers.DocumentBuilderFactory.newInstance(); - + javax.xml.parsers.DocumentBuilderFactory dbf =javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); - javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse(new java.io.ByteArrayInputStream(bytes)); - return doc.getDocumentElement(); } catch (org.xml.sax.SAXException ex) { throw new KeyResolverException("empty", ex); @@ -296,16 +272,43 @@ * @param storage * */ - public javax.crypto.SecretKey engineResolveSecretKey( + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( Element element, String BaseURI, StorageResolver storage) { return null; } - static Element getFirstElementChild(Element e){ - Node n=e.getFirstChild(); - while (n!=null && n.getNodeType()!=Node.ELEMENT_NODE) { - n=n.getNextSibling(); - } - return (Element)n; + + static Element getDocumentElement(Set set) { + Iterator it=set.iterator(); + Element e=null; + while (it.hasNext()) { + Node currentNode=(Node)it.next(); + if (currentNode instanceof Element) { + e=(Element)currentNode; + break; + } + + } + List parents=new ArrayList(10); + + //Obtain all the parents of the elemnt + do { + parents.add(e); + Node n=e.getParentNode(); + if (!(n instanceof Element )) { + break; + } + e=(Element)n; + } while (e!=null); + //Visit them in reverse order. + ListIterator it2=parents.listIterator(parents.size()-1); + Element ele=null; + while (it2.hasPrevious()) { + ele=(Element)it2.previous(); + if (set.contains(ele)) { + return ele; + } + } + return null; } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -41,7 +40,7 @@ * Resolves Certificates which are directly contained inside a * ds:X509Certificate Element. * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class X509CertificateResolver extends KeyResolverSpi { @@ -49,47 +48,7 @@ static java.util.logging.Logger log = java.util.logging.Logger.getLogger(X509CertificateResolver.class.getName()); - /** Field _dsaKeyElement */ - Element[] _x509CertKeyElements = null; - /** - * Method engineCanResolve - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public boolean engineCanResolve(Element element, String BaseURI, - StorageResolver storage) { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_X509DATA)) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I can't"); - - return false; - } - - - this._x509CertKeyElements = XMLUtils.selectDsNodes(element.getFirstChild(), - Constants._TAG_X509CERTIFICATE); - - if ((this._x509CertKeyElements != null) - && (this._x509CertKeyElements.length > 0)) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Yes Sir, I can"); - - return true; - } - - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I can't"); - - return false; - } - - /** Field _x509certObject[] */ - XMLX509Certificate _x509certObject[] = null; /** * Method engineResolvePublicKey @@ -100,11 +59,11 @@ * * @throws KeyResolverException */ - public PublicKey engineResolvePublicKey( + public PublicKey engineLookupAndResolvePublicKey( Element element, String BaseURI, StorageResolver storage) throws KeyResolverException { - X509Certificate cert = this.engineResolveX509Certificate(element, + X509Certificate cert = this.engineLookupResolveX509Certificate(element, BaseURI, storage); if (cert != null) { @@ -123,43 +82,33 @@ * * @throws KeyResolverException */ - public X509Certificate engineResolveX509Certificate( + public X509Certificate engineLookupResolveX509Certificate( Element element, String BaseURI, StorageResolver storage) throws KeyResolverException { try { - if ((this._x509CertKeyElements == null) - || (this._x509CertKeyElements.length == 0)) { - boolean weCanResolve = this.engineCanResolve(element, BaseURI, - storage); - - if (!weCanResolve || (this._x509CertKeyElements == null) - || (this._x509CertKeyElements.length == 0)) { - return null; - } + Element[] els=XMLUtils.selectDsNodes(element.getFirstChild(), + Constants._TAG_X509CERTIFICATE); + if ((els == null) || (els.length == 0)) { + Element el=XMLUtils.selectDsNode(element.getFirstChild(), + Constants._TAG_X509DATA,0); + if (el!=null) { + return engineLookupResolveX509Certificate(el, BaseURI, storage); + } + return null; } - this._x509certObject = - new XMLX509Certificate[this._x509CertKeyElements.length]; - // populate Object array - for (int i = 0; i < this._x509CertKeyElements.length; i++) { - this._x509certObject[i] = - new XMLX509Certificate(this._x509CertKeyElements[i] - , BaseURI); - } - - for (int i = 0; i < this._x509certObject.length; i++) { - X509Certificate cert = this._x509certObject[i].getX509Certificate(); - - if (cert != null) { - return cert; + for (int i = 0; i < els.length; i++) { + XMLX509Certificate xmlCert=new XMLX509Certificate(els[i], BaseURI); + X509Certificate cert = xmlCert.getX509Certificate(); + if (cert!=null) { + return cert; } } - return null; } catch (XMLSecurityException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); throw new KeyResolverException("generic.EmptyMessage", ex); } @@ -173,7 +122,7 @@ * @param storage * */ - public javax.crypto.SecretKey engineResolveSecretKey( + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( Element element, String BaseURI, StorageResolver storage) { return null; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -39,7 +38,7 @@ /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class X509IssuerSerialResolver extends KeyResolverSpi { @@ -48,44 +47,13 @@ java.util.logging.Logger.getLogger( X509IssuerSerialResolver.class.getName()); - /** @inheritDoc */ - public boolean engineCanResolve(Element element, String BaseURI, - StorageResolver storage) { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - - X509Data x509data = null; - try { - x509data = new X509Data(element, BaseURI); - } catch (XMLSignatureException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I can't"); - - return false; - } catch (XMLSecurityException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I can't"); - - return false; - } - - if (x509data == null) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I can't"); - return false; - } - - if (x509data.containsIssuerSerial()) { - return true; - } - - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I can't"); - return false; - } /** @inheritDoc */ - public PublicKey engineResolvePublicKey( + public PublicKey engineLookupAndResolvePublicKey( Element element, String BaseURI, StorageResolver storage) throws KeyResolverException { - X509Certificate cert = this.engineResolveX509Certificate(element, + X509Certificate cert = this.engineLookupResolveX509Certificate(element, BaseURI, storage); if (cert != null) { @@ -96,10 +64,31 @@ } /** @inheritDoc */ - public X509Certificate engineResolveX509Certificate( + public X509Certificate engineLookupResolveX509Certificate( Element element, String BaseURI, StorageResolver storage) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + X509Data x509data = null; + try { + x509data = new X509Data(element, BaseURI); + } catch (XMLSignatureException ex) { + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } catch (XMLSecurityException ex) { + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + if (x509data == null) { + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + if (!x509data.containsIssuerSerial()) { + return null; + } try { if (storage == null) { Object exArgs[] = { Constants._TAG_X509ISSUERSERIAL }; @@ -107,53 +96,52 @@ new KeyResolverException("KeyResolver.needStorageResolver", exArgs); - if (log.isLoggable(java.util.logging.Level.INFO)) log.log(java.util.logging.Level.INFO, "", ex); + log.log(java.util.logging.Level.INFO, "", ex); throw ex; } - X509Data x509data = new X509Data(element, BaseURI); int noOfISS = x509data.lengthIssuerSerial(); while (storage.hasNext()) { X509Certificate cert = storage.next(); XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert); - if (true) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: " + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: " + certSerial.getIssuerName()); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Found Certificate Serial: " + log.log(java.util.logging.Level.FINE, "Found Certificate Serial: " + certSerial.getSerialNumber().toString()); } for (int i=0; i 0)) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Yes Sir, I can"); - - return true; - } - - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I can't"); - - return false; - } /** * Method engineResolvePublicKey @@ -102,11 +57,11 @@ * @return null if no {@link PublicKey} could be obtained * @throws KeyResolverException */ - public PublicKey engineResolvePublicKey( + public PublicKey engineLookupAndResolvePublicKey( Element element, String BaseURI, StorageResolver storage) throws KeyResolverException { - X509Certificate cert = this.engineResolveX509Certificate(element, + X509Certificate cert = this.engineLookupResolveX509Certificate(element, BaseURI, storage); if (cert != null) { @@ -125,46 +80,55 @@ * * @throws KeyResolverException */ - public X509Certificate engineResolveX509Certificate( + public X509Certificate engineLookupResolveX509Certificate( Element element, String BaseURI, StorageResolver storage) throws KeyResolverException { - - try { - if (this._x509childNodes == null) { - boolean weCanResolve = this.engineCanResolve(element, BaseURI, - storage); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + if (!XMLUtils.elementIsInSignatureSpace(element, + Constants._TAG_X509DATA)) { + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + /** Field _x509childObject[] */ + XMLX509SKI x509childObject[] = null; - if (!weCanResolve || (this._x509childNodes == null)) { - return null; - } - } + Element x509childNodes[] = null; + x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), + Constants._TAG_X509SKI); + if (!((x509childNodes != null) + && (x509childNodes.length > 0))) { + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + try { if (storage == null) { Object exArgs[] = { Constants._TAG_X509SKI }; KeyResolverException ex = new KeyResolverException("KeyResolver.needStorageResolver", exArgs); - if (log.isLoggable(java.util.logging.Level.INFO)) log.log(java.util.logging.Level.INFO, "", ex); + log.log(java.util.logging.Level.INFO, "", ex); throw ex; } - this._x509childObject = - new XMLX509SKI[this._x509childNodes.length]; + x509childObject = new XMLX509SKI[x509childNodes.length]; - for (int i = 0; i < this._x509childNodes.length; i++) { - this._x509childObject[i] = - new XMLX509SKI(this._x509childNodes[i], BaseURI); + for (int i = 0; i < x509childNodes.length; i++) { + x509childObject[i] = + new XMLX509SKI(x509childNodes[i], BaseURI); } while (storage.hasNext()) { X509Certificate cert = storage.next(); XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert); - for (int i = 0; i < this._x509childObject.length; i++) { - if (certSKI.equals(this._x509childObject[i])) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Return PublicKey from " + for (int i = 0; i < x509childObject.length; i++) { + if (certSKI.equals(x509childObject[i])) { + log.log(java.util.logging.Level.FINE, "Return PublicKey from " + cert.getSubjectDN().getName()); return cert; @@ -186,7 +150,7 @@ * @param storage * */ - public javax.crypto.SecretKey engineResolveSecretKey( + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( Element element, String BaseURI, StorageResolver storage) { return null; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java Wed Jul 05 16:42:37 2017 +0200 @@ -38,7 +38,7 @@ /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class X509SubjectNameResolver extends KeyResolverSpi { @@ -47,50 +47,6 @@ java.util.logging.Logger.getLogger( X509SubjectNameResolver.class.getName()); - /** Field _x509childNodes */ - private Element[] _x509childNodes = null; - - /** Field _x509childObject[] */ - private XMLX509SubjectName _x509childObject[] = null; - - /** - * Method engineCanResolve - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public boolean engineCanResolve(Element element, String BaseURI, - StorageResolver storage) { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - - - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_X509DATA) ) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I can't"); - - return false; - } - - - - this._x509childNodes = XMLUtils.selectDsNodes(element, - Constants._TAG_X509SUBJECTNAME); - - if ((this._x509childNodes != null) - && (this._x509childNodes.length > 0)) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Yes Sir, I can"); - - return true; - } - - - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "I can't"); - - return false; - } /** * Method engineResolvePublicKey @@ -101,11 +57,11 @@ * @return null if no {@link PublicKey} could be obtained * @throws KeyResolverException */ - public PublicKey engineResolvePublicKey( + public PublicKey engineLookupAndResolvePublicKey( Element element, String BaseURI, StorageResolver storage) throws KeyResolverException { - X509Certificate cert = this.engineResolveX509Certificate(element, + X509Certificate cert = this.engineLookupResolveX509Certificate(element, BaseURI, storage); if (cert != null) { @@ -124,37 +80,46 @@ * * @throws KeyResolverException */ - public X509Certificate engineResolveX509Certificate( + public X509Certificate engineLookupResolveX509Certificate( Element element, String BaseURI, StorageResolver storage) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + Element[] x509childNodes = null; + XMLX509SubjectName x509childObject[] = null; + + if (!XMLUtils.elementIsInSignatureSpace(element, + Constants._TAG_X509DATA) ) { + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), + Constants._TAG_X509SUBJECTNAME); + + if (!((x509childNodes != null) + && (x509childNodes.length > 0))) { + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } try { - if (this._x509childNodes == null) { - boolean weCanResolve = this.engineCanResolve(element, BaseURI, - storage); - - if (!weCanResolve || (this._x509childNodes == null)) { - return null; - } - } - if (storage == null) { Object exArgs[] = { Constants._TAG_X509SUBJECTNAME }; KeyResolverException ex = new KeyResolverException("KeyResolver.needStorageResolver", exArgs); - if (log.isLoggable(java.util.logging.Level.INFO)) log.log(java.util.logging.Level.INFO, "", ex); + log.log(java.util.logging.Level.INFO, "", ex); throw ex; } - this._x509childObject = - new XMLX509SubjectName[this._x509childNodes.length]; + x509childObject = + new XMLX509SubjectName[x509childNodes.length]; - for (int i = 0; i < this._x509childNodes.length; i++) { - this._x509childObject[i] = - new XMLX509SubjectName(this._x509childNodes[i], + for (int i = 0; i < x509childNodes.length; i++) { + x509childObject[i] = + new XMLX509SubjectName(x509childNodes[i], BaseURI); } @@ -163,24 +128,24 @@ XMLX509SubjectName certSN = new XMLX509SubjectName(element.getOwnerDocument(), cert); - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName()); + log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName()); - for (int i = 0; i < this._x509childObject.length; i++) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Found Element SN: " - + this._x509childObject[i].getSubjectName()); + for (int i = 0; i < x509childObject.length; i++) { + log.log(java.util.logging.Level.FINE, "Found Element SN: " + + x509childObject[i].getSubjectName()); - if (certSN.equals(this._x509childObject[i])) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "match !!! "); + if (certSN.equals(x509childObject[i])) { + log.log(java.util.logging.Level.FINE, "match !!! "); return cert; } - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "no match..."); + log.log(java.util.logging.Level.FINE, "no match..."); } } return null; } catch (XMLSecurityException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); throw new KeyResolverException("generic.EmptyMessage", ex); } @@ -194,7 +159,7 @@ * @param storage * */ - public javax.crypto.SecretKey engineResolveSecretKey( + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( Element element, String BaseURI, StorageResolver storage) { return null; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -21,8 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.keys.storage; - - import java.security.KeyStore; import java.security.cert.X509Certificate; import java.util.ArrayList; @@ -36,7 +33,7 @@ /** * This class collects customized resolvers for Certificates. * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class StorageResolver { @@ -45,7 +42,7 @@ java.util.logging.Logger.getLogger(StorageResolver.class.getName()); /** Field _storageResolvers */ - List _storageResolvers = new ArrayList(); + List _storageResolvers = null; /** Field _iterator */ Iterator _iterator = null; @@ -71,7 +68,8 @@ * @param resolver */ public void add(StorageResolverSpi resolver) { - + if (_storageResolvers==null) + _storageResolvers=new ArrayList(); this._storageResolvers.add(resolver); this._iterator = null; @@ -126,6 +124,8 @@ public Iterator getIterator() { if (this._iterator == null) { + if (_storageResolvers==null) + _storageResolvers=new ArrayList(); this._iterator = new StorageResolverIterator(this._storageResolvers.iterator()); } @@ -140,6 +140,8 @@ public boolean hasNext() { if (this._iterator == null) { + if (_storageResolvers==null) + _storageResolvers=new ArrayList(); this._iterator = new StorageResolverIterator(this._storageResolvers.iterator()); } @@ -158,15 +160,13 @@ /** * Class StorageResolverIterator * - * @author $Author: raul $ + * @author $Author: mullan $ + * @version $Revision: 1.5 $ */ - class StorageResolverIterator implements Iterator { + static class StorageResolverIterator implements Iterator { /** Field _resolvers */ - Iterator _resolvers = null; - - /** Field _currentResolver */ - int _currentResolver = 0; + Iterator _resolvers = null; /** * Constructor FilesystemIterator @@ -179,17 +179,16 @@ /** @inheritDoc */ public boolean hasNext() { - return _resolvers.hasNext(); + return _resolvers.hasNext(); } /** @inheritDoc */ public Object next() { - return _resolvers.next(); + return _resolvers.next(); } /** * Method remove - * */ public void remove() { throw new UnsupportedOperationException( diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -28,7 +27,7 @@ /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class StorageResolverException extends XMLSecurityException { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -28,7 +27,7 @@ /** * - * @author $Author: raul $ + * @author $Author: mullan $ */ public abstract class StorageResolverSpi { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -21,8 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.keys.storage.implementations; - - import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -40,12 +37,11 @@ import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi; import com.sun.org.apache.xml.internal.security.utils.Base64; - /** * This {@link StorageResolverSpi} makes all raw (binary) {@link X509Certificate}s * which reside as files in a single directory available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class CertsInFilesystemDirectoryResolver extends StorageResolverSpi { @@ -131,20 +127,20 @@ dn = cert.getSubjectDN().getName(); added = true; } catch (FileNotFoundException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); } catch (IOException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); } catch (CertificateNotYetValidException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); } catch (CertificateExpiredException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); } catch (CertificateException ex) { - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); } if (added) { - if (true) - if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Added certificate: " + dn); + if (log.isLoggable(java.util.logging.Level.FINE)) + log.log(java.util.logging.Level.FINE, "Added certificate: " + dn); } } } @@ -157,9 +153,10 @@ /** * Class FilesystemIterator * - * @author $Author: raul $ + * @author $Author: mullan $ + * @version $Revision: 1.5 $ */ - class FilesystemIterator implements Iterator { + private static class FilesystemIterator implements Iterator { /** Field _certs */ List _certs = null; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -21,8 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.keys.storage.implementations; - - import java.security.KeyStore; import java.security.KeyStoreException; import java.security.cert.X509Certificate; @@ -37,7 +34,7 @@ * Makes the Certificates from a JAVA {@link KeyStore} object available to the * {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class KeyStoreResolver extends StorageResolverSpi { @@ -66,9 +63,10 @@ /** * Class KeyStoreIterator * - * @author $Author: raul $ + * @author $Author: mullan $ + * @version $Revision: 1.5 $ */ - class KeyStoreIterator implements Iterator { + static class KeyStoreIterator implements Iterator { /** Field _keyStore */ KeyStore _keyStore = null; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java Wed Jul 05 16:42:37 2017 +0200 @@ -2,7 +2,6 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ - /* * Copyright 1999-2004 The Apache Software Foundation. * @@ -21,8 +20,6 @@ */ package com.sun.org.apache.xml.internal.security.keys.storage.implementations; - - import java.security.cert.X509Certificate; import java.util.Iterator; @@ -33,7 +30,7 @@ * This {@link StorageResolverSpi} makes a single {@link X509Certificate} * available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. * - * @author $Author: raul $ + * @author $Author: mullan $ */ public class SingleCertificateResolver extends StorageResolverSpi { @@ -61,9 +58,10 @@ /** * Class InternalIterator * - * @author $Author: raul $ + * @author $Author: mullan $ + * @version $Revision: 1.5 $ */ - class InternalIterator implements Iterator { + static class InternalIterator implements Iterator { /** Field _alreadyReturned */ boolean _alreadyReturned = false; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.dtd --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.dtd Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.dtd Wed Jul 05 16:42:37 2017 +0200 @@ -1,73 +1,73 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml Wed Jul 05 16:42:37 2017 +0200 @@ -1,380 +1,399 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/etsi.xsd --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/etsi.xsd Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/etsi.xsd Wed Jul 05 16:42:37 2017 +0200 @@ -1,347 +1,347 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.dtd --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.dtd Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.dtd Wed Jul 05 16:42:37 2017 +0200 @@ -3,7 +3,7 @@ Joseph Reagle $last changed 20001215$ http://www.w3.org/2000/09/xmldsig# - $Revision: 1.1 $ on $Date: 2002/02/08 20:32:26 $ by $Author: reagle $ + $Revision: 1.6 $ on $Date: 2008/07/24 16:15:03 $ by $Author: mullan $ Copyright 2001 The Internet Society and W3C (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.xsd --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.xsd Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.xsd Wed Jul 05 16:42:37 2017 +0200 @@ -11,7 +11,7 @@ + + + + +This package contains classes that allow the creation +and manipulation of service tags. +This com.sun.servicetag package is intended for +Sun internal use only. +

+

+
Service Tag
+
A service tag is an XML-based data structure that contains identifying +information about an instance of a product or component on a system. +
+
+
+
Service Tag Registry
+
A service tag registry is a XML-based registry that contains +the service tags of all the tagged components on a system. The +service tag registry is present on systems that have the +Service Tags software installed. +
+
+
+
Registration Data
+
A registration data is a container of one or more +service tags that identify the +components for product registration and will be used to interface +with the Sun Connection registration services. +
+
+ +This package contains the methods to create service tags, set up the +registration data for product registration, add service tags to and +remove them from the system service tag registry. +

+All methods defined in this package will throw {@code NullPointerException} +if {@code null} is passed in any input parameter unless it is stated otherwise. +In addition, they are multi-thread safe. + + + + diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/servicetag/resources/Putback-Notes.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/servicetag/resources/Putback-Notes.txt Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,25 @@ +README for auto-generating of the offline registration page. + +1. register.html is defined by the xDesign team. + +2. Before putback in the workspace, we need to modify the + register.html to contain the following: + + (a) replace the pathname of the jdk_header.png image to + + + (b) replace the product name from: + Java Development Kit Version 6 Update 5 (e.g.) + to: + Java Development Kit @@JDK_VERSION@@ + + (c) replace the form action for the "Register My JDK" button with: + +

+ + (d) Add this input in the form for posting data after + the line: + + + +3. The jdk_header.png is located under /lib/servicetag directory. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/servicetag/resources/javase_5_swordfish.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/servicetag/resources/javase_5_swordfish.properties Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,29 @@ +# Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Sun designates this +# particular file as subject to the "Classpath" exception as provided +# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. + +servicetag.jdk.urn = urn:uuid:d5bed446-05f2-42ed-ba0a-153105a52413 +servicetag.jdk.name = J2SE 5.0 Development Kit +servicetag.jre.urn = urn:uuid:5c6686aa-fd05-46a6-ba3e-700e2d5f7043 +servicetag.jre.name = J2SE 5.0 Runtime Environment +servicetag.parent.urn = urn:uuid:f3c20172-557a-11d7-93d0-d6a41ea318df +servicetag.parent.name = Java 2 Platform, Standard Edition 5.0 diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/servicetag/resources/javase_6_swordfish.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/servicetag/resources/javase_6_swordfish.properties Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,29 @@ +# Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Sun designates this +# particular file as subject to the "Classpath" exception as provided +# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. + +servicetag.jdk.urn = urn:uuid:b58ef9a8-5ae8-11db-a023-080020a9ed93 +servicetag.jdk.name = Java SE 6 Development Kit +servicetag.jre.urn = urn:uuid:92d1de8c-1e59-42c6-a280-1c379526bcbc +servicetag.jre.name = Java SE 6 Runtime Environment +servicetag.parent.urn = urn:uuid:fdc90b21-018d-4cab-b866-612c7c119ed3 +servicetag.parent.name = Java Platform Standard Edition 6 (Java SE 6) diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/servicetag/resources/javase_7_swordfish.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/servicetag/resources/javase_7_swordfish.properties Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,29 @@ +# Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Sun designates this +# particular file as subject to the "Classpath" exception as provided +# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. + +servicetag.jdk.urn = JSEZ9-007-ZZZZ +servicetag.jdk.name = Java SE 7 Development Kit +servicetag.jre.urn = JSERE-007-ZZZZ +servicetag.jre.name = Java SE 7 Runtime Environment +servicetag.parent.urn = urn:uuid:dc1704fe-264f-11dc-9482-080020a9ed93 +servicetag.parent.name = Java Platform Standard Edition 7 (Java SE 7) diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/servicetag/resources/jdk_header.png Binary file jdk/src/share/classes/com/sun/servicetag/resources/jdk_header.png has changed diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/servicetag/resources/product_registration.xsd --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/servicetag/resources/product_registration.xsd Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,301 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/servicetag/resources/register.html --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/servicetag/resources/register.html Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,105 @@ + + + + +Register your JDK + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  +
 

Thank you for installing the + Java Development Kit @@JDK_VERSION@@ + from Sun Microsystems.

+

Registering your product will give you the following benefits:

+
    +
  • Notification of new versions, patches, and updates
  • +
  • Special offers on Sun developer products, services and training
  • +
  • Access to early releases and documentation
  • +
+

Product registration is FREE, quick and easy!

+
+

All you need is a Sun Developer Network or other Sun Online account. If you don't already have one, you will be prompted to create one.

+ + + + + +
+ + + + You need to be connected to the Internet to register this Sun product.
+
+
  +

Sun Microsystems, Inc. respects your privacy. + We will use your personal information for communications + and management of your Sun Online Account, the services + and applications you access using your Sun Online Account, + and the products and systems you register with your Sun Online Account.

+

For more information on the data that will be collected as + part of the registration process and how it will be managed
+ see http://java.sun.com/javase/registration/JDKRegistrationPrivacy.html.
+
+ For more information on Sun's Privacy Policy see http://www.sun.com/privacy/ or contact privacy@sun.com.

  
  
+ + diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/servicetag/resources/register_ja.html --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/servicetag/resources/register_ja.html Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,91 @@ + + + + +JDK 製品登録 + + + + + + + + + + + + + + + + + + + + + + + + + + +
 
 

Sun Microsystems の Java Development Kit @@JDK_VERSION@@ をインストールしていただき、ありがとうございます。

+

製品登録をすると、次のような特典を受けることができます。

+
    +
  • 最新のバージョン、パッチ、および更新についての通知
  • +
  • Sun の開発者向け製品、サービス、およびトレーニングの特別販売
  • +
  • アーリーリリースおよびドキュメントへのアクセス
  • +
+

製品登録は無料であり、迅速で簡単です。

+
+

必要になるのは、Sun 開発者向けネットワークアカウントまたはその他の Sun オンラインアカウントだけです。 まだアカウントがない場合は、アカウントの作成が求められます。

+ + + + + +
+ + +
この Sun 製品を登録するには、インターネットに接続している必要があります。
+
+
  +

Sun Microsystems, Inc. は、お客様のプライバシーを尊重します。 お客様の個人情報は、お客様の Sun オンラインアカウント、お客様が Sun オンラインアカウントを使用してアクセスするサービスとアプリケーション、およびお客様が Sun オンラインアカウントで登録する製品とシステムの通信と管理に使用します。

+

登録の際に収集されるデータや、それらがどのように管理されるかについての詳細は、
http://java.sun.com/javase/ja/registration/JDKRegistrationPrivacy.html を参照してください。

Sun のプライバシーポリシーについての詳細は、http://jp.sun.com/privacy/ を参照するか、お問い合わせフォームからお問い合わせください。

  
  
+ + diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/servicetag/resources/register_zh_CN.html --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/com/sun/servicetag/resources/register_zh_CN.html Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,92 @@ + + + + +注册您的 JDK + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 
 

感谢您安装 Sun Microsystems 的 Java Development Kit @@JDK_VERSION@@

+

注册产品后您将获得如下增值服务:

+
    +
  • 获得新版本、修补程序和更新的通知服务
  • +
  • 获得有关 Sun 开发者产品、服务和培训的优惠
  • +
  • 获得对早期版本和文档的访问权限
  • +
+

产品注册是免费的,即快速又轻松!

+
+

您需要具有 Sun 开发者网络或其他 Sun 联机帐户。如果您没有,系统将提示您创建一个。

+ + + + + +
+ + +
您需要连接到 Internet 来注册此 Sun 产品。
+
+
  +

Sun Microsystems, Inc. 尊重您的隐私。我们会将您的个人信息用于通信和 Sun 联机帐户的管理、Sun 联机帐户访问的服务和应用程序以及用于使用 Sun 联机帐户注册的产品和系统。

+

有关注册过程中收集的数据以及这些数据的管理方式的更多信息,
请访问 http://java.sun.com/javase/registration/JDKRegistrationPrivacy.html

有关 Sun 隐私政策的更多信息,请访问 http://www.sun.com/privacy/ 或与 privacy@sun.com 联系。

  
  
+ + diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic.properties --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic.properties Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic.properties Wed Jul 05 16:42:37 2017 +0200 @@ -101,30 +101,41 @@ ColorChooser.sampleText=Sample Text Sample Text ColorChooser.swatchesNameText=Swatches ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Recent: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Red ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=Green ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=Blue ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_de.properties --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_de.properties Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_de.properties Wed Jul 05 16:42:37 2017 +0200 @@ -101,30 +101,41 @@ ColorChooser.sampleText=Beispieltext Beispieltext ColorChooser.swatchesNameText=Muster ColorChooser.swatchesMnemonic=77 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Aktuell: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Rot ColorChooser.rgbRedMnemonic=82 ColorChooser.rgbGreenText=Gr\u00fcn ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=Blau ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_es.properties --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_es.properties Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_es.properties Wed Jul 05 16:42:37 2017 +0200 @@ -101,30 +101,41 @@ ColorChooser.sampleText=Texto de ejemplo Texto de ejemplo ColorChooser.swatchesNameText=Muestras ColorChooser.swatchesMnemonic=77 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Reciente: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=V -ColorChooser.hsbBlueText=A +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Rojo ColorChooser.rgbRedMnemonic=74 ColorChooser.rgbGreenText=Verde ColorChooser.rgbGreenMnemonic=86 ColorChooser.rgbBlueText=Azul ColorChooser.rgbBlueMnemonic=76 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_fr.properties --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_fr.properties Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_fr.properties Wed Jul 05 16:42:37 2017 +0200 @@ -101,30 +101,41 @@ ColorChooser.sampleText=Echantillon de texte Echantillon de texte ColorChooser.swatchesNameText=Echantillons ColorChooser.swatchesMnemonic=69 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Dernier : -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=V -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RVB ColorChooser.rgbMnemonic=86 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Rouge ColorChooser.rgbRedMnemonic=71 ColorChooser.rgbGreenText=Vert ColorChooser.rgbGreenMnemonic=84 ColorChooser.rgbBlueText=Bleu ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_it.properties --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_it.properties Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_it.properties Wed Jul 05 16:42:37 2017 +0200 @@ -101,30 +101,41 @@ ColorChooser.sampleText=Testo di prova Testo di prova ColorChooser.swatchesNameText=Colori campione ColorChooser.swatchesMnemonic=67 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Recenti: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=Rosso ColorChooser.rgbRedMnemonic=79 ColorChooser.rgbGreenText=Verde ColorChooser.rgbGreenMnemonic=69 ColorChooser.rgbBlueText=Blu ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ja.properties --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ja.properties Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ja.properties Wed Jul 05 16:42:37 2017 +0200 @@ -101,30 +101,41 @@ ColorChooser.sampleText=\u30b5\u30f3\u30d7\u30eb\u30c6\u30ad\u30b9\u30c8 \u30b5\u30f3\u30d7\u30eb\u30c6\u30ad\u30b9\u30c8 ColorChooser.swatchesNameText=\u30b5\u30f3\u30d7\u30eb(S) ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=5 ColorChooser.swatchesRecentText=\u6700\u65b0: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=\u8d64(D) ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=\u7dd1(N) ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=\u9752(B) ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ko.properties --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ko.properties Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_ko.properties Wed Jul 05 16:42:37 2017 +0200 @@ -101,30 +101,41 @@ ColorChooser.sampleText=\uc0d8\ud50c \ud14d\uc2a4\ud2b8 \uc0d8\ud50c \ud14d\uc2a4\ud2b8 ColorChooser.swatchesNameText=\uacac\ubcf8(S) ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=3 ColorChooser.swatchesRecentText=\ucd5c\uadfc \ubaa9\ub85d: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=\ube68\uac04\uc0c9(D) ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=\ub179\uc0c9(N) ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=\ud30c\ub780\uc0c9(B) ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_sv.properties --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_sv.properties Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_sv.properties Wed Jul 05 16:42:37 2017 +0200 @@ -101,30 +101,41 @@ ColorChooser.sampleText=Exempeltext Exempeltext ColorChooser.swatchesNameText=Prov ColorChooser.swatchesMnemonic=80 -ColorChooser.swatchesDisplayedMnemonicIndex=0 ColorChooser.swatchesRecentText=Tidigare: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=R\u00f6d ColorChooser.rgbRedMnemonic=82 ColorChooser.rgbGreenText=Gr\u00f6n ColorChooser.rgbGreenMnemonic=71 ColorChooser.rgbBlueText=Bl\u00e5 ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_CN.properties --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_CN.properties Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_CN.properties Wed Jul 05 16:42:37 2017 +0200 @@ -101,30 +101,41 @@ ColorChooser.sampleText=\u6837\u54c1\u6587\u672c \u6837\u54c1\u6587\u672c ColorChooser.swatchesNameText=\u6837\u54c1(S) ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=3 ColorChooser.swatchesRecentText=\u6700\u8fd1: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=\u7ea2 ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=\u7eff ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=\u84dd ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_TW.properties --- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_TW.properties Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_zh_TW.properties Wed Jul 05 16:42:37 2017 +0200 @@ -101,30 +101,41 @@ ColorChooser.sampleText=\u7bc4\u4f8b\u6587\u5b57 \u7bc4\u4f8b\u6587\u5b57 ColorChooser.swatchesNameText=\u8abf\u8272\u677f(S) ColorChooser.swatchesMnemonic=83 -ColorChooser.swatchesDisplayedMnemonicIndex=4 ColorChooser.swatchesRecentText=\u6700\u65b0\u9078\u64c7: -ColorChooser.hsbNameText=HSB # Each of the ColorChooser types can define a mnemonic, as a KeyEvent.VK_XXX # constant, and an index into the text to render the mnemonic as. The # mnemonic is xxxMnemonic and the index of the character to underline is # xxxDisplayedMnemonicIndex. -ColorChooser.hsbMnemonic=72 -ColorChooser.hsbDisplayedMnemonicIndex=0 -ColorChooser.hsbHueText=H -ColorChooser.hsbSaturationText=S -ColorChooser.hsbBrightnessText=B -ColorChooser.hsbRedText=R -ColorChooser.hsbGreenText=G -ColorChooser.hsbBlueText=B +ColorChooser.hsvNameText=HSV +ColorChooser.hsvMnemonic=72 +ColorChooser.hsvHueText=Hue +ColorChooser.hsvSaturationText=Saturation +ColorChooser.hsvValueText=Value +ColorChooser.hsvTransparencyText=Transparency +ColorChooser.hslNameText=HSL +ColorChooser.hslMnemonic=76 +ColorChooser.hslHueText=Hue +ColorChooser.hslSaturationText=Saturation +ColorChooser.hslLightnessText=Lightness +ColorChooser.hslTransparencyText=Transparency ColorChooser.rgbNameText=RGB ColorChooser.rgbMnemonic=71 -ColorChooser.rgbDisplayedMnemonicIndex=1 ColorChooser.rgbRedText=\u7d05\u8272(D) ColorChooser.rgbRedMnemonic=68 ColorChooser.rgbGreenText=\u7da0\u8272(N) ColorChooser.rgbGreenMnemonic=78 ColorChooser.rgbBlueText=\u85cd\u8272(B) ColorChooser.rgbBlueMnemonic=66 +ColorChooser.rgbAlphaText=Alpha +ColorChooser.rgbHexCodeText=Color Code +ColorChooser.rgbHexCodeMnemonic=67 +ColorChooser.cmykNameText=CMYK +ColorChooser.cmykMnemonic=77 +ColorChooser.cmykCyanText=Cyan +ColorChooser.cmykMagentaText=Magenta +ColorChooser.cmykYellowText=Yellow +ColorChooser.cmykBlackText=Black +ColorChooser.cmykAlphaText=Alpha ############ OPTION PANE STRINGS ############# # Mnemonic keys correspond to KeyEvent.VK_XXX constant diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/com/sun/tools/jdi/ThreadReferenceImpl.java --- a/jdk/src/share/classes/com/sun/tools/jdi/ThreadReferenceImpl.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/com/sun/tools/jdi/ThreadReferenceImpl.java Wed Jul 05 16:42:37 2017 +0200 @@ -61,7 +61,8 @@ private ThreadGroupReference threadGroup; // This is cached only while this one thread is suspended. Each time - // the thread is resumed, we clear this and start with a fresh one. + // the thread is resumed, we abandon the current cache object and + // create a new intialized one. private static class LocalCache { JDWP.ThreadReference.Status status = null; List frames = null; @@ -74,6 +75,28 @@ boolean triedCurrentContended = false; } + /* + * The localCache instance var is set by resetLocalCache to an initialized + * object as shown above. This occurs when the ThreadReference + * object is created, and when the mirrored thread is resumed. + * The fields are then filled in by the relevant methods as they + * are called. A problem can occur if resetLocalCache is called + * (ie, a resume() is executed) at certain points in the execution + * of some of these methods - see 6751643. To avoid this, each + * method that wants to use this cache must make a local copy of + * this variable and use that. This means that each invocation of + * these methods will use a copy of the cache object that was in + * effect at the point that the copy was made; if a racy resume + * occurs, it won't affect the method's local copy. This means that + * the values returned by these calls may not match the state of + * the debuggee at the time the caller gets the values. EG, + * frameCount() is called and comes up with 5 frames. But before + * it returns this, a resume of the debuggee thread is executed in a + * different debugger thread. The thread is resumed and running at + * the time that the value 5 is returned. Or even worse, the thread + * could be suspended again and have a different number of frames, eg, 24, + * but this call will still return 5. + */ private LocalCache localCache; private void resetLocalCache() { @@ -129,8 +152,9 @@ } /** - * Note that we only cache the name string while suspended because - * it can change via Thread.setName arbitrarily + * Note that we only cache the name string while the entire VM is suspended + * because the name can change via Thread.setName arbitrarily while this + * thread is running. */ public String name() { String name = null; @@ -240,19 +264,20 @@ } private JDWP.ThreadReference.Status jdwpStatus() { - JDWP.ThreadReference.Status myStatus = localCache.status; + LocalCache snapshot = localCache; + JDWP.ThreadReference.Status myStatus = snapshot.status; try { if (myStatus == null) { myStatus = JDWP.ThreadReference.Status.process(vm, this); if ((myStatus.suspendStatus & SUSPEND_STATUS_SUSPENDED) != 0) { // thread is suspended, we can cache the status. - localCache.status = myStatus; + snapshot.status = myStatus; } } } catch (JDWPException exc) { throw exc.toJDIException(); } - return myStatus; + return myStatus; } public int status() { @@ -304,9 +329,10 @@ } public int frameCount() throws IncompatibleThreadStateException { + LocalCache snapshot = localCache; try { - if (localCache.frameCount == -1) { - localCache.frameCount = JDWP.ThreadReference.FrameCount + if (snapshot.frameCount == -1) { + snapshot.frameCount = JDWP.ThreadReference.FrameCount .process(vm, this).frameCount; } } catch (JDWPException exc) { @@ -318,7 +344,7 @@ throw exc.toJDIException(); } } - return localCache.frameCount; + return snapshot.frameCount; } public List frames() throws IncompatibleThreadStateException { @@ -335,22 +361,22 @@ * local is known to be non-null. Should only be called from * a sync method. */ - private boolean isSubrange(LocalCache localCache, + private boolean isSubrange(LocalCache snapshot, int start, int length) { - if (start < localCache.framesStart) { + if (start < snapshot.framesStart) { return false; } if (length == -1) { - return (localCache.framesLength == -1); + return (snapshot.framesLength == -1); } - if (localCache.framesLength == -1) { - if ((start + length) > (localCache.framesStart + - localCache.frames.size())) { + if (snapshot.framesLength == -1) { + if ((start + length) > (snapshot.framesStart + + snapshot.frames.size())) { throw new IndexOutOfBoundsException(); } return true; } - return ((start + length) <= (localCache.framesStart + localCache.framesLength)); + return ((start + length) <= (snapshot.framesStart + snapshot.framesLength)); } public List frames(int start, int length) @@ -371,14 +397,14 @@ // Lock must be held while creating stack frames so if that two threads // do this at the same time, one won't clobber the subset created by the other. - + LocalCache snapshot = localCache; try { - if (localCache.frames == null || !isSubrange(localCache, start, length)) { + if (snapshot.frames == null || !isSubrange(snapshot, start, length)) { JDWP.ThreadReference.Frames.Frame[] jdwpFrames = JDWP.ThreadReference.Frames. process(vm, this, start, length).frames; int count = jdwpFrames.length; - localCache.frames = new ArrayList(count); + snapshot.frames = new ArrayList(count); for (int i = 0; i ownedMonitors() throws IncompatibleThreadStateException { + LocalCache snapshot = localCache; try { - if (localCache.ownedMonitors == null) { - localCache.ownedMonitors = Arrays.asList( + if (snapshot.ownedMonitors == null) { + snapshot.ownedMonitors = Arrays.asList( (ObjectReference[])JDWP.ThreadReference.OwnedMonitors. process(vm, this).owned); if ((vm.traceFlags & vm.TRACE_OBJREFS) != 0) { vm.printTrace(description() + " temporarily caching owned monitors"+ - " (count = " + localCache.ownedMonitors.size() + ")"); + " (count = " + snapshot.ownedMonitors.size() + ")"); } } } catch (JDWPException exc) { @@ -435,54 +462,57 @@ throw exc.toJDIException(); } } - return localCache.ownedMonitors; + return snapshot.ownedMonitors; } public ObjectReference currentContendedMonitor() throws IncompatibleThreadStateException { + LocalCache snapshot = localCache; try { - if (localCache.contendedMonitor == null && - !localCache.triedCurrentContended) { - localCache.contendedMonitor = JDWP.ThreadReference.CurrentContendedMonitor. + if (snapshot.contendedMonitor == null && + !snapshot.triedCurrentContended) { + snapshot.contendedMonitor = JDWP.ThreadReference.CurrentContendedMonitor. process(vm, this).monitor; - localCache.triedCurrentContended = true; - if ((localCache.contendedMonitor != null) && + snapshot.triedCurrentContended = true; + if ((snapshot.contendedMonitor != null) && ((vm.traceFlags & vm.TRACE_OBJREFS) != 0)) { vm.printTrace(description() + " temporarily caching contended monitor"+ - " (id = " + localCache.contendedMonitor.uniqueID() + ")"); + " (id = " + snapshot.contendedMonitor.uniqueID() + ")"); } } } catch (JDWPException exc) { switch (exc.errorCode()) { + case JDWP.Error.THREAD_NOT_SUSPENDED: case JDWP.Error.INVALID_THREAD: /* zombie */ throw new IncompatibleThreadStateException(); default: throw exc.toJDIException(); } } - return localCache.contendedMonitor; + return snapshot.contendedMonitor; } public List ownedMonitorsAndFrames() throws IncompatibleThreadStateException { + LocalCache snapshot = localCache; try { - if (localCache.ownedMonitorsInfo == null) { + if (snapshot.ownedMonitorsInfo == null) { JDWP.ThreadReference.OwnedMonitorsStackDepthInfo.monitor[] minfo; minfo = JDWP.ThreadReference.OwnedMonitorsStackDepthInfo.process(vm, this).owned; - localCache.ownedMonitorsInfo = new ArrayList(minfo.length); + snapshot.ownedMonitorsInfo = new ArrayList(minfo.length); for (int i=0; i < minfo.length; i++) { JDWP.ThreadReference.OwnedMonitorsStackDepthInfo.monitor mi = minfo[i]; MonitorInfo mon = new MonitorInfoImpl(vm, minfo[i].monitor, this, minfo[i].stack_depth); - localCache.ownedMonitorsInfo.add(mon); + snapshot.ownedMonitorsInfo.add(mon); } if ((vm.traceFlags & vm.TRACE_OBJREFS) != 0) { vm.printTrace(description() + " temporarily caching owned monitors"+ - " (count = " + localCache.ownedMonitorsInfo.size() + ")"); + " (count = " + snapshot.ownedMonitorsInfo.size() + ")"); } } @@ -495,7 +525,7 @@ throw exc.toJDIException(); } } - return localCache.ownedMonitorsInfo; + return snapshot.ownedMonitorsInfo; } public void popFrames(StackFrame frame) throws IncompatibleThreadStateException { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/awt/EventDispatchThread.java --- a/jdk/src/share/classes/java/awt/EventDispatchThread.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/awt/EventDispatchThread.java Wed Jul 05 16:42:37 2017 +0200 @@ -39,6 +39,7 @@ import java.util.logging.*; import sun.awt.dnd.SunDragSourceContextPeer; +import sun.awt.EventQueueDelegate; /** * EventDispatchThread is a package-private AWT class which takes @@ -243,10 +244,16 @@ try { AWTEvent event; boolean eventOK; + EventQueueDelegate.Delegate delegate = + EventQueueDelegate.getDelegate(); do { - event = (id == ANY_EVENT) - ? theQueue.getNextEvent() - : theQueue.getNextEvent(id); + if (delegate != null && id == ANY_EVENT) { + event = delegate.getNextEvent(theQueue); + } else { + event = (id == ANY_EVENT) + ? theQueue.getNextEvent() + : theQueue.getNextEvent(id); + } eventOK = true; synchronized (eventFilters) { @@ -272,7 +279,14 @@ eventLog.log(Level.FINEST, "Dispatching: " + event); } + Object handle = null; + if (delegate != null) { + handle = delegate.beforeDispatch(event); + } theQueue.dispatchEvent(event); + if (delegate != null) { + delegate.afterDispatch(event, handle); + } return true; } catch (ThreadDeath death) { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java --- a/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java Wed Jul 05 16:42:37 2017 +0200 @@ -298,7 +298,7 @@ oldL = (EventListener[])MethodUtil.invoke(m, oldInstance, new Object[]{}); newL = (EventListener[])MethodUtil.invoke(m, newInstance, new Object[]{}); } - catch (Throwable e2) { + catch (Exception e2) { try { Method m = type.getMethod("getListeners", new Class[]{Class.class}); oldL = (EventListener[])MethodUtil.invoke(m, oldInstance, new Object[]{listenerType}); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/beans/EventHandler.java --- a/jdk/src/share/classes/java/beans/EventHandler.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/beans/EventHandler.java Wed Jul 05 16:42:37 2017 +0200 @@ -404,7 +404,7 @@ Object newTarget = MethodUtil.invoke(getter, target, new Object[]{}); return applyGetters(newTarget, rest); } - catch (Throwable e) { + catch (Exception e) { throw new RuntimeException("Failed to call method: " + first + " on " + target, e); } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/beans/MetaData.java --- a/jdk/src/share/classes/java/beans/MetaData.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/beans/MetaData.java Wed Jul 05 16:42:37 2017 +0200 @@ -650,7 +650,7 @@ // Remove the new elements. // Do this first otherwise we undo the adding work. if (newMap != null) { - for ( Object newKey : newMap.keySet() ) { + for (Object newKey : newMap.keySet().toArray()) { // PENDING: This "key" is not in the right environment. if (!oldMap.containsKey(newKey)) { invokeStatement(oldInstance, "remove", new Object[]{newKey}, out); @@ -986,14 +986,20 @@ // null to defined values after the Windows are made visible - // special case them for now. if (!(oldInstance instanceof java.awt.Window)) { - String[] fieldNames = new String[]{"background", "foreground", "font"}; - for(int i = 0; i < fieldNames.length; i++) { - String name = fieldNames[i]; - Object oldValue = ReflectionUtils.getPrivateField(oldInstance, java.awt.Component.class, name, out.getExceptionListener()); - Object newValue = (newInstance == null) ? null : ReflectionUtils.getPrivateField(newInstance, java.awt.Component.class, name, out.getExceptionListener()); - if (oldValue != null && !oldValue.equals(newValue)) { - invokeStatement(oldInstance, "set" + NameGenerator.capitalize(name), new Object[]{oldValue}, out); - } + Object oldBackground = c.isBackgroundSet() ? c.getBackground() : null; + Object newBackground = c2.isBackgroundSet() ? c2.getBackground() : null; + if (!MetaData.equals(oldBackground, newBackground)) { + invokeStatement(oldInstance, "setBackground", new Object[] { oldBackground }, out); + } + Object oldForeground = c.isForegroundSet() ? c.getForeground() : null; + Object newForeground = c2.isForegroundSet() ? c2.getForeground() : null; + if (!MetaData.equals(oldForeground, newForeground)) { + invokeStatement(oldInstance, "setForeground", new Object[] { oldForeground }, out); + } + Object oldFont = c.isFontSet() ? c.getFont() : null; + Object newFont = c2.isFontSet() ? c2.getFont() : null; + if (!MetaData.equals(oldFont, newFont)) { + invokeStatement(oldInstance, "setFont", new Object[] { oldFont }, out); } } @@ -1104,26 +1110,30 @@ // BorderLayout class java_awt_BorderLayout_PersistenceDelegate extends DefaultPersistenceDelegate { + private static final String[] CONSTRAINTS = { + BorderLayout.NORTH, + BorderLayout.SOUTH, + BorderLayout.EAST, + BorderLayout.WEST, + BorderLayout.CENTER, + BorderLayout.PAGE_START, + BorderLayout.PAGE_END, + BorderLayout.LINE_START, + BorderLayout.LINE_END, + }; + @Override protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { super.initialize(type, oldInstance, newInstance, out); - String[] locations = {"north", "south", "east", "west", "center"}; - String[] names = {java.awt.BorderLayout.NORTH, java.awt.BorderLayout.SOUTH, - java.awt.BorderLayout.EAST, java.awt.BorderLayout.WEST, - java.awt.BorderLayout.CENTER}; - for(int i = 0; i < locations.length; i++) { - Object oldC = ReflectionUtils.getPrivateField(oldInstance, - java.awt.BorderLayout.class, - locations[i], - out.getExceptionListener()); - Object newC = ReflectionUtils.getPrivateField(newInstance, - java.awt.BorderLayout.class, - locations[i], - out.getExceptionListener()); + BorderLayout oldLayout = (BorderLayout) oldInstance; + BorderLayout newLayout = (BorderLayout) newInstance; + for (String constraints : CONSTRAINTS) { + Object oldC = oldLayout.getLayoutComponent(constraints); + Object newC = newLayout.getLayoutComponent(constraints); // Pending, assume any existing elements are OK. if (oldC != null && newC == null) { invokeStatement(oldInstance, "addLayoutComponent", - new Object[]{oldC, names[i]}, out); + new Object[] { oldC, constraints }, out); } } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/beans/PropertyChangeSupport.java --- a/jdk/src/share/classes/java/beans/PropertyChangeSupport.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/beans/PropertyChangeSupport.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,12 +34,49 @@ /** * This is a utility class that can be used by beans that support bound - * properties. You can use an instance of this class as a member field - * of your bean and delegate various work to it. + * properties. It manages a list of listeners and dispatches + * {@link PropertyChangeEvent}s to them. You can use an instance of this class + * as a member field of your bean and delegate these types of work to it. + * The {@link PropertyChangeListener} can be registered for all properties + * or for a property specified by name. + *

+ * Here is an example of {@code PropertyChangeSupport} usage that follows + * the rules and recommendations laid out in the JavaBeans™ specification: + *

+ * public class MyBean {
+ *     private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
+ *
+ *     public void addPropertyChangeListener(PropertyChangeListener listener) {
+ *         this.pcs.addPropertyChangeListener(listener);
+ *     }
  *
+ *     public void removePropertyChangeListener(PropertyChangeListener listener) {
+ *         this.pcs.removePropertyChangeListener(listener);
+ *     }
+ *
+ *     private String value;
+ *
+ *     public String getValue() {
+ *         return this.value;
+ *     }
+ *
+ *     public void setValue(String newValue) {
+ *         String oldValue = this.value;
+ *         this.value = newValue;
+ *         this.pcs.firePropertyChange("value", oldValue, newValue);
+ *     }
+ *
+ *     [...]
+ * }
+ * 
+ *

+ * A {@code PropertyChangeSupport} instance is thread-safe. + *

* This class is serializable. When it is serialized it will save * (and restore) any listeners that are themselves serializable. Any * non-serializable listeners will be skipped during serialization. + * + * @see VetoableChangeSupport */ public class PropertyChangeSupport implements Serializable { private PropertyChangeListenerMap map = new PropertyChangeListenerMap(); @@ -208,91 +245,91 @@ } /** - * Report a bound property update to any registered listeners. - * No event is fired if old and new are equal and non-null. - * + * Reports a bound property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * No event is fired if old and new values are equal and non-null. *

* This is merely a convenience wrapper around the more general - * firePropertyChange method that takes {@code - * PropertyChangeEvent} value. + * {@link #firePropertyChange(PropertyChangeEvent)} method. * - * @param propertyName The programmatic name of the property - * that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property */ - public void firePropertyChange(String propertyName, - Object oldValue, Object newValue) { - if (oldValue != null && newValue != null && oldValue.equals(newValue)) { - return; + public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + firePropertyChange(new PropertyChangeEvent(this.source, propertyName, oldValue, newValue)); } - firePropertyChange(new PropertyChangeEvent(source, propertyName, - oldValue, newValue)); } /** - * Report an int bound property update to any registered listeners. - * No event is fired if old and new are equal. + * Reports an integer bound property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * firePropertyChange method that takes Object values. + * {@link #firePropertyChange(String, Object, Object)} method. * - * @param propertyName The programmatic name of the property - * that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property */ - public void firePropertyChange(String propertyName, - int oldValue, int newValue) { - if (oldValue == newValue) { - return; + public void firePropertyChange(String propertyName, int oldValue, int newValue) { + if (oldValue != newValue) { + firePropertyChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } - firePropertyChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } /** - * Report a boolean bound property update to any registered listeners. - * No event is fired if old and new are equal. + * Reports a boolean bound property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * firePropertyChange method that takes Object values. + * {@link #firePropertyChange(String, Object, Object)} method. * - * @param propertyName The programmatic name of the property - * that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property */ - public void firePropertyChange(String propertyName, - boolean oldValue, boolean newValue) { - if (oldValue == newValue) { - return; + public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { + if (oldValue != newValue) { + firePropertyChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } - firePropertyChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } /** - * Fire an existing PropertyChangeEvent to any registered listeners. - * No event is fired if the given event's old and new values are - * equal and non-null. - * @param evt The PropertyChangeEvent object. + * Fires a property change event to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * No event is fired if the given event's old and new values are equal and non-null. + * + * @param event the {@code PropertyChangeEvent} to be fired */ - public void firePropertyChange(PropertyChangeEvent evt) { - Object oldValue = evt.getOldValue(); - Object newValue = evt.getNewValue(); - String propertyName = evt.getPropertyName(); - if (oldValue != null && newValue != null && oldValue.equals(newValue)) { - return; + public void firePropertyChange(PropertyChangeEvent event) { + Object oldValue = event.getOldValue(); + Object newValue = event.getNewValue(); + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + String name = event.getPropertyName(); + + PropertyChangeListener[] common = this.map.get(null); + PropertyChangeListener[] named = (name != null) + ? this.map.get(name) + : null; + + fire(common, event); + fire(named, event); } - PropertyChangeListener[] common = this.map.get(null); - PropertyChangeListener[] named = (propertyName != null) - ? this.map.get(propertyName) - : null; - - fire(common, evt); - fire(named, evt); } - private void fire(PropertyChangeListener[] listeners, PropertyChangeEvent event) { + private static void fire(PropertyChangeListener[] listeners, PropertyChangeEvent event) { if (listeners != null) { for (PropertyChangeListener listener : listeners) { listener.propertyChange(event); @@ -301,78 +338,69 @@ } /** - * Report a bound indexed property update to any registered - * listeners. + * Reports a bound indexed property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

- * No event is fired if old and new values are equal - * and non-null. - * + * No event is fired if old and new values are equal and non-null. *

* This is merely a convenience wrapper around the more general - * firePropertyChange method that takes {@code PropertyChangeEvent} value. + * {@link #firePropertyChange(PropertyChangeEvent)} method. * - * @param propertyName The programmatic name of the property that - * was changed. - * @param index index of the property element that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param index the index of the property element that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property * @since 1.5 */ - public void fireIndexedPropertyChange(String propertyName, int index, - Object oldValue, Object newValue) { - firePropertyChange(new IndexedPropertyChangeEvent - (source, propertyName, oldValue, newValue, index)); + public void fireIndexedPropertyChange(String propertyName, int index, Object oldValue, Object newValue) { + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + firePropertyChange(new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index)); + } } /** - * Report an int bound indexed property update to any registered - * listeners. + * Reports an integer bound indexed property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

* No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * fireIndexedPropertyChange method which takes Object values. + * {@link #fireIndexedPropertyChange(String, int, Object, Object)} method. * - * @param propertyName The programmatic name of the property that - * was changed. - * @param index index of the property element that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param index the index of the property element that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property * @since 1.5 */ - public void fireIndexedPropertyChange(String propertyName, int index, - int oldValue, int newValue) { - if (oldValue == newValue) { - return; + public void fireIndexedPropertyChange(String propertyName, int index, int oldValue, int newValue) { + if (oldValue != newValue) { + fireIndexedPropertyChange(propertyName, index, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } - fireIndexedPropertyChange(propertyName, index, - Integer.valueOf(oldValue), - Integer.valueOf(newValue)); } /** - * Report a boolean bound indexed property update to any - * registered listeners. + * Reports a boolean bound indexed property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

* No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * fireIndexedPropertyChange method which takes Object values. + * {@link #fireIndexedPropertyChange(String, int, Object, Object)} method. * - * @param propertyName The programmatic name of the property that - * was changed. - * @param index index of the property element that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that was changed + * @param index the index of the property element that was changed + * @param oldValue the old value of the property + * @param newValue the new value of the property * @since 1.5 */ - public void fireIndexedPropertyChange(String propertyName, int index, - boolean oldValue, boolean newValue) { - if (oldValue == newValue) { - return; + public void fireIndexedPropertyChange(String propertyName, int index, boolean oldValue, boolean newValue) { + if (oldValue != newValue) { + fireIndexedPropertyChange(propertyName, index, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } - fireIndexedPropertyChange(propertyName, index, Boolean.valueOf(oldValue), - Boolean.valueOf(newValue)); } /** diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/beans/PropertyEditor.java --- a/jdk/src/share/classes/java/beans/PropertyEditor.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/beans/PropertyEditor.java Wed Jul 05 16:42:37 2017 +0200 @@ -204,20 +204,21 @@ //---------------------------------------------------------------------- /** - * Register a listener for the PropertyChange event. When a - * PropertyEditor changes its value it should fire a PropertyChange - * event on all registered PropertyChangeListeners, specifying the - * null value for the property name and itself as the source. + * Adds a listener for the value change. + * When the property editor changes its value + * it should fire a {@link PropertyChangeEvent} + * on all registered {@link PropertyChangeListener}s, + * specifying the {@code null} value for the property name + * and itself as the source. * - * @param listener An object to be invoked when a PropertyChange - * event is fired. + * @param listener the {@link PropertyChangeListener} to add */ void addPropertyChangeListener(PropertyChangeListener listener); /** - * Remove a listener for the PropertyChange event. + * Removes a listener for the value change. * - * @param listener The PropertyChange listener to be removed. + * @param listener the {@link PropertyChangeListener} to remove */ void removePropertyChangeListener(PropertyChangeListener listener); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/beans/PropertyEditorManager.java --- a/jdk/src/share/classes/java/beans/PropertyEditorManager.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/beans/PropertyEditorManager.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * 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 @@ package java.beans; +import com.sun.beans.WeakCache; import sun.beans.editors.*; /** @@ -55,32 +56,30 @@ public class PropertyEditorManager { /** - * Register an editor class to be used to edit values of - * a given target class. - * - *

First, if there is a security manager, its checkPropertiesAccess - * method is called. This could result in a SecurityException. + * Registers an editor class to edit values of the given target class. + * If the editor class is {@code null}, + * then any existing definition will be removed. + * Thus this method can be used to cancel the registration. + * The registration is canceled automatically + * if either the target or editor class is unloaded. + *

+ * If there is a security manager, its {@code checkPropertiesAccess} + * method is called. This could result in a {@linkplain SecurityException}. * - * @param targetType the Class object of the type to be edited - * @param editorClass the Class object of the editor class. If - * this is null, then any existing definition will be removed. - * @exception SecurityException if a security manager exists and its - * checkPropertiesAccess method doesn't allow setting - * of system properties. + * @param targetType the class object of the type to be edited + * @param editorClass the class object of the editor class + * @throws SecurityException if a security manager exists and + * its {@code checkPropertiesAccess} method + * doesn't allow setting of system properties + * * @see SecurityManager#checkPropertiesAccess */ - - public static void registerEditor(Class targetType, Class editorClass) { + public static synchronized void registerEditor(Class targetType, Class editorClass) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } - initialize(); - if (editorClass == null) { - registry.remove(targetType); - } else { - registry.put(targetType, editorClass); - } + registry.put(targetType, editorClass); } /** @@ -90,10 +89,8 @@ * @return An editor object for the given target class. * The result is null if no suitable editor can be found. */ - public static synchronized PropertyEditor findEditor(Class targetType) { - initialize(); - Class editorClass = (Class)registry.get(targetType); + Class editorClass = registry.get(targetType); if (editorClass != null) { try { Object o = editorClass.newInstance(); @@ -143,10 +140,7 @@ * e.g. Sun implementation initially sets to {"sun.beans.editors"}. */ public static synchronized String[] getEditorSearchPath() { - // Return a copy of the searchPath. - String result[] = new String[searchPath.length]; - System.arraycopy(searchPath, 0, result, 0, searchPath.length); - return result; + return searchPath.clone(); } /** @@ -162,23 +156,22 @@ * of system properties. * @see SecurityManager#checkPropertiesAccess */ - - public static synchronized void setEditorSearchPath(String path[]) { + public static synchronized void setEditorSearchPath(String[] path) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } - if (path == null) { - path = new String[0]; - } - searchPath = path; + searchPath = (path != null) + ? path.clone() + : EMPTY; } - private static synchronized void initialize() { - if (registry != null) { - return; - } - registry = new java.util.Hashtable(); + private static String[] searchPath = { "sun.beans.editors" }; + private static final String[] EMPTY = {}; + private static final WeakCache, Class> registry; + + static { + registry = new WeakCache, Class>(); registry.put(Byte.TYPE, ByteEditor.class); registry.put(Short.TYPE, ShortEditor.class); registry.put(Integer.TYPE, IntegerEditor.class); @@ -187,7 +180,4 @@ registry.put(Float.TYPE, FloatEditor.class); registry.put(Double.TYPE, DoubleEditor.class); } - - private static String[] searchPath = { "sun.beans.editors" }; - private static java.util.Hashtable registry; } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/beans/PropertyEditorSupport.java --- a/jdk/src/share/classes/java/beans/PropertyEditorSupport.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/beans/PropertyEditorSupport.java Wed Jul 05 16:42:37 2017 +0200 @@ -233,11 +233,20 @@ //---------------------------------------------------------------------- /** - * Register a listener for the PropertyChange event. The class will - * fire a PropertyChange value whenever the value is updated. + * Adds a listener for the value change. + * When the property editor changes its value + * it should fire a {@link PropertyChangeEvent} + * on all registered {@link PropertyChangeListener}s, + * specifying the {@code null} value for the property name. + * If the source property is set, + * it should be used as the source of the event. + *

+ * The same listener object may be added more than once, + * and will be called as many times as it is added. + * If {@code listener} is {@code null}, + * no exception is thrown and no action is taken. * - * @param listener An object to be invoked when a PropertyChange - * event is fired. + * @param listener the {@link PropertyChangeListener} to add */ public synchronized void addPropertyChangeListener( PropertyChangeListener listener) { @@ -248,9 +257,14 @@ } /** - * Remove a listener for the PropertyChange event. + * Removes a listener for the value change. + *

+ * If the same listener was added more than once, + * it will be notified one less time after being removed. + * If {@code listener} is {@code null}, or was never added, + * no exception is thrown and no action is taken. * - * @param listener The PropertyChange listener to be removed. + * @param listener the {@link PropertyChangeListener} to remove */ public synchronized void removePropertyChangeListener( PropertyChangeListener listener) { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/beans/VetoableChangeSupport.java --- a/jdk/src/share/classes/java/beans/VetoableChangeSupport.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/beans/VetoableChangeSupport.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,12 +34,49 @@ /** * This is a utility class that can be used by beans that support constrained - * properties. You can use an instance of this class as a member field - * of your bean and delegate various work to it. + * properties. It manages a list of listeners and dispatches + * {@link PropertyChangeEvent}s to them. You can use an instance of this class + * as a member field of your bean and delegate these types of work to it. + * The {@link VetoableChangeListener} can be registered for all properties + * or for a property specified by name. + *

+ * Here is an example of {@code VetoableChangeSupport} usage that follows + * the rules and recommendations laid out in the JavaBeans™ specification: + *

+ * public class MyBean {
+ *     private final VetoableChangeSupport vcs = new VetoableChangeSupport(this);
+ *
+ *     public void addVetoableChangeListener(VetoableChangeListener listener) {
+ *         this.vcs.addVetoableChangeListener(listener);
+ *     }
  *
+ *     public void removeVetoableChangeListener(VetoableChangeListener listener) {
+ *         this.vcs.removeVetoableChangeListener(listener);
+ *     }
+ *
+ *     private String value;
+ *
+ *     public String getValue() {
+ *         return this.value;
+ *     }
+ *
+ *     public void setValue(String newValue) throws PropertyVetoException {
+ *         String oldValue = this.value;
+ *         this.vcs.fireVetoableChange("value", oldValue, newValue);
+ *         this.value = newValue;
+ *     }
+ *
+ *     [...]
+ * }
+ * 
+ *

+ * A {@code VetoableChangeSupport} instance is thread-safe. + *

* This class is serializable. When it is serialized it will save * (and restore) any listeners that are themselves serializable. Any * non-serializable listeners will be skipped during serialization. + * + * @see PropertyChangeSupport */ public class VetoableChangeSupport implements Serializable { private VetoableChangeListenerMap map = new VetoableChangeListenerMap(); @@ -208,126 +245,149 @@ } /** - * Report a vetoable property update to any registered listeners. If - * anyone vetos the change, then fire a new event reverting everyone to - * the old value and then rethrow the PropertyVetoException. + * Reports a constrained property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

- * No event is fired if old and new are equal and non-null. + * Any listener can throw a {@code PropertyVetoException} to veto the update. + * If one of the listeners vetoes the update, this method passes + * a new "undo" {@code PropertyChangeEvent} that reverts to the old value + * to all listeners that already confirmed this update + * and throws the {@code PropertyVetoException} again. + *

+ * No event is fired if old and new values are equal and non-null. + *

+ * This is merely a convenience wrapper around the more general + * {@link #fireVetoableChange(PropertyChangeEvent)} method. * - * @param propertyName The programmatic name of the property - * that is about to change.. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. - * @exception PropertyVetoException if the recipient wishes the property - * change to be rolled back. + * @param propertyName the programmatic name of the property that is about to change + * @param oldValue the old value of the property + * @param newValue the new value of the property + * @throws PropertyVetoException if one of listeners vetoes the property update */ - public void fireVetoableChange(String propertyName, - Object oldValue, Object newValue) - throws PropertyVetoException { - if (oldValue != null && newValue != null && oldValue.equals(newValue)) { - return; + public void fireVetoableChange(String propertyName, Object oldValue, Object newValue) + throws PropertyVetoException { + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + fireVetoableChange(new PropertyChangeEvent(this.source, propertyName, oldValue, newValue)); } - PropertyChangeEvent evt = new PropertyChangeEvent(source, propertyName, - oldValue, newValue); - fireVetoableChange(evt); } /** - * Report a int vetoable property update to any registered listeners. - * No event is fired if old and new are equal. + * Reports an integer constrained property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * Any listener can throw a {@code PropertyVetoException} to veto the update. + * If one of the listeners vetoes the update, this method passes + * a new "undo" {@code PropertyChangeEvent} that reverts to the old value + * to all listeners that already confirmed this update + * and throws the {@code PropertyVetoException} again. + *

+ * No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * fireVetoableChange method that takes Object values. + * {@link #fireVetoableChange(String, Object, Object)} method. * - * @param propertyName The programmatic name of the property - * that is about to change. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that is about to change + * @param oldValue the old value of the property + * @param newValue the new value of the property + * @throws PropertyVetoException if one of listeners vetoes the property update */ - public void fireVetoableChange(String propertyName, - int oldValue, int newValue) - throws PropertyVetoException { - if (oldValue == newValue) { - return; + public void fireVetoableChange(String propertyName, int oldValue, int newValue) + throws PropertyVetoException { + if (oldValue != newValue) { + fireVetoableChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } - fireVetoableChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } /** - * Report a boolean vetoable property update to any registered listeners. - * No event is fired if old and new are equal. + * Reports a boolean constrained property update to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. + *

+ * Any listener can throw a {@code PropertyVetoException} to veto the update. + * If one of the listeners vetoes the update, this method passes + * a new "undo" {@code PropertyChangeEvent} that reverts to the old value + * to all listeners that already confirmed this update + * and throws the {@code PropertyVetoException} again. + *

+ * No event is fired if old and new values are equal. *

* This is merely a convenience wrapper around the more general - * fireVetoableChange method that takes Object values. + * {@link #fireVetoableChange(String, Object, Object)} method. * - * @param propertyName The programmatic name of the property - * that is about to change. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. + * @param propertyName the programmatic name of the property that is about to change + * @param oldValue the old value of the property + * @param newValue the new value of the property + * @throws PropertyVetoException if one of listeners vetoes the property update */ - public void fireVetoableChange(String propertyName, - boolean oldValue, boolean newValue) - throws PropertyVetoException { - if (oldValue == newValue) { - return; + public void fireVetoableChange(String propertyName, boolean oldValue, boolean newValue) + throws PropertyVetoException { + if (oldValue != newValue) { + fireVetoableChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } - fireVetoableChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); } /** - * Fire a vetoable property update to any registered listeners. If - * anyone vetos the change, then fire a new event reverting everyone to - * the old value and then rethrow the PropertyVetoException. + * Fires a property change event to listeners + * that have been registered to track updates of + * all properties or a property with the specified name. *

- * No event is fired if old and new are equal and non-null. + * Any listener can throw a {@code PropertyVetoException} to veto the update. + * If one of the listeners vetoes the update, this method passes + * a new "undo" {@code PropertyChangeEvent} that reverts to the old value + * to all listeners that already confirmed this update + * and throws the {@code PropertyVetoException} again. + *

+ * No event is fired if the given event's old and new values are equal and non-null. * - * @param evt The PropertyChangeEvent to be fired. - * @exception PropertyVetoException if the recipient wishes the property - * change to be rolled back. + * @param event the {@code PropertyChangeEvent} to be fired + * @throws PropertyVetoException if one of listeners vetoes the property update */ - public void fireVetoableChange(PropertyChangeEvent evt) - throws PropertyVetoException { + public void fireVetoableChange(PropertyChangeEvent event) + throws PropertyVetoException { + Object oldValue = event.getOldValue(); + Object newValue = event.getNewValue(); + if (oldValue == null || newValue == null || !oldValue.equals(newValue)) { + String name = event.getPropertyName(); - Object oldValue = evt.getOldValue(); - Object newValue = evt.getNewValue(); - String propertyName = evt.getPropertyName(); - if (oldValue != null && newValue != null && oldValue.equals(newValue)) { - return; - } - VetoableChangeListener[] common = this.map.get(null); - VetoableChangeListener[] named = (propertyName != null) - ? this.map.get(propertyName) - : null; - fire(common, evt); - fire(named, evt); - } + VetoableChangeListener[] common = this.map.get(null); + VetoableChangeListener[] named = (name != null) + ? this.map.get(name) + : null; - private void fire(VetoableChangeListener[] listeners, PropertyChangeEvent event) throws PropertyVetoException { - if (listeners != null) { - VetoableChangeListener current = null; - try { - for (VetoableChangeListener listener : listeners) { - current = listener; - listener.vetoableChange(event); - } - } catch (PropertyVetoException veto) { - // Create an event to revert everyone to the old value. - event = new PropertyChangeEvent( this.source, - event.getPropertyName(), - event.getNewValue(), - event.getOldValue() ); - for (VetoableChangeListener listener : listeners) { - if (current == listener) { - break; - } - try { - listener.vetoableChange(event); - } catch (PropertyVetoException ex) { - // We just ignore exceptions that occur during reversions. + VetoableChangeListener[] listeners; + if (common == null) { + listeners = named; + } + else if (named == null) { + listeners = common; + } + else { + listeners = new VetoableChangeListener[common.length + named.length]; + System.arraycopy(common, 0, listeners, 0, common.length); + System.arraycopy(named, 0, listeners, common.length, named.length); + } + if (listeners != null) { + int current = 0; + try { + while (current < listeners.length) { + listeners[current].vetoableChange(event); + current++; } } - // And now rethrow the PropertyVetoException. - throw veto; + catch (PropertyVetoException veto) { + event = new PropertyChangeEvent(this.source, name, newValue, oldValue); + for (int i = 0; i < current; i++) { + try { + listeners[i].vetoableChange(event); + } + catch (PropertyVetoException exception) { + // ignore exceptions that occur during rolling back + } + } + throw veto; // rethrow the veto exception + } } } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/io/CharConversionException.java --- a/jdk/src/share/classes/java/io/CharConversionException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/io/CharConversionException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1996-1999 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,8 @@ public class CharConversionException extends java.io.IOException { + private static final long serialVersionUID = -8680016352018427031L; + /** * This provides no detailed message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/io/EOFException.java --- a/jdk/src/share/classes/java/io/EOFException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/io/EOFException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-2000 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,6 +41,8 @@ */ public class EOFException extends IOException { + private static final long serialVersionUID = 6433858223774886977L; + /** * Constructs an EOFException with null * as its error detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/io/FileNotFoundException.java --- a/jdk/src/share/classes/java/io/FileNotFoundException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/io/FileNotFoundException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1999 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,6 +41,7 @@ */ public class FileNotFoundException extends IOException { + private static final long serialVersionUID = -897856973823710492L; /** * Constructs a FileNotFoundException with diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/io/InterruptedIOException.java --- a/jdk/src/share/classes/java/io/InterruptedIOException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/io/InterruptedIOException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-2000 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,6 +41,8 @@ */ public class InterruptedIOException extends IOException { + private static final long serialVersionUID = 4020568460727500567L; + /** * Constructs an InterruptedIOException with * null as its error detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/io/SyncFailedException.java --- a/jdk/src/share/classes/java/io/SyncFailedException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/io/SyncFailedException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1996-1999 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,8 @@ * @since JDK1.1 */ public class SyncFailedException extends IOException { + private static final long serialVersionUID = -2353342684412443330L; + /** * Constructs an SyncFailedException with a detail message. * A detail message is a String that describes this particular exception. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/io/UTFDataFormatException.java --- a/jdk/src/share/classes/java/io/UTFDataFormatException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/io/UTFDataFormatException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-2004 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,6 +44,8 @@ */ public class UTFDataFormatException extends IOException { + private static final long serialVersionUID = 420743449228280612L; + /** * Constructs a UTFDataFormatException with * null as its error detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/io/UnsupportedEncodingException.java --- a/jdk/src/share/classes/java/io/UnsupportedEncodingException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/io/UnsupportedEncodingException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1996-1999 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,8 @@ public class UnsupportedEncodingException extends IOException { + private static final long serialVersionUID = -4274276298326136670L; + /** * Constructs an UnsupportedEncodingException without a detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/AbstractMethodError.java --- a/jdk/src/share/classes/java/lang/AbstractMethodError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/AbstractMethodError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,8 @@ */ public class AbstractMethodError extends IncompatibleClassChangeError { + private static final long serialVersionUID = -1654391082989018462L; + /** * Constructs an AbstractMethodError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/ArithmeticException.java --- a/jdk/src/share/classes/java/lang/ArithmeticException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/ArithmeticException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,8 @@ */ public class ArithmeticException extends RuntimeException { + private static final long serialVersionUID = 2256477558314496007L; + /** * Constructs an ArithmeticException with no detail * message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/ArrayIndexOutOfBoundsException.java --- a/jdk/src/share/classes/java/lang/ArrayIndexOutOfBoundsException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/ArrayIndexOutOfBoundsException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,8 @@ */ public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException { + private static final long serialVersionUID = -5116101128118950844L; + /** * Constructs an ArrayIndexOutOfBoundsException with no * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/ArrayStoreException.java --- a/jdk/src/share/classes/java/lang/ArrayStoreException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/ArrayStoreException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,6 +39,8 @@ */ public class ArrayStoreException extends RuntimeException { + private static final long serialVersionUID = -4522193890499838241L; + /** * Constructs an ArrayStoreException with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/AssertionError.java --- a/jdk/src/share/classes/java/lang/AssertionError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/AssertionError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,6 +43,8 @@ * @since 1.4 */ public class AssertionError extends Error { + private static final long serialVersionUID = -5013299493970297370L; + /** * Constructs an AssertionError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/ClassCastException.java --- a/jdk/src/share/classes/java/lang/ClassCastException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/ClassCastException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,6 +39,8 @@ */ public class ClassCastException extends RuntimeException { + private static final long serialVersionUID = -9223365651070458532L; + /** * Constructs a ClassCastException with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/ClassCircularityError.java --- a/jdk/src/share/classes/java/lang/ClassCircularityError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/ClassCircularityError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,8 @@ * @since JDK1.0 */ public class ClassCircularityError extends LinkageError { + private static final long serialVersionUID = 1054362542914539689L; + /** * Constructs a {@code ClassCircularityError} with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/ClassFormatError.java --- a/jdk/src/share/classes/java/lang/ClassFormatError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/ClassFormatError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,8 @@ */ public class ClassFormatError extends LinkageError { + private static final long serialVersionUID = -8420114879011949195L; + /** * Constructs a ClassFormatError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/CloneNotSupportedException.java --- a/jdk/src/share/classes/java/lang/CloneNotSupportedException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/CloneNotSupportedException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,6 +43,8 @@ public class CloneNotSupportedException extends Exception { + private static final long serialVersionUID = 5195511250079656443L; + /** * Constructs a CloneNotSupportedException with no * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/EnumConstantNotPresentException.java --- a/jdk/src/share/classes/java/lang/EnumConstantNotPresentException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/EnumConstantNotPresentException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2004-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,8 @@ * @since 1.5 */ public class EnumConstantNotPresentException extends RuntimeException { + private static final long serialVersionUID = -6046998521960521108L; + /** * The type of the missing enum constant. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/IllegalAccessError.java --- a/jdk/src/share/classes/java/lang/IllegalAccessError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/IllegalAccessError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,8 @@ * @since JDK1.0 */ public class IllegalAccessError extends IncompatibleClassChangeError { + private static final long serialVersionUID = -8988904074992417891L; + /** * Constructs an IllegalAccessError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/IllegalAccessException.java --- a/jdk/src/share/classes/java/lang/IllegalAccessException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/IllegalAccessException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-2000 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ * @since JDK1.0 */ public class IllegalAccessException extends Exception { + private static final long serialVersionUID = 6616958222490762034L; + /** * Constructs an IllegalAccessException without a * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/IllegalMonitorStateException.java --- a/jdk/src/share/classes/java/lang/IllegalMonitorStateException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/IllegalMonitorStateException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,6 +40,8 @@ */ public class IllegalMonitorStateException extends RuntimeException { + private static final long serialVersionUID = 3713306369498869069L; + /** * Constructs an IllegalMonitorStateException with no * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/IllegalThreadStateException.java --- a/jdk/src/share/classes/java/lang/IllegalThreadStateException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/IllegalThreadStateException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,8 @@ * @since JDK1.0 */ public class IllegalThreadStateException extends IllegalArgumentException { + private static final long serialVersionUID = -7626246362397460174L; + /** * Constructs an IllegalThreadStateException with no * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/IncompatibleClassChangeError.java --- a/jdk/src/share/classes/java/lang/IncompatibleClassChangeError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/IncompatibleClassChangeError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,8 @@ */ public class IncompatibleClassChangeError extends LinkageError { + private static final long serialVersionUID = -4914975503642802119L; + /** * Constructs an IncompatibleClassChangeError with no * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/IndexOutOfBoundsException.java --- a/jdk/src/share/classes/java/lang/IndexOutOfBoundsException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/IndexOutOfBoundsException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,6 +36,8 @@ */ public class IndexOutOfBoundsException extends RuntimeException { + private static final long serialVersionUID = 234122996006267687L; + /** * Constructs an IndexOutOfBoundsException with no * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/InstantiationError.java --- a/jdk/src/share/classes/java/lang/InstantiationError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/InstantiationError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,6 +40,8 @@ public class InstantiationError extends IncompatibleClassChangeError { + private static final long serialVersionUID = -4885810657349421204L; + /** * Constructs an InstantiationError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/InstantiationException.java --- a/jdk/src/share/classes/java/lang/InstantiationException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/InstantiationException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,6 +44,8 @@ */ public class InstantiationException extends Exception { + private static final long serialVersionUID = -8441929162975509110L; + /** * Constructs an {@code InstantiationException} with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/InternalError.java --- a/jdk/src/share/classes/java/lang/InternalError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/InternalError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,8 @@ */ public class InternalError extends VirtualMachineError { + private static final long serialVersionUID = -9062593416125562365L; + /** * Constructs an InternalError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/InterruptedException.java --- a/jdk/src/share/classes/java/lang/InterruptedException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/InterruptedException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -48,6 +48,8 @@ */ public class InterruptedException extends Exception { + private static final long serialVersionUID = 6700697376100628473L; + /** * Constructs an InterruptedException with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/LinkageError.java --- a/jdk/src/share/classes/java/lang/LinkageError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/LinkageError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,6 +36,8 @@ */ public class LinkageError extends Error { + private static final long serialVersionUID = 3579600108157160122L; + /** * Constructs a LinkageError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/NegativeArraySizeException.java --- a/jdk/src/share/classes/java/lang/NegativeArraySizeException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/NegativeArraySizeException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,8 @@ */ public class NegativeArraySizeException extends RuntimeException { + private static final long serialVersionUID = -8960118058596991861L; + /** * Constructs a NegativeArraySizeException with no * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/NoClassDefFoundError.java --- a/jdk/src/share/classes/java/lang/NoClassDefFoundError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/NoClassDefFoundError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-2000 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,6 +40,8 @@ */ public class NoClassDefFoundError extends LinkageError { + private static final long serialVersionUID = 9095859863287012458L; + /** * Constructs a NoClassDefFoundError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/NoSuchFieldError.java --- a/jdk/src/share/classes/java/lang/NoSuchFieldError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/NoSuchFieldError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,6 +38,8 @@ */ public class NoSuchFieldError extends IncompatibleClassChangeError { + private static final long serialVersionUID = -3456430195886129035L; + /** * Constructs a NoSuchFieldException with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/NoSuchFieldException.java --- a/jdk/src/share/classes/java/lang/NoSuchFieldException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/NoSuchFieldException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1996-1999 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,8 @@ * @since JDK1.1 */ public class NoSuchFieldException extends Exception { + private static final long serialVersionUID = -6143714805279938260L; + /** * Constructor. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/NoSuchMethodError.java --- a/jdk/src/share/classes/java/lang/NoSuchMethodError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/NoSuchMethodError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1998 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,6 +39,8 @@ */ public class NoSuchMethodError extends IncompatibleClassChangeError { + private static final long serialVersionUID = -3765521442372831335L; + /** * Constructs a NoSuchMethodError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/NoSuchMethodException.java --- a/jdk/src/share/classes/java/lang/NoSuchMethodException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/NoSuchMethodException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,8 @@ */ public class NoSuchMethodException extends Exception { + private static final long serialVersionUID = 5034388446362600923L; + /** * Constructs a NoSuchMethodException without a detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/NullPointerException.java --- a/jdk/src/share/classes/java/lang/NullPointerException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/NullPointerException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,6 +46,8 @@ */ public class NullPointerException extends RuntimeException { + private static final long serialVersionUID = 5162710183389028792L; + /** * Constructs a NullPointerException with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/OutOfMemoryError.java --- a/jdk/src/share/classes/java/lang/OutOfMemoryError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/OutOfMemoryError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,8 @@ */ public class OutOfMemoryError extends VirtualMachineError { + private static final long serialVersionUID = 8228564086184010517L; + /** * Constructs an OutOfMemoryError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/StackOverflowError.java --- a/jdk/src/share/classes/java/lang/StackOverflowError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/StackOverflowError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,8 @@ */ public class StackOverflowError extends VirtualMachineError { + private static final long serialVersionUID = 8609175038441759607L; + /** * Constructs a StackOverflowError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/StringIndexOutOfBoundsException.java --- a/jdk/src/share/classes/java/lang/StringIndexOutOfBoundsException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/StringIndexOutOfBoundsException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-2000 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,8 @@ */ public class StringIndexOutOfBoundsException extends IndexOutOfBoundsException { + private static final long serialVersionUID = -6762910422159637258L; + /** * Constructs a StringIndexOutOfBoundsException with no * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/ThreadDeath.java --- a/jdk/src/share/classes/java/lang/ThreadDeath.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/ThreadDeath.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,4 +46,6 @@ * @since JDK1.0 */ -public class ThreadDeath extends Error {} +public class ThreadDeath extends Error { + private static final long serialVersionUID = -4417128565033088268L; +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/TypeNotPresentException.java --- a/jdk/src/share/classes/java/lang/TypeNotPresentException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/TypeNotPresentException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,6 +40,8 @@ * @since 1.5 */ public class TypeNotPresentException extends RuntimeException { + private static final long serialVersionUID = -5101214195716534496L; + private String typeName; /** diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/UnknownError.java --- a/jdk/src/share/classes/java/lang/UnknownError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/UnknownError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,8 @@ */ public class UnknownError extends VirtualMachineError { + private static final long serialVersionUID = 2524784860676771849L; + /** * Constructs an UnknownError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/UnsatisfiedLinkError.java --- a/jdk/src/share/classes/java/lang/UnsatisfiedLinkError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/UnsatisfiedLinkError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,8 @@ */ public class UnsatisfiedLinkError extends LinkageError { + private static final long serialVersionUID = -4019343241616879428L; + /** * Constructs an UnsatisfiedLinkError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/UnsupportedClassVersionError.java --- a/jdk/src/share/classes/java/lang/UnsupportedClassVersionError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/UnsupportedClassVersionError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,8 @@ */ public class UnsupportedClassVersionError extends ClassFormatError { + private static final long serialVersionUID = -7123279212883497373L; + /** * Constructs a UnsupportedClassVersionError * with no detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/VerifyError.java --- a/jdk/src/share/classes/java/lang/VerifyError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/VerifyError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,8 @@ */ public class VerifyError extends LinkageError { + private static final long serialVersionUID = 7001962396098498785L; + /** * Constructs an VerifyError with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/annotation/AnnotationFormatError.java --- a/jdk/src/share/classes/java/lang/annotation/AnnotationFormatError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/annotation/AnnotationFormatError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2004-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,8 @@ * @since 1.5 */ public class AnnotationFormatError extends Error { + private static final long serialVersionUID = -4256701562333669892L; + /** * Constructs a new AnnotationFormatError with the specified * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/annotation/AnnotationTypeMismatchException.java --- a/jdk/src/share/classes/java/lang/annotation/AnnotationTypeMismatchException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/annotation/AnnotationTypeMismatchException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,8 @@ * @since 1.5 */ public class AnnotationTypeMismatchException extends RuntimeException { + private static final long serialVersionUID = 8125925355765570191L; + /** * The Method object for the annotation element. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/annotation/IncompleteAnnotationException.java --- a/jdk/src/share/classes/java/lang/annotation/IncompleteAnnotationException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/annotation/IncompleteAnnotationException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,8 @@ * @since 1.5 */ public class IncompleteAnnotationException extends RuntimeException { + private static final long serialVersionUID = 8445097402741811912L; + private Class annotationType; private String elementName; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/instrument/IllegalClassFormatException.java --- a/jdk/src/share/classes/java/lang/instrument/IllegalClassFormatException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/instrument/IllegalClassFormatException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,6 +40,8 @@ * @since 1.5 */ public class IllegalClassFormatException extends Exception { + private static final long serialVersionUID = -3841736710924794009L; + /** * Constructs an IllegalClassFormatException with no * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/instrument/UnmodifiableClassException.java --- a/jdk/src/share/classes/java/lang/instrument/UnmodifiableClassException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/instrument/UnmodifiableClassException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2004-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,8 @@ * @since 1.5 */ public class UnmodifiableClassException extends Exception { + private static final long serialVersionUID = 1716652643585309178L; + /** * Constructs an UnmodifiableClassException with no * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/management/ManagementPermission.java --- a/jdk/src/share/classes/java/lang/management/ManagementPermission.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/management/ManagementPermission.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -83,6 +83,7 @@ */ public final class ManagementPermission extends java.security.BasicPermission { + private static final long serialVersionUID = 1897496590799378737L; /** * Constructs a ManagementPermission with the specified name. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/reflect/GenericSignatureFormatError.java --- a/jdk/src/share/classes/java/lang/reflect/GenericSignatureFormatError.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/reflect/GenericSignatureFormatError.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,4 +33,6 @@ * * @since 1.5 */ -public class GenericSignatureFormatError extends ClassFormatError{} +public class GenericSignatureFormatError extends ClassFormatError { + private static final long serialVersionUID = 6709919147137911034L; +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/lang/reflect/MalformedParameterizedTypeException.java --- a/jdk/src/share/classes/java/lang/reflect/MalformedParameterizedTypeException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/lang/reflect/MalformedParameterizedTypeException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,4 +34,6 @@ * * @since 1.5 */ -public class MalformedParameterizedTypeException extends RuntimeException{} +public class MalformedParameterizedTypeException extends RuntimeException { + private static final long serialVersionUID = -5696557788586220964L; +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/net/AbstractPlainSocketImpl.java --- a/jdk/src/share/classes/java/net/AbstractPlainSocketImpl.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/net/AbstractPlainSocketImpl.java Wed Jul 05 16:42:37 2017 +0200 @@ -308,6 +308,12 @@ FileDescriptor fd = acquireFD(); try { socketConnect(address, port, timeout); + /* socket may have been closed during poll/select */ + synchronized (fdLock) { + if (closePending) { + throw new SocketException ("Socket closed"); + } + } // If we have a ref. to the Socket, then sets the flags // created, bound & connected to true. // This is normally done in Socket.connect() but some diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/net/BindException.java --- a/jdk/src/share/classes/java/net/BindException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/net/BindException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1996-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,7 @@ */ public class BindException extends SocketException { + private static final long serialVersionUID = -5945005768251722951L; /** * Constructs a new BindException with the specified detail diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/net/ConnectException.java --- a/jdk/src/share/classes/java/net/ConnectException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/net/ConnectException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1996-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,8 @@ * @since JDK1.1 */ public class ConnectException extends SocketException { + private static final long serialVersionUID = 3831404271622369215L; + /** * Constructs a new ConnectException with the specified detail * message as to why the connect error occurred. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/net/HttpRetryException.java --- a/jdk/src/share/classes/java/net/HttpRetryException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/net/HttpRetryException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2004-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,7 @@ */ public class HttpRetryException extends IOException { + private static final long serialVersionUID = -9186022286469111381L; private int responseCode; private String location; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/net/MalformedURLException.java --- a/jdk/src/share/classes/java/net/MalformedURLException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/net/MalformedURLException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,6 +36,8 @@ * @since JDK1.0 */ public class MalformedURLException extends IOException { + private static final long serialVersionUID = -182787522200415866L; + /** * Constructs a MalformedURLException with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/net/NoRouteToHostException.java --- a/jdk/src/share/classes/java/net/NoRouteToHostException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/net/NoRouteToHostException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1996-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,8 @@ * @since JDK1.1 */ public class NoRouteToHostException extends SocketException { + private static final long serialVersionUID = -1897550894873493790L; + /** * Constructs a new NoRouteToHostException with the specified detail * message as to why the remote host cannot be reached. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/net/PortUnreachableException.java --- a/jdk/src/share/classes/java/net/PortUnreachableException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/net/PortUnreachableException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2001-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,7 @@ */ public class PortUnreachableException extends SocketException { + private static final long serialVersionUID = 8462541992376507323L; /** * Constructs a new PortUnreachableException with a diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/net/ProtocolException.java --- a/jdk/src/share/classes/java/net/ProtocolException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/net/ProtocolException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,6 +36,8 @@ */ public class ProtocolException extends IOException { + private static final long serialVersionUID = -6098449442062388080L; + /** * Constructs a new ProtocolException with the * specified detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/net/SocketException.java --- a/jdk/src/share/classes/java/net/SocketException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/net/SocketException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,8 @@ */ public class SocketException extends IOException { + private static final long serialVersionUID = -5935874303556886934L; + /** * Constructs a new SocketException with the * specified detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/net/SocketTimeoutException.java --- a/jdk/src/share/classes/java/net/SocketTimeoutException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/net/SocketTimeoutException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,7 @@ */ public class SocketTimeoutException extends java.io.InterruptedIOException { + private static final long serialVersionUID = -8846654841826352300L; /** * Constructs a new SocketTimeoutException with a detail diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/net/URISyntaxException.java --- a/jdk/src/share/classes/java/net/URISyntaxException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/net/URISyntaxException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,6 +38,8 @@ public class URISyntaxException extends Exception { + private static final long serialVersionUID = 2137979680897488891L; + private String input; private int index; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/net/UnknownHostException.java --- a/jdk/src/share/classes/java/net/UnknownHostException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/net/UnknownHostException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,8 @@ */ public class UnknownHostException extends IOException { + private static final long serialVersionUID = -4639126076052875403L; + /** * Constructs a new UnknownHostException with the * specified detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/net/UnknownServiceException.java --- a/jdk/src/share/classes/java/net/UnknownServiceException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/net/UnknownServiceException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-1997 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,8 @@ * @since JDK1.0 */ public class UnknownServiceException extends IOException { + private static final long serialVersionUID = -4169033248853639508L; + /** * Constructs a new UnknownServiceException with no * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/text/SimpleDateFormat.java --- a/jdk/src/share/classes/java/text/SimpleDateFormat.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/text/SimpleDateFormat.java Wed Jul 05 16:42:37 2017 +0200 @@ -374,6 +374,24 @@ private String pattern; /** + * Saved numberFormat and pattern. + * @see SimpleDateFormat#checkNegativeNumberExpression + */ + transient private NumberFormat originalNumberFormat; + transient private String originalNumberPattern; + + /** + * The minus sign to be used with format and parse. + */ + transient private char minusSign = '-'; + + /** + * True when a negative sign follows a number. + * (True as default in Arabic.) + */ + transient private boolean hasFollowingMinusSign = false; + + /** * The compiled pattern. */ transient private char[] compiledPattern; @@ -1226,6 +1244,8 @@ */ public Date parse(String text, ParsePosition pos) { + checkNegativeNumberExpression(); + int start = pos.index; int oldStart = start; int textLength = text.length(); @@ -1271,14 +1291,42 @@ // digit text (e.g., "20010704") with a pattern which // has no delimiters between fields, like "yyyyMMdd". boolean obeyCount = false; + + // In Arabic, a minus sign for a negative number is put after + // the number. Even in another locale, a minus sign can be + // put after a number using DateFormat.setNumberFormat(). + // If both the minus sign and the field-delimiter are '-', + // subParse() needs to determine whether a '-' after a number + // in the given text is a delimiter or is a minus sign for the + // preceding number. We give subParse() a clue based on the + // information in compiledPattern. + boolean useFollowingMinusSignAsDelimiter = false; + if (i < compiledPattern.length) { int nextTag = compiledPattern[i] >>> 8; - if (!(nextTag == TAG_QUOTE_ASCII_CHAR || nextTag == TAG_QUOTE_CHARS)) { + if (!(nextTag == TAG_QUOTE_ASCII_CHAR || + nextTag == TAG_QUOTE_CHARS)) { obeyCount = true; } + + if (hasFollowingMinusSign && + (nextTag == TAG_QUOTE_ASCII_CHAR || + nextTag == TAG_QUOTE_CHARS)) { + int c; + if (nextTag == TAG_QUOTE_ASCII_CHAR) { + c = compiledPattern[i] & 0xff; + } else { + c = compiledPattern[i+1]; + } + + if (c == minusSign) { + useFollowingMinusSignAsDelimiter = true; + } + } } start = subParse(text, start, tag, count, obeyCount, - ambiguousYear, pos); + ambiguousYear, pos, + useFollowingMinusSignAsDelimiter); if (start < 0) { pos.index = oldStart; return null; @@ -1482,10 +1530,13 @@ // If the time zone matched uses the same name // (abbreviation) for both standard and daylight time, // let the time zone in the Calendar decide which one. - if (!useSameName) { + // + // Also if tz.getDSTSaving() returns 0 for DST, use tz to + // determine the local time. (6645292) + int dstAmount = (nameIndex >= 3) ? tz.getDSTSavings() : 0; + if (!(useSameName || (nameIndex >= 3 && dstAmount == 0))) { calendar.set(Calendar.ZONE_OFFSET, tz.getRawOffset()); - calendar.set(Calendar.DST_OFFSET, - nameIndex >= 3 ? tz.getDSTSavings() : 0); + calendar.set(Calendar.DST_OFFSET, dstAmount); } return (start + zoneNames[nameIndex].length()); } @@ -1511,8 +1562,8 @@ */ private int subParse(String text, int start, int patternCharIndex, int count, boolean obeyCount, boolean[] ambiguousYear, - ParsePosition origPos) - { + ParsePosition origPos, + boolean useFollowingMinusSignAsDelimiter) { Number number = null; int value = 0; ParsePosition pos = new ParsePosition(0); @@ -1537,10 +1588,10 @@ // a number value. We handle further, more generic cases below. We need // to handle some of them here because some fields require extra processing on // the parsed value. - if (patternCharIndex == 4 /*HOUR_OF_DAY1_FIELD*/ || - patternCharIndex == 15 /*HOUR1_FIELD*/ || - (patternCharIndex == 2 /*MONTH_FIELD*/ && count <= 2) || - patternCharIndex == 1) { + if (patternCharIndex == 4 /* HOUR_OF_DAY1_FIELD */ || + patternCharIndex == 15 /* HOUR1_FIELD */ || + (patternCharIndex == 2 /* MONTH_FIELD */ && count <= 2) || + patternCharIndex == 1 /* YEAR_FIELD */) { // It would be good to unify this with the obeyCount logic below, // but that's going to be difficult. if (obeyCount) { @@ -1557,6 +1608,15 @@ } } else { value = number.intValue(); + + if (useFollowingMinusSignAsDelimiter && (value < 0) && + (((pos.index < text.length()) && + (text.charAt(pos.index) != minusSign)) || + ((pos.index == text.length()) && + (text.charAt(pos.index-1) == minusSign)))) { + value = -value; + pos.index--; + } } } @@ -1888,7 +1948,18 @@ number = numberFormat.parse(text, pos); } if (number != null) { - calendar.set(field, number.intValue()); + value = number.intValue(); + + if (useFollowingMinusSignAsDelimiter && (value < 0) && + (((pos.index < text.length()) && + (text.charAt(pos.index) != minusSign)) || + ((pos.index == text.length()) && + (text.charAt(pos.index-1) == minusSign)))) { + value = -value; + pos.index--; + } + + calendar.set(field, value); return pos.index; } break parsing; @@ -2099,4 +2170,33 @@ } } } + + /** + * Analyze the negative subpattern of DecimalFormat and set/update values + * as necessary. + */ + private void checkNegativeNumberExpression() { + if ((numberFormat instanceof DecimalFormat) && + !numberFormat.equals(originalNumberFormat)) { + String numberPattern = ((DecimalFormat)numberFormat).toPattern(); + if (!numberPattern.equals(originalNumberPattern)) { + hasFollowingMinusSign = false; + + int separatorIndex = numberPattern.indexOf(';'); + // If the negative subpattern is not absent, we have to analayze + // it in order to check if it has a following minus sign. + if (separatorIndex > -1) { + int minusIndex = numberPattern.indexOf('-', separatorIndex); + if ((minusIndex > numberPattern.lastIndexOf('0')) && + (minusIndex > numberPattern.lastIndexOf('#'))) { + hasFollowingMinusSign = true; + minusSign = ((DecimalFormat)numberFormat).getDecimalFormatSymbols().getMinusSign(); + } + } + originalNumberPattern = numberPattern; + } + originalNumberFormat = numberFormat; + } + } + } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/util/ConcurrentModificationException.java --- a/jdk/src/share/classes/java/util/ConcurrentModificationException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/util/ConcurrentModificationException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -67,6 +67,8 @@ * @since 1.2 */ public class ConcurrentModificationException extends RuntimeException { + private static final long serialVersionUID = -3666751008965953603L; + /** * Constructs a ConcurrentModificationException with no * detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/util/EmptyStackException.java --- a/jdk/src/share/classes/java/util/EmptyStackException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/util/EmptyStackException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1998 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,8 @@ */ public class EmptyStackException extends RuntimeException { + private static final long serialVersionUID = 5084686378493302095L; + /** * Constructs a new EmptyStackException with null * as its error message string. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/util/InputMismatchException.java --- a/jdk/src/share/classes/java/util/InputMismatchException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/util/InputMismatchException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,6 +36,8 @@ */ public class InputMismatchException extends NoSuchElementException { + private static final long serialVersionUID = 8811230760997066428L; + /** * Constructs an InputMismatchException with null * as its error message string. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/util/NoSuchElementException.java --- a/jdk/src/share/classes/java/util/NoSuchElementException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/util/NoSuchElementException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1994-1998 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1994-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,8 @@ */ public class NoSuchElementException extends RuntimeException { + private static final long serialVersionUID = 6769829250639411880L; + /** * Constructs a NoSuchElementException with null * as its error message string. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/util/TooManyListenersException.java --- a/jdk/src/share/classes/java/util/TooManyListenersException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/util/TooManyListenersException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1996-1999 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -48,6 +48,7 @@ */ public class TooManyListenersException extends Exception { + private static final long serialVersionUID = 5074640544770687831L; /** * Constructs a TooManyListenersException with no detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/util/jar/JarException.java --- a/jdk/src/share/classes/java/util/jar/JarException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/util/jar/JarException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1997-1999 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,8 @@ */ public class JarException extends java.util.zip.ZipException { + private static final long serialVersionUID = 7159778400963954473L; + /** * Constructs a JarException with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/util/regex/PatternSyntaxException.java --- a/jdk/src/share/classes/java/util/regex/PatternSyntaxException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/util/regex/PatternSyntaxException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1999-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1999-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,6 +40,7 @@ public class PatternSyntaxException extends IllegalArgumentException { + private static final long serialVersionUID = -3864639126226059218L; private final String desc; private final String pattern; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/util/zip/DataFormatException.java --- a/jdk/src/share/classes/java/util/zip/DataFormatException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/util/zip/DataFormatException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1996 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,8 @@ */ public class DataFormatException extends Exception { + private static final long serialVersionUID = 2219632870893641452L; + /** * Constructs a DataFormatException with no detail message. */ diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/java/util/zip/ZipException.java --- a/jdk/src/share/classes/java/util/zip/ZipException.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/java/util/zip/ZipException.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1995-2001 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,8 @@ public class ZipException extends IOException { + private static final long serialVersionUID = 8000196834066748623L; + /** * Constructs an ZipException with null * as its error detail message. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/management/openmbean/MXBeanMappingFactory.java --- a/jdk/src/share/classes/javax/management/openmbean/MXBeanMappingFactory.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/management/openmbean/MXBeanMappingFactory.java Wed Jul 05 16:42:37 2017 +0200 @@ -48,7 +48,7 @@ * effect by defining {@code MyLinkedListMappingFactory} as follows:

* *
- * public class MyLinkedListMappingFactory implements MXBeanMappingFactory {
+ * public class MyLinkedListMappingFactory extends MXBeanMappingFactory {
  *     public MyLinkedListMappingFactory() {}
  *
  *     public MXBeanMapping mappingForType(Type t, MXBeanMappingFactory f)
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/AbstractButton.java
--- a/jdk/src/share/classes/javax/swing/AbstractButton.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/AbstractButton.java	Wed Jul 05 16:42:37 2017 +0200
@@ -1315,8 +1315,7 @@
             // Make sure the change actually took effect
             if (!selected && isSelected()) {
                 if (getModel() instanceof DefaultButtonModel) {
-                    ButtonGroup group = (ButtonGroup)
-                            ((DefaultButtonModel)getModel()).getGroup();
+                    ButtonGroup group = ((DefaultButtonModel)getModel()).getGroup();
                     if (group != null) {
                         group.clearSelection();
                     }
@@ -1886,8 +1885,7 @@
      * @since 1.4
      */
     public ChangeListener[] getChangeListeners() {
-        return (ChangeListener[])(listenerList.getListeners(
-            ChangeListener.class));
+        return listenerList.getListeners(ChangeListener.class);
     }
 
     /**
@@ -1944,8 +1942,7 @@
      * @since 1.4
      */
     public ActionListener[] getActionListeners() {
-        return (ActionListener[])(listenerList.getListeners(
-            ActionListener.class));
+        return listenerList.getListeners(ActionListener.class);
     }
 
     /**
@@ -2137,7 +2134,7 @@
      * @since 1.4
      */
     public ItemListener[] getItemListeners() {
-        return (ItemListener[])listenerList.getListeners(ItemListener.class);
+        return listenerList.getListeners(ItemListener.class);
     }
 
    /**
@@ -2981,7 +2978,7 @@
             paintViewR.height = AbstractButton.this.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);
 
             String clippedText = SwingUtilities.layoutCompoundLabel(
-                (JComponent)AbstractButton.this,
+                AbstractButton.this,
                 getFontMetrics(getFont()),
                 text,
                 icon,
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/AbstractCellEditor.java
--- a/jdk/src/share/classes/javax/swing/AbstractCellEditor.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/AbstractCellEditor.java	Wed Jul 05 16:42:37 2017 +0200
@@ -118,8 +118,7 @@
      * @since 1.4
      */
     public CellEditorListener[] getCellEditorListeners() {
-        return (CellEditorListener[])listenerList.getListeners(
-                CellEditorListener.class);
+        return listenerList.getListeners(CellEditorListener.class);
     }
 
     /**
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/AbstractListModel.java
--- a/jdk/src/share/classes/javax/swing/AbstractListModel.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/AbstractListModel.java	Wed Jul 05 16:42:37 2017 +0200
@@ -85,8 +85,7 @@
      * @since 1.4
      */
     public ListDataListener[] getListDataListeners() {
-        return (ListDataListener[])listenerList.getListeners(
-                ListDataListener.class);
+        return listenerList.getListeners(ListDataListener.class);
     }
 
 
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/AbstractSpinnerModel.java
--- a/jdk/src/share/classes/javax/swing/AbstractSpinnerModel.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/AbstractSpinnerModel.java	Wed Jul 05 16:42:37 2017 +0200
@@ -98,8 +98,7 @@
      * @since 1.4
      */
     public ChangeListener[] getChangeListeners() {
-        return (ChangeListener[])listenerList.getListeners(
-                ChangeListener.class);
+        return listenerList.getListeners(ChangeListener.class);
     }
 
 
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/ActionMap.java
--- a/jdk/src/share/classes/javax/swing/ActionMap.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/ActionMap.java	Wed Jul 05 16:42:37 2017 +0200
@@ -197,7 +197,7 @@
             return pKeys;
         }
 
-        HashMap        keyMap = new HashMap();
+        HashMap keyMap = new HashMap();
         int            counter;
 
         for (counter = keys.length - 1; counter >= 0; counter--) {
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/AncestorNotifier.java
--- a/jdk/src/share/classes/javax/swing/AncestorNotifier.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/AncestorNotifier.java	Wed Jul 05 16:42:37 2017 +0200
@@ -62,7 +62,7 @@
     }
 
     AncestorListener[] getAncestorListeners() {
-        return (AncestorListener[])listenerList.getListeners(AncestorListener.class);
+        return listenerList.getListeners(AncestorListener.class);
     }
 
     /**
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/ArrayTable.java
--- a/jdk/src/share/classes/javax/swing/ArrayTable.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/ArrayTable.java	Wed Jul 05 16:42:37 2017 +0200
@@ -88,10 +88,10 @@
             // Write ou the Serializable key/value pairs.
             s.writeInt(validCount);
             if (validCount > 0) {
-                for (int counter = 0; counter < keys.length; counter++) {
-                    if (keys[counter] != null) {
-                        s.writeObject(keys[counter]);
-                        s.writeObject(table.get(keys[counter]));
+                for (Object key : keys) {
+                    if (key != null) {
+                        s.writeObject(key);
+                        s.writeObject(table.get(key));
                         if (--validCount == 0) {
                             break;
                         }
@@ -315,7 +315,7 @@
      */
     private void grow() {
         Object[] array = (Object[])table;
-        Hashtable tmp = new Hashtable(array.length/2);
+        Hashtable tmp = new Hashtable(array.length/2);
         for (int i = 0; i buttons = new Vector();
+    protected Vector buttons = new Vector();
 
     /**
      * The current selection.
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/DebugGraphicsInfo.java
--- a/jdk/src/share/classes/javax/swing/DebugGraphicsInfo.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/DebugGraphicsInfo.java	Wed Jul 05 16:42:37 2017 +0200
@@ -37,7 +37,7 @@
     Color                flashColor = Color.red;
     int                  flashTime = 100;
     int                  flashCount = 2;
-    Hashtable            componentToDebug;
+    Hashtable componentToDebug;
     JFrame               debugFrame = null;
     java.io.PrintStream  stream = System.out;
 
@@ -46,7 +46,7 @@
             return;
         }
         if (componentToDebug == null) {
-            componentToDebug = new Hashtable();
+            componentToDebug = new Hashtable();
         }
         if (debug > 0) {
             componentToDebug.put(component, Integer.valueOf(debug));
@@ -59,7 +59,7 @@
         if (componentToDebug == null) {
             return 0;
         } else {
-            Integer integer = (Integer)componentToDebug.get(component);
+            Integer integer = componentToDebug.get(component);
 
             return integer == null ? 0 : integer.intValue();
         }
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/DefaultBoundedRangeModel.java
--- a/jdk/src/share/classes/javax/swing/DefaultBoundedRangeModel.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/DefaultBoundedRangeModel.java	Wed Jul 05 16:42:37 2017 +0200
@@ -343,8 +343,7 @@
      * @since 1.4
      */
     public ChangeListener[] getChangeListeners() {
-        return (ChangeListener[])listenerList.getListeners(
-                ChangeListener.class);
+        return listenerList.getListeners(ChangeListener.class);
     }
 
 
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/DefaultButtonModel.java
--- a/jdk/src/share/classes/javax/swing/DefaultButtonModel.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/DefaultButtonModel.java	Wed Jul 05 16:42:37 2017 +0200
@@ -326,8 +326,7 @@
      * @since 1.4
      */
     public ChangeListener[] getChangeListeners() {
-        return (ChangeListener[])listenerList.getListeners(
-                ChangeListener.class);
+        return listenerList.getListeners(ChangeListener.class);
     }
 
     /**
@@ -380,8 +379,7 @@
      * @since 1.4
      */
     public ActionListener[] getActionListeners() {
-        return (ActionListener[])listenerList.getListeners(
-                ActionListener.class);
+        return listenerList.getListeners(ActionListener.class);
     }
 
     /**
@@ -434,7 +432,7 @@
      * @since 1.4
      */
     public ItemListener[] getItemListeners() {
-        return (ItemListener[])listenerList.getListeners(ItemListener.class);
+        return listenerList.getListeners(ItemListener.class);
     }
 
     /**
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/DefaultFocusManager.java
--- a/jdk/src/share/classes/javax/swing/DefaultFocusManager.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/DefaultFocusManager.java	Wed Jul 05 16:42:37 2017 +0200
@@ -156,18 +156,17 @@
     }
 }
 
-final class CompareTabOrderComparator implements Comparator {
+final class CompareTabOrderComparator implements Comparator {
     private final DefaultFocusManager defaultFocusManager;
 
     CompareTabOrderComparator(DefaultFocusManager defaultFocusManager) {
         this.defaultFocusManager = defaultFocusManager;
     }
 
-    public int compare(Object o1, Object o2) {
+    public int compare(Component o1, Component o2) {
         if (o1 == o2) {
             return 0;
         }
-        return (defaultFocusManager.compareTabOrder((Component)o1,
-                                                    (Component)o2)) ? -1 : 1;
+        return (defaultFocusManager.compareTabOrder(o1, o2)) ? -1 : 1;
     }
 }
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java
--- a/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java	Wed Jul 05 16:42:37 2017 +0200
@@ -133,8 +133,7 @@
      * @since 1.4
      */
     public ListSelectionListener[] getListSelectionListeners() {
-        return (ListSelectionListener[])listenerList.getListeners(
-                ListSelectionListener.class);
+        return listenerList.getListeners(ListSelectionListener.class);
     }
 
     /**
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/DefaultSingleSelectionModel.java
--- a/jdk/src/share/classes/javax/swing/DefaultSingleSelectionModel.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/DefaultSingleSelectionModel.java	Wed Jul 05 16:42:37 2017 +0200
@@ -110,8 +110,7 @@
      * @since 1.4
      */
     public ChangeListener[] getChangeListeners() {
-        return (ChangeListener[])listenerList.getListeners(
-                ChangeListener.class);
+        return listenerList.getListeners(ChangeListener.class);
     }
 
     /**
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/GroupLayout.java
--- a/jdk/src/share/classes/javax/swing/GroupLayout.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/GroupLayout.java	Wed Jul 05 16:42:37 2017 +0200
@@ -1119,7 +1119,7 @@
      * creating one if necessary.
      */
     private ComponentInfo getComponentInfo(Component component) {
-        ComponentInfo info = (ComponentInfo)componentInfos.get(component);
+        ComponentInfo info = componentInfos.get(component);
         if (info == null) {
             info = new ComponentInfo(component);
             componentInfos.put(component, info);
@@ -1698,7 +1698,7 @@
             for (int counter = springs.size() - 1; counter >= 0; counter--) {
                 Spring spring = springs.get(counter);
                 if (spring instanceof AutoPreferredGapSpring) {
-                    ((AutoPreferredGapSpring)spring).unset();
+                    spring.unset();
                 } else if (spring instanceof Group) {
                     ((Group)spring).unsetAutopadding();
                 }
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/InputMap.java
--- a/jdk/src/share/classes/javax/swing/InputMap.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/InputMap.java	Wed Jul 05 16:42:37 2017 +0200
@@ -200,7 +200,7 @@
             return pKeys;
         }
 
-        HashMap        keyMap = new HashMap();
+        HashMap keyMap = new HashMap();
         int            counter;
 
         for (counter = keys.length - 1; counter >= 0; counter--) {
@@ -212,7 +212,7 @@
 
         KeyStroke[]    allKeys = new KeyStroke[keyMap.size()];
 
-        return (KeyStroke[])keyMap.keySet().toArray(allKeys);
+        return keyMap.keySet().toArray(allKeys);
     }
 
     private void writeObject(ObjectOutputStream s) throws IOException {
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JApplet.java
--- a/jdk/src/share/classes/javax/swing/JApplet.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JApplet.java	Wed Jul 05 16:42:37 2017 +0200
@@ -131,10 +131,7 @@
         // Check the timerQ and restart if necessary.
         TimerQueue q = TimerQueue.sharedInstance();
         if(q != null) {
-            synchronized(q) {
-                if(!q.running)
-                    q.start();
-            }
+            q.startIfNeeded();
         }
 
         /* Workaround for bug 4155072.  The shared double buffer image
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JComboBox.java
--- a/jdk/src/share/classes/javax/swing/JComboBox.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JComboBox.java	Wed Jul 05 16:42:37 2017 +0200
@@ -859,7 +859,7 @@
      * @since 1.4
      */
     public ItemListener[] getItemListeners() {
-        return (ItemListener[])listenerList.getListeners(ItemListener.class);
+        return listenerList.getListeners(ItemListener.class);
     }
 
     /**
@@ -897,8 +897,7 @@
      * @since 1.4
      */
     public ActionListener[] getActionListeners() {
-        return (ActionListener[])listenerList.getListeners(
-                ActionListener.class);
+        return listenerList.getListeners(ActionListener.class);
     }
 
     /**
@@ -937,8 +936,7 @@
      * @since 1.4
      */
     public PopupMenuListener[] getPopupMenuListeners() {
-        return (PopupMenuListener[])listenerList.getListeners(
-                PopupMenuListener.class);
+        return listenerList.getListeners(PopupMenuListener.class);
     }
 
     /**
@@ -1668,7 +1666,7 @@
             if (editor != null) {
                 Component comp = editor.getEditorComponent();
                 if (comp instanceof Accessible) {
-                    AccessibleContext ac = ((Accessible)comp).getAccessibleContext();
+                    AccessibleContext ac = comp.getAccessibleContext();
                     if (ac != null) { // may be null
                         ac.setAccessibleName(getAccessibleName());
                         ac.setAccessibleDescription(getAccessibleDescription());
@@ -1741,7 +1739,7 @@
 
                 // Fire a FOCUSED lost PropertyChangeEvent for the
                 // previously selected list item.
-                PropertyChangeEvent pce = null;
+                PropertyChangeEvent pce;
 
                 if (previousSelectedAccessible != null) {
                     pce = new PropertyChangeEvent(previousSelectedAccessible,
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JComponent.java
--- a/jdk/src/share/classes/javax/swing/JComponent.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JComponent.java	Wed Jul 05 16:42:37 2017 +0200
@@ -192,7 +192,8 @@
     /**
      * @see #readObject
      */
-    private static final Hashtable readObjectCallbacks = new Hashtable(1);
+    private static final Hashtable readObjectCallbacks =
+            new Hashtable(1);
 
     /**
      * Keys to use for forward focus traversal when the JComponent is
@@ -356,7 +357,7 @@
     /**
      * Temporary rectangles.
      */
-    private static java.util.List tempRectangles = new java.util.ArrayList(11);
+    private static java.util.List tempRectangles = new java.util.ArrayList(11);
 
     /** Used for WHEN_FOCUSED bindings. */
     private InputMap focusInputMap;
@@ -451,7 +452,7 @@
             Rectangle rect;
             int size = tempRectangles.size();
             if (size > 0) {
-                rect = (Rectangle)tempRectangles.remove(size - 1);
+                rect = tempRectangles.remove(size - 1);
             }
             else {
                 rect = new Rectangle(0, 0, 0, 0);
@@ -806,7 +807,7 @@
             // its index.
             if (paintingChild != null &&
                 (paintingChild instanceof JComponent) &&
-                ((JComponent)paintingChild).isOpaque()) {
+                paintingChild.isOpaque()) {
                 for (; i >= 0; i--) {
                     if (getComponent(i) == paintingChild){
                         break;
@@ -875,7 +876,7 @@
                                     shouldSetFlagBack = true;
                                 }
                                 if(!printing) {
-                                    ((JComponent)comp).paint(cg);
+                                    comp.paint(cg);
                                 }
                                 else {
                                     if (!getFlag(IS_PRINTING_ALL)) {
@@ -1098,7 +1099,7 @@
     }
 
     private void adjustPaintFlags() {
-        JComponent jparent = null;
+        JComponent jparent;
         Container parent;
         for(parent = getParent() ; parent != null ; parent =
             parent.getParent()) {
@@ -2096,7 +2097,7 @@
     private void registerWithKeyboardManager(boolean onlyIfNew) {
         InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW, false);
         KeyStroke[] strokes;
-        Hashtable registered = (Hashtable)getClientProperty
+        Hashtable registered = (Hashtable)getClientProperty
                                 (WHEN_IN_FOCUSED_WINDOW_BINDINGS);
 
         if (inputMap != null) {
@@ -2120,10 +2121,10 @@
         }
         // Remove any old ones.
         if (registered != null && registered.size() > 0) {
-            Enumeration keys = registered.keys();
+            Enumeration keys = registered.keys();
 
             while (keys.hasMoreElements()) {
-                KeyStroke ks = (KeyStroke)keys.nextElement();
+                KeyStroke ks = keys.nextElement();
                 unregisterWithKeyboardManager(ks);
             }
             registered.clear();
@@ -2131,7 +2132,7 @@
         // Updated the registered Hashtable.
         if (strokes != null && strokes.length > 0) {
             if (registered == null) {
-                registered = new Hashtable(strokes.length);
+                registered = new Hashtable(strokes.length);
                 putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, registered);
             }
             for (int counter = strokes.length - 1; counter >= 0; counter--) {
@@ -2174,7 +2175,7 @@
         InputMap km = getInputMap(WHEN_IN_FOCUSED_WINDOW, false);
 
         while (km != inputMap && km != null) {
-            km = (ComponentInputMap)km.getParent();
+            km = km.getParent();
         }
         if (km != null) {
             registerWithKeyboardManager(false);
@@ -3673,7 +3674,7 @@
                 if (c != null && c instanceof Accessible) {
                     AccessibleJComponent.this.firePropertyChange(
                         AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
-                        null, ((Accessible) c).getAccessibleContext());
+                        null, c.getAccessibleContext());
                 }
             }
             public void componentRemoved(ContainerEvent e) {
@@ -3681,7 +3682,7 @@
                 if (c != null && c instanceof Accessible) {
                     AccessibleJComponent.this.firePropertyChange(
                         AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
-                        ((Accessible) c).getAccessibleContext(), null);
+                        c.getAccessibleContext(), null);
                 }
             }
         }
@@ -4377,7 +4378,7 @@
 //                  System.out.println("A) checking opaque: " + ((JComponent)child).isOpaque() + "  " + child);
 //                  System.out.print("B) ");
 //                  Thread.dumpStack();
-                    return ((JComponent)child).isOpaque();
+                    return child.isOpaque();
                 } else {
                     /** Sometimes a heavy weight can have a bound larger than its peer size
                      *  so we should always draw under heavy weights
@@ -4693,7 +4694,7 @@
             result = (T[])getPropertyChangeListeners();
         }
         else {
-            result = (T[])listenerList.getListeners(listenerType);
+            result = listenerList.getListeners(listenerType);
         }
 
         if (result.length == 0) {
@@ -4904,7 +4905,7 @@
         if(!isShowing()) {
             return;
         }
-        while(!((JComponent)c).isOpaque()) {
+        while(!c.isOpaque()) {
             parent = c.getParent();
             if(parent != null) {
                 x += c.getX();
@@ -5198,7 +5199,7 @@
             Rectangle siblingRect;
             boolean opaque;
             if (sibling instanceof JComponent) {
-                opaque = ((JComponent)sibling).isOpaque();
+                opaque = sibling.isOpaque();
                 if (!opaque) {
                     if (retValue == PARTIALLY_OBSCURED) {
                         continue;
@@ -5345,7 +5346,7 @@
      */
     private class ReadObjectCallback implements ObjectInputValidation
     {
-        private final Vector roots = new Vector(1);
+        private final Vector roots = new Vector(1);
         private final ObjectInputStream inputStream;
 
         ReadObjectCallback(ObjectInputStream s) throws Exception {
@@ -5361,8 +5362,7 @@
          */
         public void validateObject() throws InvalidObjectException {
             try {
-                for(int i = 0; i < roots.size(); i++) {
-                    JComponent root = (JComponent)(roots.elementAt(i));
+                for (JComponent root : roots) {
                     SwingUtilities.updateComponentTreeUI(root);
                 }
             }
@@ -5382,8 +5382,7 @@
             /* If the Component c is a descendant of one of the
              * existing roots (or it IS an existing root), we're done.
              */
-            for(int i = 0; i < roots.size(); i++) {
-                JComponent root = (JComponent)roots.elementAt(i);
+            for (JComponent root : roots) {
                 for(Component p = c; p != null; p = p.getParent()) {
                     if (p == root) {
                         return;
@@ -5396,7 +5395,7 @@
              * to the roots vector.
              */
             for(int i = 0; i < roots.size(); i++) {
-                JComponent root = (JComponent)roots.elementAt(i);
+                JComponent root = roots.elementAt(i);
                 for(Component p = root.getParent(); p != null; p = p.getParent()) {
                     if (p == c) {
                         roots.removeElementAt(i--); // !!
@@ -5428,7 +5427,7 @@
          * in the readObjectCallbacks table.  Note that the ReadObjectCallback
          * constructor takes care of calling s.registerValidation().
          */
-        ReadObjectCallback cb = (ReadObjectCallback)(readObjectCallbacks.get(s));
+        ReadObjectCallback cb = readObjectCallbacks.get(s);
         if (cb == null) {
             try {
                 readObjectCallbacks.put(s, cb = new ReadObjectCallback(s));
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JDesktopPane.java
--- a/jdk/src/share/classes/javax/swing/JDesktopPane.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JDesktopPane.java	Wed Jul 05 16:42:37 2017 +0200
@@ -133,8 +133,8 @@
             public Component getDefaultComponent(Container c) {
                 JInternalFrame jifArray[] = getAllFrames();
                 Component comp = null;
-                for (int i = 0; i < jifArray.length; i++) {
-                    comp = jifArray[i].getFocusTraversalPolicy().getDefaultComponent(jifArray[i]);
+                for (JInternalFrame jif : jifArray) {
+                    comp = jif.getFocusTraversalPolicy().getDefaultComponent(jif);
                     if (comp != null) {
                         break;
                     }
@@ -262,16 +262,15 @@
     public JInternalFrame[] getAllFrames() {
         int i, count;
         JInternalFrame[] results;
-        Vector vResults = new Vector(10);
-        Object next, tmp;
+        Vector vResults = new Vector(10);
 
         count = getComponentCount();
         for(i = 0; i < count; i++) {
-            next = getComponent(i);
+            Component next = getComponent(i);
             if(next instanceof JInternalFrame)
-                vResults.addElement(next);
+                vResults.addElement((JInternalFrame) next);
             else if(next instanceof JInternalFrame.JDesktopIcon)  {
-                tmp = ((JInternalFrame.JDesktopIcon)next).getInternalFrame();
+                JInternalFrame tmp = ((JInternalFrame.JDesktopIcon)next).getInternalFrame();
                 if(tmp != null)
                     vResults.addElement(tmp);
             }
@@ -324,18 +323,17 @@
     public JInternalFrame[] getAllFramesInLayer(int layer) {
         int i, count;
         JInternalFrame[] results;
-        Vector vResults = new Vector(10);
-        Object next, tmp;
+        Vector vResults = new Vector(10);
 
         count = getComponentCount();
         for(i = 0; i < count; i++) {
-            next = getComponent(i);
+            Component next = getComponent(i);
             if(next instanceof JInternalFrame) {
                 if(((JInternalFrame)next).getLayer() == layer)
-                    vResults.addElement(next);
+                    vResults.addElement((JInternalFrame) next);
             } else if(next instanceof JInternalFrame.JDesktopIcon)  {
-                tmp = ((JInternalFrame.JDesktopIcon)next).getInternalFrame();
-                if(tmp != null && ((JInternalFrame)tmp).getLayer() == layer)
+                JInternalFrame tmp = ((JInternalFrame.JDesktopIcon)next).getInternalFrame();
+                if(tmp != null && tmp.getLayer() == layer)
                     vResults.addElement(tmp);
             }
         }
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JDialog.java
--- a/jdk/src/share/classes/javax/swing/JDialog.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JDialog.java	Wed Jul 05 16:42:37 2017 +0200
@@ -277,7 +277,7 @@
               title, modal);
         if (owner == null) {
             WindowListener ownerShutdownListener =
-                (WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener();
+                    SwingUtilities.getSharedOwnerFrameShutdownListener();
             addWindowListener(ownerShutdownListener);
         }
         dialogInit();
@@ -329,7 +329,7 @@
               title, modal, gc);
         if (owner == null) {
             WindowListener ownerShutdownListener =
-                (WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener();
+                    SwingUtilities.getSharedOwnerFrameShutdownListener();
             addWindowListener(ownerShutdownListener);
         }
         dialogInit();
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JEditorPane.java
--- a/jdk/src/share/classes/javax/swing/JEditorPane.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JEditorPane.java	Wed Jul 05 16:42:37 2017 +0200
@@ -319,8 +319,7 @@
      * @since 1.4
      */
     public synchronized HyperlinkListener[] getHyperlinkListeners() {
-        return (HyperlinkListener[])listenerList.getListeners(
-                HyperlinkListener.class);
+        return listenerList.getListeners(javax.swing.event.HyperlinkListener.class);
     }
 
     /**
@@ -492,8 +491,8 @@
         if (pageProperties != null) {
             // transfer properties discovered in stream to the
             // document property collection.
-            for (Enumeration e = pageProperties.keys(); e.hasMoreElements() ;) {
-                Object key = e.nextElement();
+            for (Enumeration e = pageProperties.keys(); e.hasMoreElements() ;) {
+                String key = e.nextElement();
                 doc.putProperty(key, pageProperties.get(key));
             }
             pageProperties.clear();
@@ -775,7 +774,7 @@
      */
     private void handleConnectionProperties(URLConnection conn) {
         if (pageProperties == null) {
-            pageProperties = new Hashtable();
+            pageProperties = new Hashtable();
         }
         String type = conn.getContentType();
         if (type != null) {
@@ -989,7 +988,7 @@
      * of the content type in the http header information.
      */
     private void setCharsetFromContentTypeParameters(String paramlist) {
-        String charset = null;
+        String charset;
         try {
             // paramlist is handed to us with a leading ';', strip it.
             int semi = paramlist.indexOf(';');
@@ -1080,9 +1079,9 @@
      */
     public EditorKit getEditorKitForContentType(String type) {
         if (typeHandlers == null) {
-            typeHandlers = new Hashtable(3);
+            typeHandlers = new Hashtable(3);
         }
-        EditorKit k = (EditorKit) typeHandlers.get(type);
+        EditorKit k = typeHandlers.get(type);
         if (k == null) {
             k = createEditorKitForContentType(type);
             if (k != null) {
@@ -1106,7 +1105,7 @@
      */
     public void setEditorKitForContentType(String type, EditorKit k) {
         if (typeHandlers == null) {
-            typeHandlers = new Hashtable(3);
+            typeHandlers = new Hashtable(3);
         }
         typeHandlers.put(type, k);
     }
@@ -1176,13 +1175,12 @@
      *   registered for the given type
      */
     public static EditorKit createEditorKitForContentType(String type) {
-        EditorKit k = null;
-        Hashtable kitRegistry = getKitRegisty();
-        k = (EditorKit) kitRegistry.get(type);
+        Hashtable kitRegistry = getKitRegisty();
+        EditorKit k = kitRegistry.get(type);
         if (k == null) {
             // try to dynamically load the support
-            String classname = (String) getKitTypeRegistry().get(type);
-            ClassLoader loader = (ClassLoader) getKitLoaderRegistry().get(type);
+            String classname = getKitTypeRegistry().get(type);
+            ClassLoader loader = getKitLoaderRegistry().get(type);
             try {
                 Class c;
                 if (loader != null) {
@@ -1252,20 +1250,20 @@
      * @since 1.3
      */
     public static String getEditorKitClassNameForContentType(String type) {
-        return (String)getKitTypeRegistry().get(type);
+        return getKitTypeRegistry().get(type);
     }
 
-    private static Hashtable getKitTypeRegistry() {
+    private static Hashtable getKitTypeRegistry() {
         loadDefaultKitsIfNecessary();
         return (Hashtable)SwingUtilities.appContextGet(kitTypeRegistryKey);
     }
 
-    private static Hashtable getKitLoaderRegistry() {
+    private static Hashtable getKitLoaderRegistry() {
         loadDefaultKitsIfNecessary();
         return (Hashtable)SwingUtilities.appContextGet(kitLoaderRegistryKey);
     }
 
-    private static Hashtable getKitRegisty() {
+    private static Hashtable getKitRegisty() {
         Hashtable ht = (Hashtable)SwingUtilities.appContextGet(kitRegistryKey);
         if (ht == null) {
             ht = new Hashtable(3);
@@ -1512,7 +1510,7 @@
     private EditorKit kit;
     private boolean isUserSetEditorKit;
 
-    private Hashtable pageProperties;
+    private Hashtable pageProperties;
 
     /** Should be kept in sync with javax.swing.text.html.FormView counterpart. */
     final static String PostDataProperty = "javax.swing.JEditorPane.postdata";
@@ -1520,7 +1518,7 @@
     /**
      * Table of registered type handlers for this editor.
      */
-    private Hashtable typeHandlers;
+    private Hashtable typeHandlers;
 
     /*
      * Private AppContext keys for this class's static variables.
@@ -1913,11 +1911,11 @@
             }
         }
 
-        private class LinkVector extends Vector {
+        private class LinkVector extends Vector {
             public int baseElementIndex(Element e) {
                 HTMLLink l;
                 for (int i = 0; i < elementCount; i++) {
-                    l = (HTMLLink) elementAt(i);
+                    l = elementAt(i);
                     if (l.element == e) {
                         return i;
                     }
@@ -2029,7 +2027,7 @@
                 buildLinkTable();
             }
             if (linkIndex >= 0 && linkIndex < hyperlinks.size()) {
-                return (AccessibleHyperlink) hyperlinks.elementAt(linkIndex);
+                return hyperlinks.elementAt(linkIndex);
             } else {
                 return null;
             }
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JFileChooser.java
--- a/jdk/src/share/classes/javax/swing/JFileChooser.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JFileChooser.java	Wed Jul 05 16:42:37 2017 +0200
@@ -248,7 +248,7 @@
     private String approveButtonToolTipText = null;
     private int approveButtonMnemonic = 0;
 
-    private Vector filters = new Vector(5);
+    private Vector filters = new Vector(5);
     private JDialog dialog = null;
     private int dialogType = OPEN_DIALOG;
     private int returnValue = ERROR_OPTION;
@@ -503,7 +503,7 @@
         if(selectedFiles == null) {
             return new File[0];
         } else {
-            return (File[]) selectedFiles.clone();
+            return selectedFiles.clone();
         }
     }
 
@@ -1415,17 +1415,17 @@
         fileFilter = filter;
         if (filter != null) {
             if (isMultiSelectionEnabled() && selectedFiles != null && selectedFiles.length > 0) {
-                Vector fList = new Vector();
+                Vector fList = new Vector();
                 boolean failed = false;
-                for (int i = 0; i < selectedFiles.length; i++) {
-                    if (filter.accept(selectedFiles[i])) {
-                        fList.add(selectedFiles[i]);
+                for (File file : selectedFiles) {
+                    if (filter.accept(file)) {
+                        fList.add(file);
                     } else {
                         failed = true;
                     }
                 }
                 if (failed) {
-                    setSelectedFiles((fList.size() == 0) ? null : (File[])fList.toArray(new File[fList.size()]));
+                    setSelectedFiles((fList.size() == 0) ? null : fList.toArray(new File[fList.size()]));
                 }
             } else if (selectedFile != null && !filter.accept(selectedFile)) {
                 setSelectedFile(null);
@@ -1702,8 +1702,7 @@
      * @since 1.4
      */
     public ActionListener[] getActionListeners() {
-        return (ActionListener[])listenerList.getListeners(
-                ActionListener.class);
+        return listenerList.getListeners(ActionListener.class);
     }
 
     /**
@@ -1744,7 +1743,7 @@
         WeakReference jfcRef;
 
         public WeakPCL(JFileChooser jfc) {
-            jfcRef = new WeakReference(jfc);
+            jfcRef = new WeakReference(jfc);
         }
         public void propertyChange(PropertyChangeEvent ev) {
             assert ev.getPropertyName().equals(SHOW_HIDDEN_PROP);
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JInternalFrame.java
--- a/jdk/src/share/classes/javax/swing/JInternalFrame.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JInternalFrame.java	Wed Jul 05 16:42:37 2017 +0200
@@ -421,8 +421,8 @@
         invalidate();
         Component[] children = getComponents();
         if (children != null) {
-            for(int i = 0; i < children.length; i++) {
-                SwingUtilities.updateComponentTreeUI(children[i]);
+            for (Component child : children) {
+                SwingUtilities.updateComponentTreeUI(child);
             }
         }
     }
@@ -1535,8 +1535,7 @@
      * @see #addInternalFrameListener
      */
     public InternalFrameListener[] getInternalFrameListeners() {
-        return (InternalFrameListener[])listenerList.getListeners(
-                InternalFrameListener.class);
+        return listenerList.getListeners(InternalFrameListener.class);
     }
 
     // remind: name ok? all one method ok? need to be synchronized?
@@ -2258,8 +2257,8 @@
             invalidate();
             Component[] children = getComponents();
             if (children != null) {
-                for(int i = 0; i < children.length; i++) {
-                    SwingUtilities.updateComponentTreeUI(children[i]);
+                for (Component child : children) {
+                    SwingUtilities.updateComponentTreeUI(child);
                 }
             }
         }
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JLayeredPane.java
--- a/jdk/src/share/classes/javax/swing/JLayeredPane.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JLayeredPane.java	Wed Jul 05 16:42:37 2017 +0200
@@ -191,7 +191,7 @@
     private void validateOptimizedDrawing() {
         boolean layeredComponentFound = false;
         synchronized(getTreeLock()) {
-            Integer layer = null;
+            Integer layer;
 
             for (Component c : getComponents()) {
                 layer = null;
@@ -213,7 +213,7 @@
     }
 
     protected void addImpl(Component comp, Object constraints, int index) {
-        int layer = DEFAULT_LAYER.intValue();
+        int layer;
         int pos;
 
         if(constraints instanceof Integer) {
@@ -364,7 +364,7 @@
         if(c instanceof JComponent)
             ((JComponent)c).putClientProperty(LAYER_PROPERTY, layerObj);
         else
-            getComponentToLayer().put((Component)c, layerObj);
+            getComponentToLayer().put(c, layerObj);
 
         if(c.getParent() == null || c.getParent() != this) {
             repaint(c.getBounds());
@@ -388,7 +388,7 @@
         if(c instanceof JComponent)
             i = (Integer)((JComponent)c).getClientProperty(LAYER_PROPERTY);
         else
-            i = (Integer)getComponentToLayer().get((Component)c);
+            i = getComponentToLayer().get(c);
 
         if(i == null)
             return DEFAULT_LAYER.intValue();
@@ -465,9 +465,9 @@
      * @see #getComponentCountInLayer
      */
     public int getPosition(Component c) {
-        int i, count, startLayer, curLayer, startLocation, pos = 0;
+        int i, startLayer, curLayer, startLocation, pos = 0;
 
-        count = getComponentCount();
+        getComponentCount();
         startLocation = getIndexOf(c);
 
         if(startLocation == -1)
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JList.java
--- a/jdk/src/share/classes/javax/swing/JList.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JList.java	Wed Jul 05 16:42:37 2017 +0200
@@ -1848,8 +1848,7 @@
      * @since 1.4
      */
     public ListSelectionListener[] getListSelectionListeners() {
-        return (ListSelectionListener[])listenerList.getListeners(
-                ListSelectionListener.class);
+        return listenerList.getListeners(ListSelectionListener.class);
     }
 
 
@@ -2220,9 +2219,9 @@
         ListSelectionModel sm = getSelectionModel();
         sm.clearSelection();
         int size = getModel().getSize();
-        for(int i = 0; i < indices.length; i++) {
-            if (indices[i] < size) {
-                sm.addSelectionInterval(indices[i], indices[i]);
+        for (int i : indices) {
+            if (i < size) {
+                sm.addSelectionInterval(i, i);
             }
         }
     }
@@ -2724,7 +2723,7 @@
             return true;
         }
         if (getParent() instanceof JViewport) {
-            return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
+            return (getParent().getWidth() > getPreferredSize().width);
         }
         return false;
     }
@@ -2749,7 +2748,7 @@
             return true;
         }
         if (getParent() instanceof JViewport) {
-            return (((JViewport)getParent()).getHeight() > getPreferredSize().height);
+            return (getParent().getHeight() > getPreferredSize().height);
         }
         return false;
     }
@@ -3161,7 +3160,7 @@
             private AccessibleContext getCurrentAccessibleContext() {
                 Component c = getComponentAtIndex(indexInParent);
                 if (c instanceof Accessible) {
-                    return ((Accessible) c).getAccessibleContext();
+                    return c.getAccessibleContext();
                 } else {
                     return null;
                 }
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JMenu.java
--- a/jdk/src/share/classes/javax/swing/JMenu.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JMenu.java	Wed Jul 05 16:42:37 2017 +0200
@@ -371,8 +371,8 @@
      * @since 1.3
      */
     protected Point getPopupMenuOrigin() {
-        int x = 0;
-        int y = 0;
+        int x;
+        int y;
         JPopupMenu pm = getPopupMenu();
         // Figure out the sizes needed to caclulate the menu position
         Dimension s = getSize();
@@ -900,10 +900,8 @@
      *         on another menu
      */
     public boolean isTopLevelMenu() {
-        if (getParent() instanceof JMenuBar)
-            return true;
+        return getParent() instanceof JMenuBar;
 
-        return false;
     }
 
     /**
@@ -1015,7 +1013,7 @@
      * @since 1.4
      */
     public MenuListener[] getMenuListeners() {
-        return (MenuListener[])listenerList.getListeners(MenuListener.class);
+        return listenerList.getListeners(MenuListener.class);
     }
 
     /**
@@ -1305,7 +1303,7 @@
      * @return the array of menu items
      */
     private MenuElement[] buildMenuElementArray(JMenu leaf) {
-        Vector elements = new Vector();
+        Vector elements = new Vector();
         Component current = leaf.getPopupMenu();
         JPopupMenu pop;
         JMenu menu;
@@ -1409,8 +1407,8 @@
         public int getAccessibleChildrenCount() {
             Component[] children = getMenuComponents();
             int count = 0;
-            for (int j = 0; j < children.length; j++) {
-                if (children[j] instanceof Accessible) {
+            for (Component child : children) {
+                if (child instanceof Accessible) {
                     count++;
                 }
             }
@@ -1426,18 +1424,18 @@
         public Accessible getAccessibleChild(int i) {
             Component[] children = getMenuComponents();
             int count = 0;
-            for (int j = 0; j < children.length; j++) {
-                if (children[j] instanceof Accessible) {
+            for (Component child : children) {
+                if (child instanceof Accessible) {
                     if (count == i) {
-                        if (children[j] instanceof JComponent) {
+                        if (child instanceof JComponent) {
                             // FIXME:  [[[WDW - probably should set this when
                             // the component is added to the menu.  I tried
                             // to do this in most cases, but the separators
                             // added by addSeparator are hard to get to.]]]
-                            AccessibleContext ac = ((Accessible) children[j]).getAccessibleContext();
+                            AccessibleContext ac = child.getAccessibleContext();
                             ac.setAccessibleParent(JMenu.this);
                         }
-                        return (Accessible) children[j];
+                        return (Accessible) child;
                     } else {
                         count++;
                     }
@@ -1581,7 +1579,7 @@
             }
             JMenuItem mi = getItem(i);
             if (mi != null && mi instanceof JMenu) {
-                if (((JMenu) mi).isSelected()) {
+                if (mi.isSelected()) {
                     MenuElement old[] =
                         MenuSelectionManager.defaultManager().getSelectedPath();
                     MenuElement me[] = new MenuElement[old.length-2];
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JMenuBar.java
--- a/jdk/src/share/classes/javax/swing/JMenuBar.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JMenuBar.java	Wed Jul 05 16:42:37 2017 +0200
@@ -414,7 +414,7 @@
      */
     public MenuElement[] getSubElements() {
         MenuElement result[];
-        Vector tmp = new Vector();
+        Vector tmp = new Vector();
         int c = getComponentCount();
         int i;
         Component m;
@@ -422,12 +422,12 @@
         for(i=0 ; i < c ; i++) {
             m = getComponent(i);
             if(m instanceof MenuElement)
-                tmp.addElement(m);
+                tmp.addElement((MenuElement) m);
         }
 
         result = new MenuElement[tmp.size()];
         for(i=0,c=tmp.size() ; i < c ; i++)
-            result[i] = (MenuElement) tmp.elementAt(i);
+            result[i] = tmp.elementAt(i);
         return result;
     }
 
@@ -664,9 +664,9 @@
         boolean retValue = super.processKeyBinding(ks, e, condition, pressed);
         if (!retValue) {
             MenuElement[] subElements = getSubElements();
-            for (int i=0; i values = new Vector();
 
         s.defaultWriteObject();
         // Save the icon, if its Serializable.
@@ -2342,7 +2339,7 @@
         }
         // Save the treeModel, if its Serializable.
         if(options != null) {
-            Vector           serOptions = new Vector();
+            Vector serOptions = new Vector();
 
             for(int counter = 0, maxCounter = options.length;
                 counter < maxCounter; counter++)
@@ -2510,16 +2507,16 @@
     /**
      * Retrieves a method from the provided class and makes it accessible.
      */
-    private static class ModalPrivilegedAction implements PrivilegedAction {
-        private Class clazz;
+    private static class ModalPrivilegedAction implements PrivilegedAction {
+        private Class clazz;
         private String methodName;
 
-        public ModalPrivilegedAction(Class clazz, String methodName) {
+        public ModalPrivilegedAction(Class clazz, String methodName) {
             this.clazz = clazz;
             this.methodName = methodName;
         }
 
-        public Object run() {
+        public Method run() {
             Method method = null;
             try {
                 method = clazz.getDeclaredMethod(methodName, (Class[])null);
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JPopupMenu.java
--- a/jdk/src/share/classes/javax/swing/JPopupMenu.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JPopupMenu.java	Wed Jul 05 16:42:37 2017 +0200
@@ -584,7 +584,7 @@
 
         int nitems = getComponentCount();
         // PENDING(ges): Why not use an array?
-        Vector tempItems = new Vector();
+        Vector tempItems = new Vector();
 
         /* Remove the item at index, nitems-index times
            storing them in a temporary vector in the
@@ -600,8 +600,8 @@
         /* Add the removed items back to the menu, they are
            already in the correct order in the temp vector.
            */
-        for (int i = 0; i < tempItems.size()  ; i++) {
-            add((Component)tempItems.elementAt(i));
+        for (Component tempItem : tempItems) {
+            add(tempItem);
         }
     }
 
@@ -632,8 +632,7 @@
      * @since 1.4
      */
     public PopupMenuListener[] getPopupMenuListeners() {
-        return (PopupMenuListener[])listenerList.getListeners(
-                PopupMenuListener.class);
+        return listenerList.getListeners(PopupMenuListener.class);
     }
 
     /**
@@ -665,8 +664,7 @@
      * @since 1.5
      */
     public MenuKeyListener[] getMenuKeyListeners() {
-        return (MenuKeyListener[])listenerList.getListeners(
-                MenuKeyListener.class);
+        return listenerList.getListeners(MenuKeyListener.class);
     }
 
     /**
@@ -781,7 +779,7 @@
             // set selection path before popping up!
             if (isPopupMenu()) {
                 MenuElement me[] = new MenuElement[1];
-                me[0] = (MenuElement) this;
+                me[0] = this;
                 MenuSelectionManager.defaultManager().setSelectedPath(me);
             }
         }
@@ -848,10 +846,7 @@
      * being displayed).
      */
     public boolean isVisible() {
-        if(popup != null)
-            return true;
-        else
-            return false;
+        return popup != null;
     }
 
     /**
@@ -1311,7 +1306,7 @@
 // Serialization support.
 ////////////
     private void writeObject(ObjectOutputStream s) throws IOException {
-        Vector      values = new Vector();
+        Vector values = new Vector();
 
         s.defaultWriteObject();
         // Save the invoker, if its Serializable.
@@ -1494,7 +1489,7 @@
      */
     public MenuElement[] getSubElements() {
         MenuElement result[];
-        Vector tmp = new Vector();
+        Vector tmp = new Vector();
         int c = getComponentCount();
         int i;
         Component m;
@@ -1502,12 +1497,12 @@
         for(i=0 ; i < c ; i++) {
             m = getComponent(i);
             if(m instanceof MenuElement)
-                tmp.addElement(m);
+                tmp.addElement((MenuElement) m);
         }
 
         result = new MenuElement[tmp.size()];
         for(i=0,c=tmp.size() ; i < c ; i++)
-            result[i] = (MenuElement) tmp.elementAt(i);
+            result[i] = tmp.elementAt(i);
         return result;
     }
 
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JProgressBar.java
--- a/jdk/src/share/classes/javax/swing/JProgressBar.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JProgressBar.java	Wed Jul 05 16:42:37 2017 +0200
@@ -699,8 +699,7 @@
      * @since 1.4
      */
     public ChangeListener[] getChangeListeners() {
-        return (ChangeListener[])listenerList.getListeners(
-                ChangeListener.class);
+        return listenerList.getListeners(ChangeListener.class);
     }
 
     /**
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JScrollBar.java
--- a/jdk/src/share/classes/javax/swing/JScrollBar.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JScrollBar.java	Wed Jul 05 16:42:37 2017 +0200
@@ -659,8 +659,7 @@
      * @since 1.4
      */
     public AdjustmentListener[] getAdjustmentListeners() {
-        return (AdjustmentListener[])listenerList.getListeners(
-                AdjustmentListener.class);
+        return listenerList.getListeners(AdjustmentListener.class);
     }
 
 
@@ -754,8 +753,8 @@
     public void setEnabled(boolean x)  {
         super.setEnabled(x);
         Component[] children = getComponents();
-        for(int i = 0; i < children.length; i++) {
-            children[i].setEnabled(x);
+        for (Component child : children) {
+            child.setEnabled(x);
         }
     }
 
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JSlider.java
--- a/jdk/src/share/classes/javax/swing/JSlider.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JSlider.java	Wed Jul 05 16:42:37 2017 +0200
@@ -270,8 +270,7 @@
     {
         checkOrientation(orientation);
         this.orientation = orientation;
-        sliderModel = new DefaultBoundedRangeModel(value, 0, min, max);
-        sliderModel.addChangeListener(changeListener);
+        setModel(new DefaultBoundedRangeModel(value, 0, min, max));
         updateUI();
     }
 
@@ -284,7 +283,6 @@
     {
         this.orientation = JSlider.HORIZONTAL;
         setModel(brm);
-        sliderModel.addChangeListener(changeListener);
         updateUI();
     }
 
@@ -476,15 +474,15 @@
 
         if (newModel != null) {
             newModel.addChangeListener(changeListener);
+        }
 
-            if (accessibleContext != null) {
-                accessibleContext.firePropertyChange(
-                                                    AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
-                                                    (oldModel == null
-                                                     ? null : Integer.valueOf(oldModel.getValue())),
-                                                    (newModel == null
-                                                     ? null : Integer.valueOf(newModel.getValue())));
-            }
+        if (accessibleContext != null) {
+            accessibleContext.firePropertyChange(
+                                                AccessibleContext.ACCESSIBLE_VALUE_PROPERTY,
+                                                (oldModel == null
+                                                 ? null : Integer.valueOf(oldModel.getValue())),
+                                                (newModel == null
+                                                 ? null : Integer.valueOf(newModel.getValue())));
         }
 
         firePropertyChange("model", oldModel, sliderModel);
@@ -930,7 +928,7 @@
             throw new IllegalArgumentException( "Label incremement must be > 0" );
         }
 
-        class SmartHashtable extends Hashtable implements PropertyChangeListener {
+        class SmartHashtable extends Hashtable implements PropertyChangeListener {
             int increment = 0;
             int start = 0;
             boolean startAtMin = false;
@@ -977,9 +975,8 @@
                 if ( e.getPropertyName().equals( "minimum" ) ||
                      e.getPropertyName().equals( "maximum" ) ) {
 
-                    Dictionary labelTable = getLabelTable();
-                    Enumeration keys = labelTable.keys();
-                    Hashtable hashtable = new Hashtable();
+                    Enumeration keys = getLabelTable().keys();
+                    Hashtable hashtable = new Hashtable();
 
                     // Save the labels that were added by the developer
                     while ( keys.hasMoreElements() ) {
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JSpinner.java
--- a/jdk/src/share/classes/javax/swing/JSpinner.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JSpinner.java	Wed Jul 05 16:42:37 2017 +0200
@@ -433,8 +433,7 @@
      * @since 1.4
      */
     public ChangeListener[] getChangeListeners() {
-        return (ChangeListener[])listenerList.getListeners(
-                ChangeListener.class);
+        return listenerList.getListeners(ChangeListener.class);
     }
 
 
@@ -1536,7 +1535,7 @@
                     return textField.getAccessibleContext();
                 }
             } else if (editor instanceof Accessible) {
-                return ((Accessible)editor).getAccessibleContext();
+                return editor.getAccessibleContext();
             }
             return null;
         }
@@ -1693,7 +1692,7 @@
             if (i < 0 || i > 1) {
                 return false;
             }
-            Object o = null;
+            Object o;
             if (i == 0) {
                 o = getNextValue(); // AccessibleAction.INCREMENT
             } else {
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JTabbedPane.java
--- a/jdk/src/share/classes/javax/swing/JTabbedPane.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JTabbedPane.java	Wed Jul 05 16:42:37 2017 +0200
@@ -313,8 +313,7 @@
      * @since 1.4
      */
     public ChangeListener[] getChangeListeners() {
-        return (ChangeListener[])listenerList.getListeners(
-                ChangeListener.class);
+        return listenerList.getListeners(ChangeListener.class);
     }
 
     /**
@@ -2062,7 +2061,7 @@
                  * Accessibility classes unnecessarily.
                  */
                 AccessibleContext ac;
-                ac = ((Accessible) component).getAccessibleContext();
+                ac = component.getAccessibleContext();
                 if (ac != null) {
                     ac.setAccessibleParent(this);
                 }
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JTable.java
--- a/jdk/src/share/classes/javax/swing/JTable.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JTable.java	Wed Jul 05 16:42:37 2017 +0200
@@ -1677,16 +1677,16 @@
                 if (!forDrop && state != null) {
                     clearSelection();
 
-                    int[] rows = (int[])((int[][])state)[0];
-                    int[] cols = (int[])((int[][])state)[1];
-                    int[] anchleads = (int[])((int[][])state)[2];
-
-                    for (int i = 0; i < rows.length; i++) {
-                        addRowSelectionInterval(rows[i], rows[i]);
+                    int[] rows = ((int[][])state)[0];
+                    int[] cols = ((int[][])state)[1];
+                    int[] anchleads = ((int[][])state)[2];
+
+                    for (int row : rows) {
+                        addRowSelectionInterval(row, row);
                     }
 
-                    for (int i = 0; i < cols.length; i++) {
-                        addColumnSelectionInterval(cols[i], cols[i]);
+                    for (int col : cols) {
+                        addColumnSelectionInterval(col, col);
                     }
 
                     SwingUtilities2.setLeadAnchorWithoutSelection(
@@ -1776,7 +1776,7 @@
         boolean oldValue = this.autoCreateRowSorter;
         this.autoCreateRowSorter = autoCreateRowSorter;
         if (autoCreateRowSorter) {
-            setRowSorter(new TableRowSorter(getModel()));
+            setRowSorter(new TableRowSorter(getModel()));
         }
         firePropertyChange("autoCreateRowSorter", oldValue,
                            autoCreateRowSorter);
@@ -3198,7 +3198,7 @@
     private void accommodateDelta(int resizingColumnIndex, int delta) {
         int columnCount = getColumnCount();
         int from = resizingColumnIndex;
-        int to = columnCount;
+        int to;
 
         // Use the mode to determine how to absorb the changes.
         switch(autoResizeMode) {
@@ -3237,8 +3237,6 @@
         }
 
         adjustSizes(totalWidth + delta, r, false);
-
-        return;
     }
 
     private interface Resizable2 {
@@ -3492,7 +3490,7 @@
      * @see     #editingRow
      */
     public boolean isEditing() {
-        return (cellEditor == null)? false : true;
+        return cellEditor != null;
     }
 
     /**
@@ -3642,7 +3640,7 @@
             firePropertyChange("model", old, dataModel);
 
             if (getAutoCreateRowSorter()) {
-                setRowSorter(new TableRowSorter(dataModel));
+                setRowSorter(new TableRowSorter(dataModel));
             }
         }
     }
@@ -5160,7 +5158,7 @@
     public boolean getScrollableTracksViewportHeight() {
         return getFillsViewportHeight()
                && getParent() instanceof JViewport
-               && (((JViewport)getParent()).getHeight() > getPreferredSize().height);
+               && (getParent().getHeight() > getPreferredSize().height);
     }
 
     /**
@@ -5214,7 +5212,7 @@
         // by setting the client property JTable.autoStartsEdit to Boolean.FALSE.
         if (!retValue && condition == WHEN_ANCESTOR_OF_FOCUSED_COMPONENT &&
             isFocusOwner() &&
-            !Boolean.FALSE.equals((Boolean)getClientProperty("JTable.autoStartsEdit"))) {
+            !Boolean.FALSE.equals(getClientProperty("JTable.autoStartsEdit"))) {
             // We do not have a binding for the event.
             Component editorComponent = getEditorComponent();
             if (editorComponent == null) {
@@ -5436,7 +5434,7 @@
             this.value = null;
             ((JComponent)getComponent()).setBorder(new LineBorder(Color.black));
             try {
-                Class type = table.getColumnClass(column);
+                Class type = table.getColumnClass(column);
                 // Since our obligation is to produce a value which is
                 // assignable for the required type it is OK to use the
                 // String constructor for columns which are declared
@@ -6627,10 +6625,10 @@
             } else if (name.compareTo("tableCellEditor") == 0) {
 
                 if (oldValue != null && oldValue instanceof TableCellEditor) {
-                    ((TableCellEditor) oldValue).removeCellEditorListener((CellEditorListener) this);
+                    ((TableCellEditor) oldValue).removeCellEditorListener(this);
                 }
                 if (newValue != null && newValue instanceof TableCellEditor) {
-                    ((TableCellEditor) newValue).addCellEditorListener((CellEditorListener) this);
+                    ((TableCellEditor) newValue).addCellEditorListener(this);
                 }
             }
         }
@@ -7045,7 +7043,7 @@
          */
         public Accessible getAccessibleSelection(int i) {
             if (i < 0 || i > getAccessibleSelectionCount()) {
-                return (Accessible) null;
+                return null;
             }
 
             int rowsSel = JTable.this.getSelectedRowCount();
@@ -7158,7 +7156,7 @@
                     return getAccessibleChild((r * ttlCols) + c);
                 }
             }
-            return (Accessible) null;
+            return null;
         }
 
         /**
@@ -7906,7 +7904,7 @@
                                   JTable.this, getValueAt(row, column),
                                   false, false, row, column);
                 if (component instanceof Accessible) {
-                    return ((Accessible) component).getAccessibleContext();
+                    return component.getAccessibleContext();
                 } else {
                     return null;
                 }
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JTextField.java
--- a/jdk/src/share/classes/javax/swing/JTextField.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JTextField.java	Wed Jul 05 16:42:37 2017 +0200
@@ -475,8 +475,7 @@
      * @since 1.4
      */
     public synchronized ActionListener[] getActionListeners() {
-        return (ActionListener[])listenerList.getListeners(
-                ActionListener.class);
+        return listenerList.getListeners(ActionListener.class);
     }
 
     /**
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JTree.java
--- a/jdk/src/share/classes/javax/swing/JTree.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JTree.java	Wed Jul 05 16:42:37 2017 +0200
@@ -187,7 +187,7 @@
      * information must be determined by visiting all the parent
      * paths and seeing if they are visible.
      */
-    transient private Hashtable           expandedState;
+    transient private Hashtable expandedState;
 
 
     /**
@@ -281,7 +281,7 @@
      * Used when setExpandedState is invoked,
      * will be a Stack of Stacks.
      */
-    transient private Stack           expandedStack;
+    transient private Stack> expandedStack;
 
     /**
      * Lead selection path, may not be null.
@@ -652,9 +652,9 @@
     @ConstructorProperties({"model"})
     public JTree(TreeModel newModel) {
         super();
-        expandedStack = new Stack();
+        expandedStack = new Stack>();
         toggleClickCount = 2;
-        expandedState = new Hashtable();
+        expandedState = new Hashtable();
         setLayout(null);
         rowHeight = 16;
         visibleRowCount = 20;
@@ -691,7 +691,7 @@
      *  description: The UI object that implements the Component's LookAndFeel.
      */
     public void setUI(TreeUI ui) {
-        if ((TreeUI)this.ui != ui) {
+        if (this.ui != ui) {
             settingUI = true;
             uiTreeExpansionListener = null;
             try {
@@ -1298,8 +1298,8 @@
         Object root = (model == null) ? null : model.getRoot();
         TreePath rootPath = (root == null) ? null : new TreePath(root);
 
-        TreePath child = null;
-        TreePath parent = null;
+        TreePath child;
+        TreePath parent;
         boolean outside = row == -1
                           || p.y < bounds.y
                           || p.y >= bounds.y + bounds.height;
@@ -1940,14 +1940,14 @@
         if(!isExpanded(parent))
             return null;
 
-        Enumeration       toggledPaths = expandedState.keys();
-        Vector            elements = null;
+        Enumeration toggledPaths = expandedState.keys();
+        Vector elements = null;
         TreePath          path;
         Object            value;
 
         if(toggledPaths != null) {
             while(toggledPaths.hasMoreElements()) {
-                path = (TreePath)toggledPaths.nextElement();
+                path = toggledPaths.nextElement();
                 value = expandedState.get(path);
                 // Add the path if it is expanded, a descendant of parent,
                 // and it is visible (all parents expanded). This is rather
@@ -1956,7 +1956,7 @@
                    ((Boolean)value).booleanValue() &&
                    parent.isDescendant(path) && isVisible(path)) {
                     if (elements == null) {
-                        elements = new Vector();
+                        elements = new Vector();
                     }
                     elements.addElement(path);
                 }
@@ -1990,9 +1990,9 @@
             return false;
 
         // Is this node expanded?
-        Object          value = expandedState.get(path);
-
-        if(value == null || !((Boolean)value).booleanValue())
+        Boolean value = expandedState.get(path);
+
+        if(value == null || !value.booleanValue())
             return false;
 
         // It is, make sure its parent is also expanded.
@@ -2018,7 +2018,7 @@
             TreePath         path = tree.getPathForRow(this, row);
 
             if(path != null) {
-                Boolean value = (Boolean)expandedState.get(path);
+                Boolean value = expandedState.get(path);
 
                 return (value != null && value.booleanValue());
             }
@@ -2704,8 +2704,7 @@
      * @since 1.4
      */
     public TreeExpansionListener[] getTreeExpansionListeners() {
-        return (TreeExpansionListener[])listenerList.getListeners(
-                TreeExpansionListener.class);
+        return listenerList.getListeners(TreeExpansionListener.class);
     }
 
     /**
@@ -2737,8 +2736,7 @@
      * @since 1.4
      */
     public TreeWillExpandListener[] getTreeWillExpandListeners() {
-        return (TreeWillExpandListener[])listenerList.getListeners(
-                TreeWillExpandListener.class);
+        return listenerList.getListeners(TreeWillExpandListener.class);
     }
 
     /**
@@ -2895,8 +2893,7 @@
      * @since 1.4
      */
     public TreeSelectionListener[] getTreeSelectionListeners() {
-        return (TreeSelectionListener[])listenerList.getListeners(
-                TreeSelectionListener.class);
+        return listenerList.getListeners(TreeSelectionListener.class);
     }
 
     /**
@@ -3030,7 +3027,7 @@
 
     // Serialization support.
     private void writeObject(ObjectOutputStream s) throws IOException {
-        Vector      values = new Vector();
+        Vector values = new Vector();
 
         s.defaultWriteObject();
         // Save the cellRenderer, if its Serializable.
@@ -3077,9 +3074,9 @@
 
         // Create an instance of expanded state.
 
-        expandedState = new Hashtable();
-
-        expandedStack = new Stack();
+        expandedState = new Hashtable();
+
+        expandedStack = new Stack>();
 
         Vector          values = (Vector)s.readObject();
         int             indexCounter = 0;
@@ -3132,13 +3129,13 @@
         TreeModel       model = getModel();
 
         if(model != null) {
-            Enumeration        paths = expandedState.keys();
+            Enumeration paths = expandedState.keys();
 
             if(paths != null) {
-                Vector         state = new Vector();
+                Vector state = new Vector();
 
                 while(paths.hasMoreElements()) {
-                    TreePath   path = (TreePath)paths.nextElement();
+                    TreePath path = paths.nextElement();
                     Object     archivePath;
 
                     try {
@@ -3502,7 +3499,7 @@
      */
     public boolean getScrollableTracksViewportWidth() {
         if (getParent() instanceof JViewport) {
-            return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
+            return getParent().getWidth() > getPreferredSize().width;
         }
         return false;
     }
@@ -3518,7 +3515,7 @@
      */
     public boolean getScrollableTracksViewportHeight() {
         if (getParent() instanceof JViewport) {
-            return (((JViewport)getParent()).getHeight() > getPreferredSize().height);
+            return getParent().getHeight() > getPreferredSize().height;
         }
         return false;
     }
@@ -3535,14 +3532,14 @@
     protected void setExpandedState(TreePath path, boolean state) {
         if(path != null) {
             // Make sure all parents of path are expanded.
-            Stack         stack;
-            TreePath      parentPath = path.getParentPath();
+            Stack stack;
+            TreePath parentPath = path.getParentPath();
 
             if (expandedStack.size() == 0) {
-                stack = new Stack();
+                stack = new Stack();
             }
             else {
-                stack = (Stack)expandedStack.pop();
+                stack = expandedStack.pop();
             }
 
             try {
@@ -3556,7 +3553,7 @@
                     }
                 }
                 for(int counter = stack.size() - 1; counter >= 0; counter--) {
-                    parentPath = (TreePath)stack.pop();
+                    parentPath = stack.pop();
                     if(!isExpanded(parentPath)) {
                         try {
                             fireTreeWillExpand(parentPath);
@@ -3636,12 +3633,11 @@
         if(parent == null)
             return null;
 
-        Vector            descendants = new Vector();
-        Enumeration       nodes = expandedState.keys();
-        TreePath          path;
+        Vector descendants = new Vector();
+        Enumeration nodes = expandedState.keys();
 
         while(nodes.hasMoreElements()) {
-            path = (TreePath)nodes.nextElement();
+            TreePath path = nodes.nextElement();
             if(parent.isDescendant(path))
                 descendants.addElement(path);
         }
@@ -3664,8 +3660,8 @@
     {
          if(toRemove != null) {
              while(toRemove.hasMoreElements()) {
-                 Enumeration         descendants = getDescendantToggledPaths
-                                         ((TreePath)toRemove.nextElement());
+                 Enumeration descendants = getDescendantToggledPaths
+                         (toRemove.nextElement());
 
                  if(descendants != null) {
                      while(descendants.hasMoreElements()) {
@@ -4250,7 +4246,7 @@
         private AccessibleContext getCurrentAccessibleContext() {
             Component c = getCurrentComponent();
             if (c instanceof Accessible) {
-                return (((Accessible) c).getAccessibleContext());
+                return c.getAccessibleContext();
             } else {
                 return null;
             }
@@ -4573,7 +4569,7 @@
             private AccessibleContext getCurrentAccessibleContext() {
                 Component c = getCurrentComponent();
                 if (c instanceof Accessible) {
-                    return (((Accessible) c).getAccessibleContext());
+                    return c.getAccessibleContext();
                 } else {
                     return null;
                 }
@@ -5117,12 +5113,8 @@
             public boolean isVisible() {
                 Rectangle pathBounds = tree.getPathBounds(path);
                 Rectangle parentBounds = tree.getVisibleRect();
-                if (pathBounds != null && parentBounds != null &&
-                    parentBounds.intersects(pathBounds)) {
-                    return true;
-                } else {
-                    return false;
-                }
+                return pathBounds != null && parentBounds != null &&
+                        parentBounds.intersects(pathBounds);
             }
 
             public void setVisible(boolean b) {
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JViewport.java
--- a/jdk/src/share/classes/javax/swing/JViewport.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JViewport.java	Wed Jul 05 16:42:37 2017 +0200
@@ -389,7 +389,7 @@
                 // could be bigger than invalid size.
                 validateView();
             }
-            int     dx = 0, dy = 0;
+            int dx, dy;
 
             dx = positionAdjustment(getWidth(), contentRect.width, contentRect.x);
             dy = positionAdjustment(getHeight(), contentRect.height, contentRect.y);
@@ -682,10 +682,7 @@
      * @see JComponent#isPaintingOrigin()
      */
     boolean isPaintingOrigin() {
-        if (scrollMode == BACKINGSTORE_SCROLL_MODE) {
-            return true;
-        }
-        return false;
+        return scrollMode == BACKINGSTORE_SCROLL_MODE;
     }
 
 
@@ -903,11 +900,7 @@
       */
     public void setScrollMode(int mode) {
         scrollMode = mode;
-        if (mode == BACKINGSTORE_SCROLL_MODE) {
-            backingStore = true;
-        } else {
-            backingStore = false;
-        }
+        backingStore = mode == BACKINGSTORE_SCROLL_MODE;
     }
 
     /**
@@ -958,10 +951,10 @@
         }
     }
 
-    private final boolean isBlitting() {
+    private boolean isBlitting() {
         Component view = getView();
         return (scrollMode == BLIT_SCROLL_MODE) &&
-               (view instanceof JComponent) && ((JComponent)view).isOpaque();
+               (view instanceof JComponent) && view.isOpaque();
     }
 
 
@@ -1380,8 +1373,7 @@
      * @since 1.4
      */
     public ChangeListener[] getChangeListeners() {
-        return (ChangeListener[])listenerList.getListeners(
-                ChangeListener.class);
+        return listenerList.getListeners(ChangeListener.class);
     }
 
     /**
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/JWindow.java
--- a/jdk/src/share/classes/javax/swing/JWindow.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/JWindow.java	Wed Jul 05 16:42:37 2017 +0200
@@ -185,7 +185,7 @@
         super(owner == null? SwingUtilities.getSharedOwnerFrame() : owner);
         if (owner == null) {
             WindowListener ownerShutdownListener =
-                (WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener();
+                    SwingUtilities.getSharedOwnerFrameShutdownListener();
             addWindowListener(ownerShutdownListener);
         }
         windowInit();
@@ -212,7 +212,7 @@
               owner);
         if (owner == null) {
             WindowListener ownerShutdownListener =
-                (WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener();
+                    SwingUtilities.getSharedOwnerFrameShutdownListener();
             addWindowListener(ownerShutdownListener);
         }
         windowInit();
@@ -250,7 +250,7 @@
               owner, gc);
         if (owner == null) {
             WindowListener ownerShutdownListener =
-                (WindowListener)SwingUtilities.getSharedOwnerFrameShutdownListener();
+                    SwingUtilities.getSharedOwnerFrameShutdownListener();
             addWindowListener(ownerShutdownListener);
         }
         windowInit();
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/KeyboardManager.java
--- a/jdk/src/share/classes/javax/swing/KeyboardManager.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/KeyboardManager.java	Wed Jul 05 16:42:37 2017 +0200
@@ -68,13 +68,13 @@
     /**
       * maps top-level containers to a sub-hashtable full of keystrokes
       */
-    Hashtable containerMap = new Hashtable();
+    Hashtable containerMap = new Hashtable();
 
     /**
       * Maps component/keystroke pairs to a topLevel container
       * This is mainly used for fast unregister operations
       */
-    Hashtable componentKeyStrokeMap = new Hashtable();
+    Hashtable componentKeyStrokeMap = new Hashtable();
 
     public static KeyboardManager getCurrentManager() {
         return currentManager;
@@ -95,7 +95,7 @@
          if (topContainer == null) {
              return;
          }
-         Hashtable keyMap = (Hashtable)containerMap.get(topContainer);
+         Hashtable keyMap = containerMap.get(topContainer);
 
          if (keyMap ==  null) {  // lazy evaluate one
              keyMap = registerNewTopContainer(topContainer);
@@ -114,8 +114,8 @@
            // Then add the old compoennt and the new compoent to the vector
            // then insert the vector in the table
            if (tmp != c) {  // this means this is already registered for this component, no need to dup
-               Vector v = new Vector();
-               v.addElement(tmp);
+               Vector v = new Vector();
+               v.addElement((JComponent) tmp);
                v.addElement(c);
                keyMap.put(k, v);
            }
@@ -154,13 +154,13 @@
 
          ComponentKeyStrokePair ckp = new ComponentKeyStrokePair(c,ks);
 
-         Object topContainer = componentKeyStrokeMap.get(ckp);
+         Container topContainer = componentKeyStrokeMap.get(ckp);
 
          if (topContainer == null) {  // never heard of this pairing, so bail
              return;
          }
 
-         Hashtable keyMap = (Hashtable)containerMap.get(topContainer);
+         Hashtable keyMap = containerMap.get(topContainer);
          if  (keyMap == null) { // this should never happen, but I'm being safe
              Thread.dumpStack();
              return;
@@ -221,7 +221,7 @@
                ks=KeyStroke.getKeyStroke(e.getKeyCode(), e.getModifiers(), !pressed);
          }
 
-         Hashtable keyMap = (Hashtable)containerMap.get(topAncestor);
+         Hashtable keyMap = containerMap.get(topAncestor);
          if (keyMap != null) { // this container isn't registered, so bail
 
              Object tmp = keyMap.get(ks);
@@ -293,7 +293,7 @@
         if (top == null) {
             return;
         }
-        Hashtable keyMap = (Hashtable)containerMap.get(top);
+        Hashtable keyMap = containerMap.get(top);
 
         if (keyMap ==  null) {  // lazy evaluate one
              keyMap = registerNewTopContainer(top);
@@ -314,11 +314,11 @@
 
 
     public void unregisterMenuBar(JMenuBar mb) {
-        Object topContainer = getTopAncestor(mb);
+        Container topContainer = getTopAncestor(mb);
         if (topContainer == null) {
             return;
         }
-        Hashtable keyMap = (Hashtable)containerMap.get(topContainer);
+        Hashtable keyMap = containerMap.get(topContainer);
         if (keyMap!=null) {
             Vector v = (Vector)keyMap.get(JMenuBar.class);
             if (v != null) {
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/LayoutComparator.java
--- a/jdk/src/share/classes/javax/swing/LayoutComparator.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/LayoutComparator.java	Wed Jul 05 16:42:37 2017 +0200
@@ -39,7 +39,7 @@
  *
  * @author David Mendenhall
  */
-final class LayoutComparator implements Comparator, java.io.Serializable {
+final class LayoutComparator implements Comparator, java.io.Serializable {
 
     private static final int ROW_TOLERANCE = 10;
 
@@ -51,10 +51,7 @@
         leftToRight = orientation.isLeftToRight();
     }
 
-    public int compare(Object o1, Object o2) {
-        Component a = (Component)o1;
-        Component b = (Component)o2;
-
+    public int compare(Component a, Component b) {
         if (a == b) {
             return 0;
         }
@@ -65,9 +62,9 @@
         // each Component and then search from the Window down until the
         // hierarchy branches.
         if (a.getParent() != b.getParent()) {
-            LinkedList aAncestory, bAncestory;
+            LinkedList aAncestory = new LinkedList();
 
-            for(aAncestory = new LinkedList(); a != null; a = a.getParent()) {
+            for(; a != null; a = a.getParent()) {
                 aAncestory.add(a);
                 if (a instanceof Window) {
                     break;
@@ -78,7 +75,9 @@
                 throw new ClassCastException();
             }
 
-            for(bAncestory = new LinkedList(); b != null; b = b.getParent()) {
+            LinkedList bAncestory = new LinkedList();
+
+            for(; b != null; b = b.getParent()) {
                 bAncestory.add(b);
                 if (b instanceof Window) {
                     break;
@@ -89,18 +88,18 @@
                 throw new ClassCastException();
             }
 
-            for (ListIterator
+            for (ListIterator
                      aIter = aAncestory.listIterator(aAncestory.size()),
                      bIter = bAncestory.listIterator(bAncestory.size()); ;) {
                 if (aIter.hasPrevious()) {
-                    a = (Component)aIter.previous();
+                    a = aIter.previous();
                 } else {
                     // a is an ancestor of b
                     return -1;
                 }
 
                 if (bIter.hasPrevious()) {
-                    b = (Component)bIter.previous();
+                    b = bIter.previous();
                 } else {
                     // b is an ancestor of a
                     return 1;
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/LayoutFocusTraversalPolicy.java
--- a/jdk/src/share/classes/javax/swing/LayoutFocusTraversalPolicy.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/LayoutFocusTraversalPolicy.java	Wed Jul 05 16:42:37 2017 +0200
@@ -65,7 +65,7 @@
      * Constructs a LayoutFocusTraversalPolicy with the passed in
      * Comparator.
      */
-    LayoutFocusTraversalPolicy(Comparator c) {
+    LayoutFocusTraversalPolicy(Comparator c) {
         super(c);
     }
 
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/LegacyGlueFocusTraversalPolicy.java
--- a/jdk/src/share/classes/javax/swing/LegacyGlueFocusTraversalPolicy.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/LegacyGlueFocusTraversalPolicy.java	Wed Jul 05 16:42:37 2017 +0200
@@ -48,8 +48,8 @@
     private transient FocusTraversalPolicy delegatePolicy;
     private transient DefaultFocusManager delegateManager;
 
-    private HashMap forwardMap = new HashMap(),
-        backwardMap = new HashMap();
+    private HashMap forwardMap = new HashMap(),
+        backwardMap = new HashMap();
 
     LegacyGlueFocusTraversalPolicy(FocusTraversalPolicy delegatePolicy) {
         this.delegatePolicy = delegatePolicy;
@@ -70,11 +70,11 @@
     public Component getComponentAfter(Container focusCycleRoot,
                                        Component aComponent) {
         Component hardCoded = aComponent, prevHardCoded;
-        HashSet sanity = new HashSet();
+        HashSet sanity = new HashSet();
 
         do {
             prevHardCoded = hardCoded;
-            hardCoded = (Component)forwardMap.get(hardCoded);
+            hardCoded = forwardMap.get(hardCoded);
             if (hardCoded == null) {
                 if (delegatePolicy != null &&
                     prevHardCoded.isFocusCycleRoot(focusCycleRoot)) {
@@ -99,11 +99,11 @@
     public Component getComponentBefore(Container focusCycleRoot,
                                         Component aComponent) {
         Component hardCoded = aComponent, prevHardCoded;
-        HashSet sanity = new HashSet();
+        HashSet sanity = new HashSet();
 
         do {
             prevHardCoded = hardCoded;
-            hardCoded = (Component)backwardMap.get(hardCoded);
+            hardCoded = backwardMap.get(hardCoded);
             if (hardCoded == null) {
                 if (delegatePolicy != null &&
                     prevHardCoded.isFocusCycleRoot(focusCycleRoot)) {
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/MenuSelectionManager.java
--- a/jdk/src/share/classes/javax/swing/MenuSelectionManager.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/MenuSelectionManager.java	Wed Jul 05 16:42:37 2017 +0200
@@ -37,7 +37,7 @@
  * @author Arnaud Weber
  */
 public class MenuSelectionManager {
-    private Vector selection = new Vector();
+    private Vector selection = new Vector();
 
     /* diagnostic aids -- should be false for production builds. */
     private static final boolean TRACE =   false; // trace creates and disposes
@@ -100,14 +100,14 @@
         }
 
         for(i=0,c=path.length;i= firstDifference ; i--) {
-            MenuElement me = (MenuElement)selection.elementAt(i);
+            MenuElement me = selection.elementAt(i);
             selection.removeElementAt(i);
             me.menuSelectionChanged(false);
         }
@@ -131,7 +131,7 @@
         MenuElement res[] = new MenuElement[selection.size()];
         int i,c;
         for(i=0,c=selection.size();i 0) {
-            MenuElement me = (MenuElement)selection.elementAt(0);
+            MenuElement me = selection.elementAt(0);
             return isComponentPartOfCurrentMenu(me,c);
         } else
             return false;
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/MultiUIDefaults.java
--- a/jdk/src/share/classes/javax/swing/MultiUIDefaults.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/MultiUIDefaults.java	Wed Jul 05 16:42:37 2017 +0200
@@ -56,8 +56,7 @@
             return value;
         }
 
-        for(int i = 0; i < tables.length; i++) {
-            UIDefaults table = tables[i];
+        for (UIDefaults table : tables) {
             value = (table != null) ? table.get(key) : null;
             if (value != null) {
                 return value;
@@ -75,8 +74,7 @@
             return value;
         }
 
-        for(int i = 0; i < tables.length; i++) {
-            UIDefaults table = tables[i];
+        for (UIDefaults table : tables) {
             value = (table != null) ? table.get(key,l) : null;
             if (value != null) {
                 return value;
@@ -89,8 +87,7 @@
 
     public int size() {
         int n = super.size();
-        for(int i = 0; i < tables.length; i++) {
-            UIDefaults table = tables[i];
+        for (UIDefaults table : tables) {
             n += (table != null) ? table.size() : 0;
         }
         return n;
@@ -102,7 +99,7 @@
     }
 
 
-    public Enumeration keys()
+    public Enumeration keys()
     {
         Enumeration[] enums = new Enumeration[1 + tables.length];
         enums[0] = super.keys();
@@ -116,7 +113,7 @@
     }
 
 
-    public Enumeration elements()
+    public Enumeration elements()
     {
         Enumeration[] enums = new Enumeration[1 + tables.length];
         enums[0] = super.elements();
@@ -137,7 +134,7 @@
         }
     }
 
-    private static class MultiUIDefaultsEnumerator implements Enumeration
+    private static class MultiUIDefaultsEnumerator implements Enumeration
     {
         Enumeration[] enums;
         int n = 0;
@@ -175,8 +172,7 @@
             return value;
         }
 
-        for(int i = 0; i < tables.length; i++) {
-            UIDefaults table = tables[i];
+        for (UIDefaults table : tables) {
             value = (table != null) ? table.remove(key) : null;
             if (value != null) {
                 return value;
@@ -189,8 +185,7 @@
 
     public void clear() {
         super.clear();
-        for(int i = 0; i < tables.length; i++) {
-            UIDefaults table = tables[i];
+        for (UIDefaults table : tables) {
             if (table != null) {
                 table.clear();
             }
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/PopupFactory.java
--- a/jdk/src/share/classes/javax/swing/PopupFactory.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/PopupFactory.java	Wed Jul 05 16:42:37 2017 +0200
@@ -313,9 +313,9 @@
                 if(contents instanceof JPopupMenu) {
                     JPopupMenu jpm = (JPopupMenu) contents;
                     Component popComps[] = jpm.getComponents();
-                    for(int i=0;i cache;
+                Map> heavyPopupCache = getHeavyWeightPopupCache();
 
                 if (heavyPopupCache.containsKey(w)) {
-                    cache = (List)heavyPopupCache.get(w);
+                    cache = heavyPopupCache.get(w);
                 } else {
                     return null;
                 }
-                int c;
-                if ((c = cache.size()) > 0) {
-                    HeavyWeightPopup r = (HeavyWeightPopup)cache.get(0);
+                if (cache.size() > 0) {
+                    HeavyWeightPopup r = cache.get(0);
                     cache.remove(0);
                     return r;
                 }
@@ -380,13 +379,13 @@
          * Window to a List of
          * HeavyWeightPopups.
          */
-        private static Map getHeavyWeightPopupCache() {
+        private static Map> getHeavyWeightPopupCache() {
             synchronized (HeavyWeightPopup.class) {
-                Map cache = (Map)SwingUtilities.appContextGet(
+                Map> cache = (Map>)SwingUtilities.appContextGet(
                                   heavyWeightPopupCacheKey);
 
                 if (cache == null) {
-                    cache = new HashMap(2);
+                    cache = new HashMap>(2);
                     SwingUtilities.appContextPut(heavyWeightPopupCacheKey,
                                                  cache);
                 }
@@ -399,13 +398,13 @@
          */
         private static void recycleHeavyWeightPopup(HeavyWeightPopup popup) {
             synchronized (HeavyWeightPopup.class) {
-                List cache;
-                Object window = SwingUtilities.getWindowAncestor(
+                List cache;
+                Window window = SwingUtilities.getWindowAncestor(
                                      popup.getComponent());
-                Map heavyPopupCache = getHeavyWeightPopupCache();
+                Map> heavyPopupCache = getHeavyWeightPopupCache();
 
                 if (window instanceof Popup.DefaultFrame ||
-                                      !((Window)window).isVisible()) {
+                                      !window.isVisible()) {
                     // If the Window isn't visible, we don't cache it as we
                     // likely won't ever get a windowClosed event to clean up.
                     // We also don't cache DefaultFrames as this indicates
@@ -414,28 +413,27 @@
                     popup._dispose();
                     return;
                 } else if (heavyPopupCache.containsKey(window)) {
-                    cache = (List)heavyPopupCache.get(window);
+                    cache = heavyPopupCache.get(window);
                 } else {
-                    cache = new ArrayList();
+                    cache = new ArrayList();
                     heavyPopupCache.put(window, cache);
                     // Clean up if the Window is closed
-                    final Window w = (Window)window;
+                    final Window w = window;
 
                     w.addWindowListener(new WindowAdapter() {
                         public void windowClosed(WindowEvent e) {
-                            List popups;
+                            List popups;
 
                             synchronized(HeavyWeightPopup.class) {
-                                Map heavyPopupCache2 =
+                                Map> heavyPopupCache2 =
                                               getHeavyWeightPopupCache();
 
-                                popups = (List)heavyPopupCache2.remove(w);
+                                popups = heavyPopupCache2.remove(w);
                             }
                             if (popups != null) {
                                 for (int counter = popups.size() - 1;
                                                    counter >= 0; counter--) {
-                                    ((HeavyWeightPopup)popups.get(counter)).
-                                                       _dispose();
+                                    popups.get(counter)._dispose();
                                 }
                             }
                         }
@@ -534,10 +532,9 @@
                 Window[] ownedWindows = w.getOwnedWindows();
                 if(ownedWindows != null) {
                     Rectangle bnd = component.getBounds();
-                    for(int i=0; i getLightWeightPopupCache() {
+            List cache = (List)SwingUtilities.appContextGet(
                                    lightWeightPopupCacheKey);
             if (cache == null) {
-                cache = new ArrayList();
+                cache = new ArrayList();
                 SwingUtilities.appContextPut(lightWeightPopupCacheKey, cache);
             }
             return cache;
@@ -682,7 +679,7 @@
          */
         private static void recycleLightWeightPopup(LightWeightPopup popup) {
             synchronized (LightWeightPopup.class) {
-                List lightPopupCache = getLightWeightPopupCache();
+                List lightPopupCache = getLightWeightPopupCache();
                 if (lightPopupCache.size() < MAX_CACHE_SIZE) {
                     lightPopupCache.add(popup);
                 }
@@ -695,11 +692,9 @@
          */
         private static LightWeightPopup getRecycledLightWeightPopup() {
             synchronized (LightWeightPopup.class) {
-                List lightPopupCache = getLightWeightPopupCache();
-                int c;
-                if((c = lightPopupCache.size()) > 0) {
-                    LightWeightPopup r = (LightWeightPopup)lightPopupCache.
-                                               get(0);
+                List lightPopupCache = getLightWeightPopupCache();
+                if (lightPopupCache.size() > 0) {
+                    LightWeightPopup r = lightPopupCache.get(0);
                     lightPopupCache.remove(0);
                     return r;
                 }
@@ -755,8 +750,7 @@
 
             component.setLocation(p.x, p.y);
             if (parent instanceof JLayeredPane) {
-                ((JLayeredPane)parent).add(component,
-                                           JLayeredPane.POPUP_LAYER, 0);
+                parent.add(component, JLayeredPane.POPUP_LAYER, 0);
             } else {
                 parent.add(component);
             }
@@ -826,12 +820,12 @@
         /**
          * Returns the cache to use for medium weight popups.
          */
-        private static List getMediumWeightPopupCache() {
-            List cache = (List)SwingUtilities.appContextGet(
+        private static List getMediumWeightPopupCache() {
+            List cache = (List)SwingUtilities.appContextGet(
                                     mediumWeightPopupCacheKey);
 
             if (cache == null) {
-                cache = new ArrayList();
+                cache = new ArrayList();
                 SwingUtilities.appContextPut(mediumWeightPopupCacheKey, cache);
             }
             return cache;
@@ -842,7 +836,7 @@
          */
         private static void recycleMediumWeightPopup(MediumWeightPopup popup) {
             synchronized (MediumWeightPopup.class) {
-                List mediumPopupCache = getMediumWeightPopupCache();
+                List mediumPopupCache = getMediumWeightPopupCache();
                 if (mediumPopupCache.size() < MAX_CACHE_SIZE) {
                     mediumPopupCache.add(popup);
                 }
@@ -855,12 +849,9 @@
          */
         private static MediumWeightPopup getRecycledMediumWeightPopup() {
             synchronized (MediumWeightPopup.class) {
-                java.util.List mediumPopupCache =
-                                     getMediumWeightPopupCache();
-                int c;
-                if ((c=mediumPopupCache.size()) > 0) {
-                    MediumWeightPopup r = (MediumWeightPopup)mediumPopupCache.
-                                                 get(0);
+                List mediumPopupCache = getMediumWeightPopupCache();
+                if (mediumPopupCache.size() > 0) {
+                    MediumWeightPopup r = mediumPopupCache.get(0);
                     mediumPopupCache.remove(0);
                     return r;
                 }
@@ -904,7 +895,7 @@
                                                                        x, y);
                 component.setVisible(false);
                 component.setLocation(p.x, p.y);
-                ((JLayeredPane)parent).add(component, JLayeredPane.POPUP_LAYER,
+                parent.add(component, JLayeredPane.POPUP_LAYER,
                                            0);
             } else {
                 Point p = SwingUtilities.convertScreenLocationToParent(parent,
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/RepaintManager.java
--- a/jdk/src/share/classes/javax/swing/RepaintManager.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/RepaintManager.java	Wed Jul 05 16:42:37 2017 +0200
@@ -40,6 +40,8 @@
 import sun.java2d.SunGraphicsEnvironment;
 import sun.security.action.GetPropertyAction;
 
+import com.sun.java.swing.SwingUtilities3;
+
 
 /**
  * This class manages repaint requests, allowing the number
@@ -303,6 +305,11 @@
      */
     public synchronized void addInvalidComponent(JComponent invalidComponent)
     {
+        RepaintManager delegate = getDelegate(invalidComponent);
+        if (delegate != null) {
+            delegate.addInvalidComponent(invalidComponent);
+            return;
+        }
         Component validateRoot = null;
 
         /* Find the first JComponent ancestor of this component whose
@@ -373,6 +380,11 @@
      * @see #addInvalidComponent
      */
     public synchronized void removeInvalidComponent(JComponent component) {
+        RepaintManager delegate = getDelegate(component);
+        if (delegate != null) {
+            delegate.removeInvalidComponent(component);
+            return;
+        }
         if(invalidComponents != null) {
             int index = invalidComponents.indexOf(component);
             if(index != -1) {
@@ -464,6 +476,11 @@
      */
     public void addDirtyRegion(JComponent c, int x, int y, int w, int h)
     {
+        RepaintManager delegate = getDelegate(c);
+        if (delegate != null) {
+            delegate.addDirtyRegion(c, x, y, w, h);
+            return;
+        }
         addDirtyRegion0(c, x, y, w, h);
     }
 
@@ -572,7 +589,7 @@
      */
     private synchronized boolean extendDirtyRegion(
         Component c, int x, int y, int w, int h) {
-        Rectangle r = (Rectangle)dirtyComponents.get(c);
+        Rectangle r = dirtyComponents.get(c);
         if (r != null) {
             // A non-null r implies c is already marked as dirty,
             // and that the parent is valid. Therefore we can
@@ -588,9 +605,13 @@
      *  dirty.
      */
     public Rectangle getDirtyRegion(JComponent aComponent) {
-        Rectangle r = null;
+        RepaintManager delegate = getDelegate(aComponent);
+        if (delegate != null) {
+            return delegate.getDirtyRegion(aComponent);
+        }
+        Rectangle r;
         synchronized(this) {
-            r = (Rectangle)dirtyComponents.get(aComponent);
+            r = dirtyComponents.get(aComponent);
         }
         if(r == null)
             return new Rectangle(0,0,0,0);
@@ -603,6 +624,11 @@
      * completely painted during the next paintDirtyRegions() call.
      */
     public void markCompletelyDirty(JComponent aComponent) {
+        RepaintManager delegate = getDelegate(aComponent);
+        if (delegate != null) {
+            delegate.markCompletelyDirty(aComponent);
+            return;
+        }
         addDirtyRegion(aComponent,0,0,Integer.MAX_VALUE,Integer.MAX_VALUE);
     }
 
@@ -611,6 +637,11 @@
      * get painted during the next paintDirtyRegions() call.
      */
     public void markCompletelyClean(JComponent aComponent) {
+        RepaintManager delegate = getDelegate(aComponent);
+        if (delegate != null) {
+            delegate.markCompletelyClean(aComponent);
+            return;
+        }
         synchronized(this) {
                 dirtyComponents.remove(aComponent);
         }
@@ -623,6 +654,10 @@
      * if it return true.
      */
     public boolean isCompletelyDirty(JComponent aComponent) {
+        RepaintManager delegate = getDelegate(aComponent);
+        if (delegate != null) {
+            return delegate.isCompletelyDirty(aComponent);
+        }
         Rectangle r;
 
         r = getDirtyRegion(aComponent);
@@ -710,8 +745,8 @@
         Rectangle rect;
         int localBoundsX = 0;
         int localBoundsY = 0;
-        int localBoundsH = 0;
-        int localBoundsW = 0;
+        int localBoundsH;
+        int localBoundsW;
         Enumeration keys;
 
         roots = new ArrayList(count);
@@ -818,7 +853,7 @@
 
         dx = rootDx = 0;
         dy = rootDy = 0;
-        tmp.setBounds((Rectangle) dirtyComponents.get(dirtyComponent));
+        tmp.setBounds(dirtyComponents.get(dirtyComponent));
 
         // System.out.println("Collect dirty component for bound " + tmp +
         //                                   "component bounds is " + cBounds);;
@@ -865,7 +900,7 @@
             Rectangle r;
             tmp.setLocation(tmp.x + rootDx - dx,
                             tmp.y + rootDy - dy);
-            r = (Rectangle)dirtyComponents.get(rootDirtyComponent);
+            r = dirtyComponents.get(rootDirtyComponent);
             SwingUtilities.computeUnion(tmp.x,tmp.y,tmp.width,tmp.height,r);
         }
 
@@ -900,6 +935,10 @@
      * repaint manager.
      */
     public Image getOffscreenBuffer(Component c,int proposedWidth,int proposedHeight) {
+        RepaintManager delegate = getDelegate(c);
+        if (delegate != null) {
+            return delegate.getOffscreenBuffer(c, proposedWidth, proposedHeight);
+        }
         return _getOffscreenBuffer(c, proposedWidth, proposedHeight);
     }
 
@@ -917,6 +956,11 @@
    */
     public Image getVolatileOffscreenBuffer(Component c,
                                             int proposedWidth,int proposedHeight) {
+        RepaintManager delegate = getDelegate(c);
+        if (delegate != null) {
+            return delegate.getVolatileOffscreenBuffer(c, proposedWidth,
+                                                        proposedHeight);
+        }
         GraphicsConfiguration config = c.getGraphicsConfiguration();
         if (config == null) {
             config = GraphicsEnvironment.getLocalGraphicsEnvironment().
@@ -941,7 +985,7 @@
 
     private Image _getOffscreenBuffer(Component c, int proposedWidth, int proposedHeight) {
         Dimension maxSize = getDoubleBufferMaximumSize();
-        DoubleBufferInfo doubleBuffer = null;
+        DoubleBufferInfo doubleBuffer;
         int width, height;
 
         if (standardDoubleBuffer == null) {
@@ -1010,7 +1054,7 @@
         Iterator gcs = volatileMap.keySet().iterator();
         while (gcs.hasNext()) {
             GraphicsConfiguration gc = (GraphicsConfiguration)gcs.next();
-            VolatileImage image = (VolatileImage)volatileMap.get(gc);
+            VolatileImage image = volatileMap.get(gc);
             if (image.getWidth() > width || image.getHeight() > height) {
                 image.flush();
                 gcs.remove();
@@ -1178,7 +1222,7 @@
      */
     void beginPaint() {
         boolean multiThreadedPaint = false;
-        int paintDepth = 0;
+        int paintDepth;
         Thread currentThread = Thread.currentThread();
         synchronized(this) {
             paintDepth = this.paintDepth;
@@ -1550,4 +1594,11 @@
             prePaintDirtyRegions();
         }
     }
+    private RepaintManager getDelegate(Component c) {
+        RepaintManager delegate = SwingUtilities3.getDelegateRepaintManager(c);
+        if (this == delegate) {
+            delegate = null;
+        }
+        return delegate;
+    }
 }
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java
--- a/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java	Wed Jul 05 16:42:37 2017 +0200
@@ -79,7 +79,7 @@
      * sorted list should be reused if possible.
      */
     transient private Container cachedRoot;
-    transient private List cachedCycle;
+    transient private List cachedCycle;
 
     // Delegate our fitness test to ContainerOrder so that we only have to
     // code the algorithm once.
@@ -111,7 +111,7 @@
         return cycle;
     }
     private int getComponentIndex(List cycle, Component aComponent) {
-        int index = 0;
+        int index;
         try {
             index = Collections.binarySearch(cycle, aComponent, comparator);
         } catch (ClassCastException e) {
@@ -130,14 +130,14 @@
         return index;
     }
 
-    private void enumerateAndSortCycle(Container focusCycleRoot, List cycle) {
+    private void enumerateAndSortCycle(Container focusCycleRoot, List cycle) {
         if (focusCycleRoot.isShowing()) {
             enumerateCycle(focusCycleRoot, cycle);
             Collections.sort(cycle, comparator);
         }
     }
 
-    private void enumerateCycle(Container container, List cycle) {
+    private void enumerateCycle(Container container, List cycle) {
         if (!(container.isVisible() && container.isDisplayable())) {
             return;
         }
@@ -145,8 +145,7 @@
         cycle.add(container);
 
         Component[] components = container.getComponents();
-        for (int i = 0; i < components.length; i++) {
-            Component comp = components[i];
+        for (Component comp : components) {
             if (comp instanceof Container) {
                 Container cont = (Container)comp;
 
@@ -385,8 +384,8 @@
             return getLastComponent(aContainer);
         }
 
-        Component comp = null;
-        Component tryComp = null;
+        Component comp;
+        Component tryComp;
 
         for (index--; index>=0; index--) {
             comp = cycle.get(index);
@@ -442,8 +441,7 @@
         }
         if (log.isLoggable(Level.FINE)) log.fine("### Cycle is " + cycle);
 
-        for (int i = 0; i < cycle.size(); i++) {
-            Component comp = cycle.get(i);
+        for (Component comp : cycle) {
             if (accept(comp)) {
                 return comp;
             } else if (comp instanceof Container && comp != aContainer) {
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/SpringLayout.java
--- a/jdk/src/share/classes/javax/swing/SpringLayout.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/SpringLayout.java	Wed Jul 05 16:42:37 2017 +0200
@@ -185,11 +185,11 @@
  * @since       1.4
  */
 public class SpringLayout implements LayoutManager2 {
-    private Map componentConstraints = new HashMap();
+    private Map componentConstraints = new HashMap();
 
     private Spring cyclicReference = Spring.constant(Spring.UNSET);
-    private Set cyclicSprings;
-    private Set acyclicSprings;
+    private Set cyclicSprings;
+    private Set acyclicSprings;
 
 
     /**
@@ -415,8 +415,7 @@
             }
             if (!valid) {
                 String[] all = horizontal ? ALL_HORIZONTAL : ALL_VERTICAL;
-                for (int i = 0; i < all.length; i++) {
-                    String s = all[i];
+                for (String s : all) {
                     if (!history.contains(s)) {
                         setConstraint(s, null);
                     }
@@ -822,8 +821,7 @@
        /*pp*/ void reset() {
            Spring[] allSprings = {x, y, width, height, east, south,
                horizontalCenter, verticalCenter, baseline};
-           for (int i = 0; i < allSprings.length; i++) {
-               Spring s = allSprings[i];
+           for (Spring s : allSprings) {
                if (s != null) {
                    s.setValue(Spring.UNSET);
                }
@@ -881,8 +879,8 @@
     public SpringLayout() {}
 
     private void resetCyclicStatuses() {
-        cyclicSprings = new HashSet();
-        acyclicSprings = new HashSet();
+        cyclicSprings = new HashSet();
+        acyclicSprings = new HashSet();
     }
 
     private void setParent(Container p) {
@@ -1145,7 +1143,7 @@
      * @return      the constraints for the specified component
      */
     public Constraints getConstraints(Component c) {
-       Constraints result = (Constraints)componentConstraints.get(c);
+       Constraints result = componentConstraints.get(c);
        if (result == null) {
            if (c instanceof javax.swing.JComponent) {
                 Object cp = ((javax.swing.JComponent)c).getClientProperty(SpringLayout.class);
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/SwingUtilities.java
--- a/jdk/src/share/classes/javax/swing/SwingUtilities.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/SwingUtilities.java	Wed Jul 05 16:42:37 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -108,11 +108,8 @@
      * Return true if a contains b
      */
     public static final boolean isRectangleContainingRectangle(Rectangle a,Rectangle b) {
-        if (b.x >= a.x && (b.x + b.width) <= (a.x + a.width) &&
-            b.y >= a.y && (b.y + b.height) <= (a.y + a.height)) {
-            return true;
-        }
-        return false;
+        return b.x >= a.x && (b.x + b.width) <= (a.x + a.width) &&
+                b.y >= a.y && (b.y + b.height) <= (a.y + a.height);
     }
 
     /**
@@ -272,8 +269,7 @@
         }
         if (parent instanceof Container) {
             Component components[] = ((Container)parent).getComponents();
-            for (int i = 0 ; i < components.length ; i++) {
-                Component comp = components[i];
+            for (Component comp : components) {
                 if (comp != null && comp.isVisible()) {
                     Point loc = comp.getLocation();
                     if (comp instanceof Container) {
@@ -376,8 +372,8 @@
 
             do {
                 if(c instanceof JComponent) {
-                    x = ((JComponent)c).getX();
-                    y = ((JComponent)c).getY();
+                    x = c.getX();
+                    y = c.getY();
                 } else if(c instanceof java.applet.Applet ||
                           c instanceof java.awt.Window) {
                     try {
@@ -415,8 +411,8 @@
 
         do {
             if(c instanceof JComponent) {
-                x = ((JComponent)c).getX();
-                y = ((JComponent)c).getY();
+                x = c.getX();
+                y = c.getY();
             }  else if(c instanceof java.applet.Applet ||
                        c instanceof java.awt.Window) {
                 try {
@@ -974,12 +970,13 @@
 
         boolean textIsEmpty = (text == null) || text.equals("");
         int lsb = 0;
+        int rsb = 0;
         /* Unless both text and icon are non-null, we effectively ignore
          * the value of textIconGap.
          */
         int gap;
 
-        View v = null;
+        View v;
         if (textIsEmpty) {
             textR.width = textR.height = 0;
             text = "";
@@ -1015,7 +1012,7 @@
                 if (lsb < 0) {
                     textR.width -= lsb;
                 }
-                int rsb = SwingUtilities2.getRightSideBearing(c, fm, text);
+                rsb = SwingUtilities2.getRightSideBearing(c, fm, text);
                 if (rsb > 0) {
                     textR.width += rsb;
                 }
@@ -1118,6 +1115,11 @@
             // lsb is negative. Shift the x location so that the text is
             // visually drawn at the right location.
             textR.x -= lsb;
+
+            textR.width += lsb;
+        }
+        if (rsb > 0) {
+            textR.width -= rsb;
         }
 
         return text;
@@ -1242,8 +1244,8 @@
             children = ((Container)c).getComponents();
         }
         if (children != null) {
-            for(int i = 0; i < children.length; i++) {
-                updateComponentTreeUI0(children[i]);
+            for (Component child : children) {
+                updateComponentTreeUI0(child);
             }
         }
     }
@@ -1696,7 +1698,7 @@
      */
     public static void replaceUIActionMap(JComponent component,
                                           ActionMap uiActionMap) {
-        ActionMap map = component.getActionMap((uiActionMap != null));;
+        ActionMap map = component.getActionMap((uiActionMap != null));
 
         while (map != null) {
             ActionMap parent = map.getParent();
@@ -1764,8 +1766,7 @@
          */
         void installListeners() {
             Window[] windows = getOwnedWindows();
-            for (int ind = 0; ind < windows.length; ind++){
-                Window window = windows[ind];
+            for (Window window : windows) {
                 if (window != null) {
                     window.removeWindowListener(this);
                     window.addWindowListener(this);
@@ -1780,8 +1781,7 @@
         public void windowClosed(WindowEvent e) {
             synchronized(getTreeLock()) {
                 Window[] windows = getOwnedWindows();
-                for (int ind = 0; ind < windows.length; ind++) {
-                    Window window = windows[ind];
+                for (Window window : windows) {
                     if (window != null) {
                         if (window.isDisplayable()) {
                             return;
@@ -1869,7 +1869,7 @@
     }
 
 
-    static Class loadSystemClass(String className) throws ClassNotFoundException {
+    static Class loadSystemClass(String className) throws ClassNotFoundException {
         return Class.forName(className, true, Thread.currentThread().
                              getContextClassLoader());
     }
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/Timer.java
--- a/jdk/src/share/classes/javax/swing/Timer.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/Timer.java	Wed Jul 05 16:42:37 2017 +0200
@@ -270,8 +270,7 @@
      * @since 1.4
      */
     public ActionListener[] getActionListeners() {
-        return (ActionListener[])listenerList.getListeners(
-                ActionListener.class);
+        return listenerList.getListeners(ActionListener.class);
     }
 
 
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/TimerQueue.java
--- a/jdk/src/share/classes/javax/swing/TimerQueue.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/TimerQueue.java	Wed Jul 05 16:42:37 2017 +0200
@@ -31,6 +31,7 @@
 
 import java.util.*;
 import java.util.concurrent.*;
+import java.util.concurrent.locks.*;
 import java.util.concurrent.atomic.AtomicLong;
 import sun.awt.AppContext;
 
@@ -52,7 +53,8 @@
         new StringBuffer("TimerQueue.expiredTimersKey");
 
     private final DelayQueue queue;
-    volatile boolean running;
+    private volatile boolean running;
+    private final Lock runningLock;
 
     /* Lock object used in place of class object for synchronization.
      * (4187686)
@@ -69,7 +71,8 @@
         super();
         queue = new DelayQueue();
         // Now start the TimerQueue thread.
-        start();
+        runningLock = new ReentrantLock();
+        startIfNeeded();
     }
 
 
@@ -87,33 +90,30 @@
     }
 
 
-    synchronized void start() {
-        if (running) {
-            throw new RuntimeException("Can't start a TimerQueue " +
-                                       "that is already running");
-        }
-        else {
-            final ThreadGroup threadGroup =
-                AppContext.getAppContext().getThreadGroup();
-            java.security.AccessController.doPrivileged(
-                new java.security.PrivilegedAction() {
-                public Object run() {
-                    Thread timerThread = new Thread(threadGroup, TimerQueue.this,
-                                                    "TimerQueue");
-                    timerThread.setDaemon(true);
-                    timerThread.setPriority(Thread.NORM_PRIORITY);
-                    timerThread.start();
-                    return null;
-                }
-            });
-            running = true;
+    void startIfNeeded() {
+        if (! running) {
+            runningLock.lock();
+            try {
+                final ThreadGroup threadGroup =
+                    AppContext.getAppContext().getThreadGroup();
+                java.security.AccessController.doPrivileged(
+                    new java.security.PrivilegedAction() {
+                    public Object run() {
+                        Thread timerThread = new Thread(threadGroup, TimerQueue.this,
+                                                        "TimerQueue");
+                        timerThread.setDaemon(true);
+                        timerThread.setPriority(Thread.NORM_PRIORITY);
+                        timerThread.start();
+                        return null;
+                    }
+                });
+                running = true;
+            } finally {
+                runningLock.unlock();
+            }
         }
     }
 
-     synchronized void stop() {
-         running = false;
-     }
-
     void addTimer(Timer timer, long delayMillis) {
         timer.getLock().lock();
         try {
@@ -164,6 +164,7 @@
 
 
     public void run() {
+        runningLock.lock();
         try {
             while (running) {
                 try {
@@ -195,14 +196,14 @@
             }
         }
         catch (ThreadDeath td) {
-            synchronized (this) {
-                running = false;
-                // Mark all the timers we contain as not being queued.
-                for (DelayedTimer delayedTimer : queue) {
-                    delayedTimer.getTimer().cancelEvent();
-                }
-                throw td;
+            // Mark all the timers we contain as not being queued.
+            for (DelayedTimer delayedTimer : queue) {
+                delayedTimer.getTimer().cancelEvent();
             }
+            throw td;
+        } finally {
+            running = false;
+            runningLock.unlock();
         }
     }
 
@@ -225,7 +226,7 @@
     /**
      * Returns nanosecond time offset by origin
      */
-    private final static long now() {
+    private static long now() {
         return System.nanoTime() - NANO_ORIGIN;
     }
 
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/UIDefaults.java
--- a/jdk/src/share/classes/javax/swing/UIDefaults.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/UIDefaults.java	Wed Jul 05 16:42:37 2017 +0200
@@ -72,11 +72,11 @@
  */
 public class UIDefaults extends Hashtable
 {
-    private static final Object PENDING = new String("Pending");
+    private static final Object PENDING = "Pending";
 
     private SwingPropertyChangeSupport changeSupport;
 
-    private Vector resourceBundles;
+    private Vector resourceBundles;
 
     private Locale defaultLocale = Locale.getDefault();
 
@@ -86,7 +86,7 @@
      * Access to this should be done while holding a lock on the
      * UIDefaults, eg synchronized(this).
      */
-    private Map resourceCache;
+    private Map> resourceCache;
 
     /**
      * Creates an empty defaults table.
@@ -106,7 +106,7 @@
      */
     public UIDefaults(int initialCapacity, float loadFactor) {
         super(initialCapacity, loadFactor);
-        resourceCache = new HashMap();
+        resourceCache = new HashMap>();
     }
 
 
@@ -281,24 +281,24 @@
             if( defaultLocale == null )
                 return null;
             else
-                l = (Locale)defaultLocale;
+                l = defaultLocale;
         }
 
         synchronized(this) {
-            return getResourceCache(l).get((String)key);
+            return getResourceCache(l).get(key);
         }
     }
 
     /**
      * Returns a Map of the known resources for the given locale.
      */
-    private Map getResourceCache(Locale l) {
-        Map values = (Map)resourceCache.get(l);
+    private Map getResourceCache(Locale l) {
+        Map values = resourceCache.get(l);
 
         if (values == null) {
-            values = new HashMap();
+            values = new HashMap();
             for (int i=resourceBundles.size()-1; i >= 0; i--) {
-                String bundleName = (String)resourceBundles.get(i);
+                String bundleName = resourceBundles.get(i);
                 try {
                     Control c = CoreResourceBundleControl.getRBControlInstance(bundleName);
                     ResourceBundle b;
@@ -751,7 +751,7 @@
         Object cl = get("ClassLoader");
         ClassLoader uiClassLoader =
             (cl != null) ? (ClassLoader)cl : target.getClass().getClassLoader();
-        Class uiClass = getUIClass(target.getUIClassID(), uiClassLoader);
+        Class uiClass = getUIClass(target.getUIClassID(), uiClassLoader);
         Object uiObject = null;
 
         if (uiClass == null) {
@@ -761,8 +761,7 @@
             try {
                 Method m = (Method)get(uiClass);
                 if (m == null) {
-                    Class acClass = javax.swing.JComponent.class;
-                    m = uiClass.getMethod("createUI", new Class[]{acClass});
+                    m = uiClass.getMethod("createUI", new Class[]{JComponent.class});
                     put(uiClass, m);
                 }
                 uiObject = MethodUtil.invoke(m, null, new Object[]{target});
@@ -862,7 +861,7 @@
             return;
         }
         if( resourceBundles == null ) {
-            resourceBundles = new Vector(5);
+            resourceBundles = new Vector(5);
         }
         if (!resourceBundles.contains(bundleName)) {
             resourceBundles.add( bundleName );
@@ -1064,7 +1063,7 @@
             className = c;
             methodName = m;
             if (o != null) {
-                args = (Object[])o.clone();
+                args = o.clone();
             }
         }
 
@@ -1079,10 +1078,10 @@
             // In order to pick up the security policy in effect at the
             // time of creation we use a doPrivileged with the
             // AccessControlContext that was in place when this was created.
-            return AccessController.doPrivileged(new PrivilegedAction() {
+            return AccessController.doPrivileged(new PrivilegedAction() {
                 public Object run() {
                     try {
-                        Class c;
+                        Class c;
                         Object cl;
                         // See if we should use a separate ClassLoader
                         if (table == null || !((cl = table.get("ClassLoader"))
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/UIManager.java
--- a/jdk/src/share/classes/javax/swing/UIManager.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/UIManager.java	Wed Jul 05 16:42:37 2017 +0200
@@ -191,7 +191,7 @@
         MultiUIDefaults multiUIDefaults = new MultiUIDefaults(tables);
         LookAndFeel lookAndFeel;
         LookAndFeel multiLookAndFeel = null;
-        Vector auxLookAndFeels = null;
+        Vector auxLookAndFeels = null;
         SwingPropertyChangeSupport changeSupport;
 
         UIDefaults getLookAndFeelDefaults() { return tables[0]; }
@@ -378,7 +378,7 @@
     private static LookAndFeelInfo[] installedLAFs;
 
     static {
-        ArrayList iLAFs = new ArrayList(4);
+        ArrayList iLAFs = new ArrayList(4);
         iLAFs.add(new LookAndFeelInfo(
                       "Metal", "javax.swing.plaf.metal.MetalLookAndFeel"));
         iLAFs.add(new LookAndFeelInfo("CDE/Motif",
@@ -400,8 +400,7 @@
             iLAFs.add(new LookAndFeelInfo("GTK+",
                   "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"));
         }
-        installedLAFs = (LookAndFeelInfo[])iLAFs.toArray(
-                        new LookAndFeelInfo[iLAFs.size()]);
+        installedLAFs = iLAFs.toArray(new LookAndFeelInfo[iLAFs.size()]);
     }
 
 
@@ -640,7 +639,7 @@
      * @see #getSystemLookAndFeelClassName
      */
     public static String getCrossPlatformLookAndFeelClassName() {
-        String laf = (String)AccessController.doPrivileged(
+        String laf = AccessController.doPrivileged(
                              new GetPropertyAction("swing.crossplatformlaf"));
         if (laf != null) {
             return laf;
@@ -1079,9 +1078,9 @@
             // for that.
             return;
         }
-        Vector v = getLAFState().auxLookAndFeels;
+        Vector v = getLAFState().auxLookAndFeels;
         if (v == null) {
-            v = new Vector();
+            v = new Vector();
         }
 
         if (!v.contains(laf)) {
@@ -1115,7 +1114,7 @@
 
         boolean result;
 
-        Vector v = getLAFState().auxLookAndFeels;
+        Vector v = getLAFState().auxLookAndFeels;
         if ((v == null) || (v.size() == 0)) {
             return false;
         }
@@ -1151,14 +1150,14 @@
     static public LookAndFeel[] getAuxiliaryLookAndFeels() {
         maybeInitialize();
 
-        Vector v = getLAFState().auxLookAndFeels;
+        Vector v = getLAFState().auxLookAndFeels;
         if ((v == null) || (v.size() == 0)) {
             return null;
         }
         else {
             LookAndFeel[] rv = new LookAndFeel[v.size()];
             for (int i = 0; i < rv.length; i++) {
-                rv[i] = (LookAndFeel)v.elementAt(i);
+                rv[i] = v.elementAt(i);
             }
             return rv;
         }
@@ -1225,7 +1224,7 @@
             final Properties props = new Properties();
 
             java.security.AccessController.doPrivileged(
-                new java.security.PrivilegedAction() {
+                new java.security.PrivilegedAction() {
                 public Object run() {
                     try {
                         File file = new File(makeSwingPropertiesFilename());
@@ -1284,7 +1283,7 @@
          * property.  For example given "swing.installedlafs=motif,windows"
          * lafs = {"motif", "windows"}.
          */
-        Vector lafs = new Vector();
+        Vector lafs = new Vector();
         StringTokenizer st = new StringTokenizer(ilafsString, ",", false);
         while (st.hasMoreTokens()) {
             lafs.addElement(st.nextToken());
@@ -1294,9 +1293,8 @@
          * list.  If they both exist then add a LookAndFeelInfo to
          * the installedLafs array.
          */
-        Vector ilafs = new Vector(lafs.size());
-        for(int i = 0; i < lafs.size(); i++) {
-            String laf = (String)lafs.elementAt(i);
+        Vector ilafs = new Vector(lafs.size());
+        for (String laf : lafs) {
             String name = swingProps.getProperty(makeInstalledLAFKey(laf, "name"), laf);
             String cls = swingProps.getProperty(makeInstalledLAFKey(laf, "class"));
             if (cls != null) {
@@ -1306,7 +1304,7 @@
 
         installedLAFs = new LookAndFeelInfo[ilafs.size()];
         for(int i = 0; i < ilafs.size(); i++) {
-            installedLAFs[i] = (LookAndFeelInfo)(ilafs.elementAt(i));
+            installedLAFs[i] = ilafs.elementAt(i);
         }
     }
 
@@ -1350,7 +1348,7 @@
             return;
         }
 
-        Vector auxLookAndFeels = new Vector();
+        Vector auxLookAndFeels = new Vector();
 
         StringTokenizer p = new StringTokenizer(auxLookAndFeelNames,",");
         String factoryName;
@@ -1451,7 +1449,7 @@
                         Component c = e.getComponent();
 
                         if ((!(c instanceof JComponent) ||
-                             (c != null && !((JComponent)c).isEnabled())) &&
+                             (c != null && !c.isEnabled())) &&
                                 JComponent.KeyboardState.shouldProcess(e) &&
                                 SwingUtilities.processKeyBindings(e)) {
                             e.consume();
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/border/CompoundBorder.java
--- a/jdk/src/share/classes/javax/swing/border/CompoundBorder.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/border/CompoundBorder.java	Wed Jul 05 16:42:37 2017 +0200
@@ -79,10 +79,13 @@
     }
 
     /**
-     * Returns whether or not this compound border is opaque.
-     * Returns true if both the inside and outside borders are
-     * non-null and opaque; returns false otherwise.
+     * Returns whether or not the compound border is opaque.
+     *
+     * @return {@code true} if the inside and outside borders
+     *         are each either {@code null} or opaque;
+     *         or {@code false} otherwise
      */
+    @Override
     public boolean isBorderOpaque() {
         return (outsideBorder == null || outsideBorder.isBorderOpaque()) &&
                (insideBorder == null || insideBorder.isBorderOpaque());
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/AbstractColorChooserPanel.java
--- a/jdk/src/share/classes/javax/swing/colorchooser/AbstractColorChooserPanel.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/colorchooser/AbstractColorChooserPanel.java	Wed Jul 05 16:42:37 2017 +0200
@@ -160,7 +160,9 @@
       *         is editing
       */
     public ColorSelectionModel getColorSelectionModel() {
-        return chooser.getSelectionModel();
+        return (this.chooser != null)
+                ? this.chooser.getSelectionModel()
+                : null;
     }
 
     /**
@@ -168,7 +170,17 @@
      * @return the Color that is selected
      */
     protected Color getColorFromModel() {
-        return getColorSelectionModel().getSelectedColor();
+        ColorSelectionModel model = getColorSelectionModel();
+        return (model != null)
+                ? model.getSelectedColor()
+                : null;
+    }
+
+    void setSelectedColor(Color color) {
+        ColorSelectionModel model = getColorSelectionModel();
+        if (model != null) {
+            model.setSelectedColor(color);
+        }
     }
 
     /**
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java
--- a/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java	Fri Oct 10 13:29:11 2008 -0700
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserComponentFactory.java	Wed Jul 05 16:42:37 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright 1998-2001 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,9 +25,7 @@
 
 package javax.swing.colorchooser;
 
-import javax.swing.*;
-
-
+import javax.swing.JComponent;
 
 /**
  * A class designed to produce preconfigured "accessory" objects to
@@ -49,16 +47,17 @@
 
     private ColorChooserComponentFactory() { } // can't instantiate
 
-
     public static AbstractColorChooserPanel[] getDefaultChooserPanels() {
-        AbstractColorChooserPanel[] choosers = { new DefaultSwatchChooserPanel(),
-                                                 new DefaultHSBChooserPanel(),
-                                                 new DefaultRGBChooserPanel() };
-        return choosers;
+        return new AbstractColorChooserPanel[] {
+                new DefaultSwatchChooserPanel(),
+                new ColorChooserPanel(new ColorModelHSV()),
+                new ColorChooserPanel(new ColorModelHSL()),
+                new ColorChooserPanel(new ColorModel()),
+                new ColorChooserPanel(new ColorModelCMYK()),
+        };
     }
 
     public static JComponent getPreviewPanel() {
         return new DefaultPreviewPanel();
     }
-
 }
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/ColorChooserPanel.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorChooserPanel.java	Wed Jul 05 16:42:37 2017 +0200
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.swing.colorchooser;
+
+import java.awt.Color;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import javax.swing.Icon;
+import javax.swing.JComponent;
+import javax.swing.JFormattedTextField;
+import javax.swing.JLabel;
+import javax.swing.SwingConstants;
+
+final class ColorChooserPanel extends AbstractColorChooserPanel implements PropertyChangeListener {
+
+    private static final int MASK = 0xFF000000;
+    private final ColorModel model;
+    private final ColorPanel panel;
+    private final DiagramComponent slider;
+    private final DiagramComponent diagram;
+    private final JFormattedTextField text;
+    private final JLabel label;
+
+    ColorChooserPanel(ColorModel model) {
+        this.model = model;
+        this.panel = new ColorPanel(this.model);
+        this.slider = new DiagramComponent(this.panel, false);
+        this.diagram = new DiagramComponent(this.panel, true);
+        this.text = new JFormattedTextField();
+        this.label = new JLabel(null, null, SwingConstants.RIGHT);
+        ValueFormatter.init(6, true, this.text);
+    }
+
+    @Override
+    public void updateChooser() {
+        Color color = getColorFromModel();
+        if (color != null) {
+            this.panel.setColor(color);
+            this.text.setValue(Integer.valueOf(color.getRGB()));
+            this.slider.repaint();
+            this.diagram.repaint();
+        }
+    }
+
+    @Override
+    protected void buildChooser() {
+        if (0 == getComponentCount()) {
+            setLayout(new GridBagLayout());
+
+            GridBagConstraints gbc = new GridBagConstraints();
+
+            gbc.gridx = 3;
+            gbc.gridwidth = 2;
+            gbc.weighty = 1.0;
+            gbc.anchor = GridBagConstraints.NORTH;
+            gbc.fill = GridBagConstraints.HORIZONTAL;
+            gbc.insets.top = 10;
+            gbc.insets.right = 10;
+            add(this.panel, gbc);
+
+            gbc.gridwidth = 1;
+            gbc.weightx = 1.0;
+            gbc.weighty = 0.0;
+            gbc.anchor = GridBagConstraints.CENTER;
+            gbc.insets.right = 5;
+            gbc.insets.bottom = 10;
+            add(this.label, gbc);
+
+            gbc.gridx = 4;
+            gbc.weightx = 0.0;
+            gbc.insets.right = 10;
+            add(this.text, gbc);
+
+            gbc.gridx = 2;
+            gbc.gridheight = 2;
+            gbc.anchor = GridBagConstraints.NORTH;
+            gbc.ipadx = this.text.getPreferredSize().height;
+            gbc.ipady = getPreferredSize().height;
+            add(this.slider, gbc);
+
+            gbc.gridx = 1;
+            gbc.insets.left = 10;
+            gbc.ipadx = gbc.ipady;
+            add(this.diagram, gbc);
+
+            this.label.setLabelFor(this.text);
+            this.text.addPropertyChangeListener("value", this); // NON-NLS: the property name
+            this.slider.setBorder(this.text.getBorder());
+            this.diagram.setBorder(this.text.getBorder());
+
+            setInheritsPopupMenu(this, true); // CR:4966112
+        }
+        String label = this.model.getText(this, "HexCode"); // NON-NLS: suffix
+        boolean visible = label != null;
+        this.text.setVisible(visible);
+        this.label.setVisible(visible);
+        if (visible) {
+            this.label.setText(label);
+            int mnemonic = this.model.getInteger(this, "HexCodeMnemonic"); // NON-NLS: suffix
+            if (mnemonic > 0) {
+                this.label.setDisplayedMnemonic(mnemonic);
+                mnemonic = this.model.getInteger(this, "HexCodeMnemonicIndex"); // NON-NLS: suffix
+                if (mnemonic >= 0) {
+                    this.label.setDisplayedMnemonicIndex(mnemonic);
+                }
+            }
+        }
+        this.panel.buildPanel();
+    }
+
+    @Override
+    public String getDisplayName() {
+        return this.model.getText(this, "Name"); // NON-NLS: suffix
+    }
+
+    @Override
+    public int getMnemonic() {
+        return this.model.getInteger(this, "Mnemonic"); // NON-NLS: suffix
+    }
+
+    @Override
+    public int getDisplayedMnemonicIndex() {
+        return this.model.getInteger(this, "DisplayedMnemonicIndex"); // NON-NLS: suffix
+    }
+
+    @Override
+    public Icon getSmallDisplayIcon() {
+        return null;
+    }
+
+    @Override
+    public Icon getLargeDisplayIcon() {
+        return null;
+    }
+
+    public void propertyChange(PropertyChangeEvent event) {
+        ColorSelectionModel model = getColorSelectionModel();
+        if (model != null) {
+            Object object = event.getNewValue();
+            if (object instanceof Integer) {
+                int value = MASK & model.getSelectedColor().getRGB() | (Integer) object;
+                model.setSelectedColor(new Color(value, true));
+            }
+        }
+        this.text.selectAll();
+    }
+
+    /**
+     * Allows to show context popup for all components recursively.
+     *
+     * @param component  the root component of the tree
+     * @param value      whether or not the popup menu is inherited
+     */
+    private static void setInheritsPopupMenu(JComponent component, boolean value) {
+        component.setInheritsPopupMenu(value);
+        for (Object object : component.getComponents()) {
+            if (object instanceof JComponent) {
+                setInheritsPopupMenu((JComponent) object, value);
+            }
+        }
+    }
+}
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/ColorModel.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModel.java	Wed Jul 05 16:42:37 2017 +0200
@@ -0,0 +1,102 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.swing.colorchooser;
+
+import java.awt.Component;
+import javax.swing.UIManager;
+
+class ColorModel {
+
+    private final String prefix;
+    private final String[] labels;
+
+    ColorModel(String name, String... labels) {
+        this.prefix = "ColorChooser." + name; // NON-NLS: default prefix
+        this.labels = labels;
+    }
+
+    ColorModel() {
+        this("rgb", "Red", "Green", "Blue", "Alpha"); // NON-NLS: components
+    }
+
+    void setColor(int color, float[] model) {
+        model[0] = normalize(color >> 16);
+        model[1] = normalize(color >> 8);
+        model[2] = normalize(color);
+        model[3] = normalize(color >> 24);
+    }
+
+    int getColor(float[] model) {
+        return to8bit(model[2]) | (to8bit(model[1]) << 8) | (to8bit(model[0]) << 16) | (to8bit(model[3]) << 24);
+    }
+
+    int getCount() {
+        return this.labels.length;
+    }
+
+    int getMinimum(int index) {
+        return 0;
+    }
+
+    int getMaximum(int index) {
+        return 255;
+    }
+
+    float getDefault(int index) {
+        return 0.0f;
+    }
+
+    final String getLabel(Component component, int index) {
+        return getText(component, this.labels[index]);
+    }
+
+    private static float normalize(int value) {
+        return (float) (value & 0xFF) / 255.0f;
+    }
+
+    private static int to8bit(float value) {
+        return (int) (255.0f * value);
+    }
+
+    final String getText(Component component, String suffix) {
+        return UIManager.getString(this.prefix + suffix + "Text", component.getLocale()); // NON-NLS: default postfix
+    }
+
+    final int getInteger(Component component, String suffix) {
+        Object value = UIManager.get(this.prefix + suffix, component.getLocale());
+        if (value instanceof Integer) {
+            return (Integer) value;
+        }
+        if (value instanceof String) {
+            try {
+                return Integer.parseInt((String) value);
+            }
+            catch (NumberFormatException exception) {
+            }
+        }
+        return -1;
+    }
+}
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/ColorModelCMYK.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelCMYK.java	Wed Jul 05 16:42:37 2017 +0200
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.swing.colorchooser;
+
+final class ColorModelCMYK extends ColorModel {
+
+    ColorModelCMYK() {
+        super("cmyk", "Cyan", "Magenta", "Yellow", "Black", "Alpha"); // NON-NLS: components
+    }
+
+    @Override
+    void setColor(int color, float[] space) {
+        super.setColor(color, space);
+        space[4] = space[3];
+        RGBtoCMYK(space, space);
+    }
+
+    @Override
+    int getColor(float[] space) {
+        CMYKtoRGB(space, space);
+        space[3] = space[4];
+        return super.getColor(space);
+    }
+
+    /**
+     * Converts CMYK components of a color to a set of RGB components.
+     *
+     * @param cmyk  a float array with length equal to
+     *              the number of CMYK components
+     * @param rgb   a float array with length of at least 3
+     *              that contains RGB components of a color
+     * @return a float array that contains RGB components
+     */
+    private static float[] CMYKtoRGB(float[] cmyk, float[] rgb) {
+        if (rgb == null) {
+            rgb = new float[3];
+        }
+        rgb[0] = 1.0f + cmyk[0] * cmyk[3] - cmyk[3] - cmyk[0];
+        rgb[1] = 1.0f + cmyk[1] * cmyk[3] - cmyk[3] - cmyk[1];
+        rgb[2] = 1.0f + cmyk[2] * cmyk[3] - cmyk[3] - cmyk[2];
+        return rgb;
+    }
+
+    /**
+     * Converts RGB components of a color to a set of CMYK components.
+     *
+     * @param rgb   a float array with length of at least 3
+     *              that contains RGB components of a color
+     * @param cmyk  a float array with length equal to
+     *              the number of CMYK components
+     * @return a float array that contains CMYK components
+     */
+    private static float[] RGBtoCMYK(float[] rgb, float[] cmyk) {
+        if (cmyk == null) {
+            cmyk = new float[4];
+        }
+        float max = ColorModelHSL.max(rgb[0], rgb[1], rgb[2]);
+        if (max > 0.0f) {
+            cmyk[0] = 1.0f - rgb[0] / max;
+            cmyk[1] = 1.0f - rgb[1] / max;
+            cmyk[2] = 1.0f - rgb[2] / max;
+        }
+        else {
+            cmyk[0] = 0.0f;
+            cmyk[1] = 0.0f;
+            cmyk[2] = 0.0f;
+        }
+        cmyk[3] = 1.0f - max;
+        return cmyk;
+    }
+}
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSL.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSL.java	Wed Jul 05 16:42:37 2017 +0200
@@ -0,0 +1,188 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.swing.colorchooser;
+
+final class ColorModelHSL extends ColorModel {
+
+    ColorModelHSL() {
+        super("hsl", "Hue", "Saturation", "Lightness", "Transparency"); // NON-NLS: components
+    }
+
+    @Override
+    void setColor(int color, float[] space) {
+        super.setColor(color, space);
+        RGBtoHSL(space, space);
+        space[3] = 1.0f - space[3];
+    }
+
+    @Override
+    int getColor(float[] space) {
+        space[3] = 1.0f - space[3];
+        HSLtoRGB(space, space);
+        return super.getColor(space);
+    }
+
+    @Override
+    int getMaximum(int index) {
+        return (index == 0) ? 360 : 100;
+    }
+
+    @Override
+    float getDefault(int index) {
+        return (index == 0) ? -1.0f : (index == 2) ? 0.5f : 1.0f;
+    }
+
+    /**
+     * Converts HSL components of a color to a set of RGB components.
+     *
+     * @param hsl  a float array with length equal to
+     *             the number of HSL components
+     * @param rgb  a float array with length of at least 3
+     *             that contains RGB components of a color
+     * @return a float array that contains RGB components
+     */
+    private static float[] HSLtoRGB(float[] hsl, float[] rgb) {
+        if (rgb == null) {
+            rgb = new float[3];
+        }
+        float hue = hsl[0];
+        float saturation = hsl[1];
+        float lightness = hsl[2];
+
+        if (saturation > 0.0f) {
+            hue = (hue < 1.0f) ? hue * 6.0f : 0.0f;
+            float q = lightness + saturation * ((lightness > 0.5f) ? 1.0f - lightness : lightness);
+            float p = 2.0f * lightness - q;
+            rgb[0]= normalize(q, p, (hue < 4.0f) ? (hue + 2.0f) : (hue - 4.0f));
+            rgb[1]= normalize(q, p, hue);
+            rgb[2]= normalize(q, p, (hue < 2.0f) ? (hue + 4.0f) : (hue - 2.0f));
+        }
+        else {
+            rgb[0] = lightness;
+            rgb[1] = lightness;
+            rgb[2] = lightness;
+        }
+        return rgb;
+    }
+
+    /**
+     * Converts RGB components of a color to a set of HSL components.
+     *
+     * @param rgb  a float array with length of at least 3
+     *             that contains RGB components of a color
+     * @param hsl  a float array with length equal to
+     *             the number of HSL components
+     * @return a float array that contains HSL components
+     */
+    private static float[] RGBtoHSL(float[] rgb, float[] hsl) {
+        if (hsl == null) {
+            hsl = new float[3];
+        }
+        float max = max(rgb[0], rgb[1], rgb[2]);
+        float min = min(rgb[0], rgb[1], rgb[2]);
+
+        float summa = max + min;
+        float saturation = max - min;
+        if (saturation > 0.0f) {
+            saturation /= (summa > 1.0f)
+                    ? 2.0f - summa
+                    : summa;
+        }
+        hsl[0] = getHue(rgb[0], rgb[1], rgb[2], max, min);
+        hsl[1] = saturation;
+        hsl[2] = summa / 2.0f;
+        return hsl;
+    }
+
+    /**
+     * Returns the smaller of three color components.
+     *
+     * @param red    the red component of the color
+     * @param green  the green component of the color
+     * @param blue   the blue component of the color
+     * @return the smaller of {@code red}, {@code green} and {@code blue}
+     */
+    static float min(float red, float green, float blue) {
+        float min = (red < green) ? red : green;
+        return (min < blue) ? min : blue;
+    }
+
+    /**
+     * Returns the larger of three color components.
+     *
+     * @param red    the red component of the color
+     * @param green  the green component of the color
+     * @param blue   the blue component of the color
+     * @return the larger of {@code red}, {@code green} and {@code blue}
+     */
+    static float max(float red, float green, float blue) {
+        float max = (red > green) ? red : green;
+        return (max > blue) ? max : blue;
+    }
+
+    /**
+     * Calculates the hue component for HSL and HSV color spaces.
+     *
+     * @param red    the red component of the color
+     * @param green  the green component of the color
+     * @param blue   the blue component of the color
+     * @param max    the larger of {@code red}, {@code green} and {@code blue}
+     * @param min    the smaller of {@code red}, {@code green} and {@code blue}
+     * @return the hue component
+     */
+    static float getHue(float red, float green, float blue, float max, float min) {
+        float hue = max - min;
+        if (hue > 0.0f) {
+            if (max == red) {
+                hue = (green - blue) / hue;
+                if (hue < 0.0f) {
+                    hue += 6.0f;
+                }
+            }
+            else if (max == green) {
+                hue = 2.0f + (blue - red) / hue;
+            }
+            else /*max == blue*/ {
+                hue = 4.0f + (red - green) / hue;
+            }
+            hue /= 6.0f;
+        }
+        return hue;
+    }
+
+    private static float normalize(float q, float p, float color) {
+        if (color < 1.0f) {
+            return p + (q - p) * color;
+        }
+        if (color < 3.0f) {
+            return q;
+        }
+        if (color < 4.0f) {
+            return p + (q - p) * (4.0f - color);
+        }
+        return p;
+    }
+}
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSV.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorModelHSV.java	Wed Jul 05 16:42:37 2017 +0200
@@ -0,0 +1,138 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.swing.colorchooser;
+
+final class ColorModelHSV extends ColorModel {
+
+    ColorModelHSV() {
+        super("hsv", "Hue", "Saturation", "Value", "Transparency"); // NON-NLS: components
+    }
+
+    @Override
+    void setColor(int color, float[] space) {
+        super.setColor(color, space);
+        RGBtoHSV(space, space);
+        space[3] = 1.0f - space[3];
+    }
+
+    @Override
+    int getColor(float[] space) {
+        space[3] = 1.0f - space[3];
+        HSVtoRGB(space, space);
+        return super.getColor(space);
+    }
+
+    @Override
+    int getMaximum(int index) {
+        return (index == 0) ? 360 : 100;
+    }
+
+    @Override
+    float getDefault(int index) {
+        return (index == 0) ? -1.0f : 1.0f;
+    }
+
+    /**
+     * Converts HSV components of a color to a set of RGB components.
+     *
+     * @param hsv  a float array with length equal to
+     *             the number of HSV components
+     * @param rgb  a float array with length of at least 3
+     *             that contains RGB components of a color
+     * @return a float array that contains RGB components
+     */
+    private static float[] HSVtoRGB(float[] hsv, float[] rgb) {
+        if (rgb == null) {
+            rgb = new float[3];
+        }
+        float hue = hsv[0];
+        float saturation = hsv[1];
+        float value = hsv[2];
+
+        rgb[0] = value;
+        rgb[1] = value;
+        rgb[2] = value;
+
+        if (saturation > 0.0f) {
+            hue = (hue < 1.0f) ? hue * 6.0f : 0.0f;
+            int integer = (int) hue;
+            float f = hue - (float) integer;
+            switch (integer) {
+                case 0:
+                    rgb[1] *= 1.0f - saturation * (1.0f - f);
+                    rgb[2] *= 1.0f - saturation;
+                    break;
+                case 1:
+                    rgb[0] *= 1.0f - saturation * f;
+                    rgb[2] *= 1.0f - saturation;
+                    break;
+                case 2:
+                    rgb[0] *= 1.0f - saturation;
+                    rgb[2] *= 1.0f - saturation * (1.0f - f);
+                    break;
+                case 3:
+                    rgb[0] *= 1.0f - saturation;
+                    rgb[1] *= 1.0f - saturation * f;
+                    break;
+                case 4:
+                    rgb[0] *= 1.0f - saturation * (1.0f - f);
+                    rgb[1] *= 1.0f - saturation;
+                    break;
+                case 5:
+                    rgb[1] *= 1.0f - saturation;
+                    rgb[2] *= 1.0f - saturation * f;
+                    break;
+            }
+        }
+        return rgb;
+    }
+
+    /**
+     * Converts RGB components of a color to a set of HSV components.
+     *
+     * @param rgb  a float array with length of at least 3
+     *             that contains RGB components of a color
+     * @param hsv  a float array with length equal to
+     *             the number of HSV components
+     * @return a float array that contains HSV components
+     */
+    private static float[] RGBtoHSV(float[] rgb, float[] hsv) {
+        if (hsv == null) {
+            hsv = new float[3];
+        }
+        float max = ColorModelHSL.max(rgb[0], rgb[1], rgb[2]);
+        float min = ColorModelHSL.min(rgb[0], rgb[1], rgb[2]);
+
+        float saturation = max - min;
+        if (saturation > 0.0f) {
+            saturation /= max;
+        }
+        hsv[0] = ColorModelHSL.getHue(rgb[0], rgb[1], rgb[2], max, min);
+        hsv[1] = saturation;
+        hsv[2] = max;
+        return hsv;
+    }
+}
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/ColorPanel.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/javax/swing/colorchooser/ColorPanel.java	Wed Jul 05 16:42:37 2017 +0200
@@ -0,0 +1,210 @@
+/*
+ * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javax.swing.colorchooser;
+
+import java.awt.Color;
+import java.awt.ContainerOrderFocusTraversalPolicy;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.Insets;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import javax.swing.ButtonGroup;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JRadioButton;
+import javax.swing.border.EmptyBorder;
+
+final class ColorPanel extends JPanel implements ActionListener {
+
+    private final SlidingSpinner[] spinners = new SlidingSpinner[5];
+    private final float[] values = new float[this.spinners.length];
+
+    private final ColorModel model;
+    private Color color;
+    private int x = 1;
+    private int y = 2;
+    private int z;
+
+    ColorPanel(ColorModel model) {
+        super(new GridBagLayout());
+
+        GridBagConstraints gbc = new GridBagConstraints();
+        gbc.fill = GridBagConstraints.HORIZONTAL;
+
+        gbc.gridx = 1;
+        ButtonGroup group = new ButtonGroup();
+        EmptyBorder border = null;
+        for (int i = 0; i < this.spinners.length; i++) {
+            if (i < 3) {
+                JRadioButton button = new JRadioButton();
+                if (i == 0) {
+                    Insets insets = button.getInsets();
+                    insets.left = button.getPreferredSize().width;
+                    border = new EmptyBorder(insets);
+                    button.setSelected(true);
+                    gbc.insets.top = 5;
+                }
+                add(button, gbc);
+                group.add(button);
+                button.setActionCommand(Integer.toString(i));
+                button.addActionListener(this);
+                this.spinners[i] = new SlidingSpinner(this, button);
+            }
+            else {
+                JLabel label = new JLabel();
+                add(label, gbc);
+                label.setBorder(border);
+                label.setFocusable(false);
+                this.spinners[i] = new SlidingSpinner(this, label);
+            }
+        }
+        gbc.gridx = 2;
+        gbc.weightx = 1.0;
+        gbc.insets.top = 0;
+        gbc.insets.left = 5;
+        for (SlidingSpinner spinner : this.spinners) {
+            add(spinner.getSlider(), gbc);
+            gbc.insets.top = 5;
+        }
+        gbc.gridx = 3;
+        gbc.weightx = 0.0;
+        gbc.insets.top = 0;
+        for (SlidingSpinner spinner : this.spinners) {
+            add(spinner.getSpinner(), gbc);
+            gbc.insets.top = 5;
+        }
+        setFocusTraversalPolicy(new ContainerOrderFocusTraversalPolicy());
+        setFocusTraversalPolicyProvider(true);
+        setFocusable(false);
+
+        this.model = model;
+    }
+
+    public void actionPerformed(ActionEvent event) {
+        try {
+            this.z = Integer.parseInt(event.getActionCommand());
+            this.y = (this.z != 2) ? 2 : 1;
+            this.x = (this.z != 0) ? 0 : 1;
+            getParent().repaint();
+        }
+        catch (NumberFormatException exception) {
+        }
+    }
+
+    void buildPanel() {
+        int count = this.model.getCount();
+        this.spinners[4].setVisible(count > 4);
+        for (int i = 0; i < count; i++) {
+            Object object = this.spinners[i].getLabel();
+            if (object instanceof JRadioButton) {
+                JRadioButton button = (JRadioButton) object;
+                button.setText(this.model.getLabel(this, i));
+            }
+            else if (object instanceof JLabel) {
+                JLabel label = (JLabel) object;
+                label.setText(this.model.getLabel(this, i));
+            }
+            this.spinners[i].setRange(this.model.getMinimum(i), this.model.getMaximum(i));
+            this.spinners[i].setValue(this.values[i]);
+        }
+    }
+
+    void colorChanged() {
+        this.color = new Color(getColor(0), true);
+        Object parent = getParent();
+        if (parent instanceof ColorChooserPanel) {
+            ColorChooserPanel chooser = (ColorChooserPanel) parent;
+            chooser.setSelectedColor(this.color);
+            chooser.repaint();
+        }
+    }
+
+    float getValueX() {
+        return this.spinners[this.x].getValue();
+    }
+
+    float getValueY() {
+        return 1.0f - this.spinners[this.y].getValue();
+    }
+
+    float getValueZ() {
+        return 1.0f - this.spinners[this.z].getValue();
+    }
+
+    void setValue(float z) {
+        this.spinners[this.z].setValue(1.0f - z);
+        colorChanged();
+    }
+
+    void setValue(float x, float y) {
+        this.spinners[this.x].setValue(x);
+        this.spinners[this.y].setValue(1.0f - y);
+        colorChanged();
+    }
+
+    int getColor(float z) {
+        setDefaultValue(this.x);
+        setDefaultValue(this.y);
+        this.values[this.z] = 1.0f - z;
+        return getColor(3);
+    }
+
+    int getColor(float x, float y) {
+        this.values[this.x] = x;
+        this.values[this.y] = 1.0f - y;
+        setValue(this.z);
+        return getColor(3);
+    }
+
+    void setColor(Color color) {
+        if (!color.equals(this.color)) {
+            this.color = color;
+            this.model.setColor(color.getRGB(), this.values);
+            for (int i = 0; i < this.model.getCount(); i++) {
+                this.spinners[i].setValue(this.values[i]);
+            }
+        }
+    }
+
+    private int getColor(int index) {
+        while (index < this.model.getCount()) {
+            setValue(index++);
+        }
+        return this.model.getColor(this.values);
+    }
+
+    private void setValue(int index) {
+        this.values[index] = this.spinners[index].getValue();
+    }
+
+    private void setDefaultValue(int index) {
+        float value = this.model.getDefault(index);
+        this.values[index] = (value < 0.0f)
+                ? this.spinners[index].getValue()
+                : value;
+    }
+}
diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/DefaultHSBChooserPanel.java
--- a/jdk/src/share/classes/javax/swing/colorchooser/DefaultHSBChooserPanel.java	Fri Oct 10 13:29:11 2008 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,801 +0,0 @@
-/*
- * Copyright 1998-2004 Sun Microsystems, Inc.  All Rights Reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Sun designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
- */
-
-package javax.swing.colorchooser;
-
-import javax.swing.*;
-import java.awt.*;
-import java.awt.event.*;
-import javax.swing.event.*;
-import javax.swing.border.*;
-import java.awt.image.*;
-import java.util.Locale;
-
-/**
- * Implements the default HSB Color chooser
- *
- *  @author Tom Santos
- *  @author Steve Wilson
- *  @author Mark Davidson
- *  @author Shannon Hickey
- */
-class DefaultHSBChooserPanel extends AbstractColorChooserPanel implements ChangeListener, HierarchyListener {
-
-    private transient HSBImage palette;
-    private transient HSBImage sliderPalette;
-
-    private transient Image paletteImage;
-    private transient Image sliderPaletteImage;
-
-    private JSlider slider;
-    private JSpinner hField;
-    private JSpinner sField;
-    private JSpinner bField;
-
-    private JTextField redField;
-    private JTextField greenField;
-    private JTextField blueField;
-
-    private boolean isAdjusting = false; // Flag which indicates that values are set internally
-    private Point paletteSelection = new Point();
-    private JLabel paletteLabel;
-    private JLabel sliderPaletteLabel;
-
-    private JRadioButton hRadio;
-    private JRadioButton sRadio;
-    private JRadioButton bRadio;
-
-    private static final int PALETTE_DIMENSION = 200;
-    private static final int MAX_HUE_VALUE = 359;
-    private static final int MAX_SATURATION_VALUE = 100;
-    private static final int MAX_BRIGHTNESS_VALUE = 100;
-
-    private int currentMode = HUE_MODE;
-
-    private static final int HUE_MODE = 0;
-    private static final int SATURATION_MODE = 1;
-    private static final int BRIGHTNESS_MODE = 2;
-
-    public DefaultHSBChooserPanel() {
-    }
-
-    private void addPaletteListeners() {
-        paletteLabel.addMouseListener(new MouseAdapter() {
-            public void mousePressed(MouseEvent e ) {
-                float[] hsb = new float[3];
-                palette.getHSBForLocation( e.getX(), e.getY(), hsb );
-                updateHSB( hsb[0], hsb[1], hsb[2] );
-            }
-        });
-
-        paletteLabel.addMouseMotionListener(new MouseMotionAdapter() {
-            public void mouseDragged( MouseEvent e ){
-                int labelWidth = paletteLabel.getWidth();
-
-                int labelHeight = paletteLabel.getHeight();
-                int x = e.getX();
-                int y = e.getY();
-
-                if ( x >= labelWidth ) {
-                    x = labelWidth - 1;
-                }
-
-                if ( y >= labelHeight ) {
-                    y = labelHeight - 1;
-                }
-
-                if ( x < 0 ) {
-                    x = 0;
-                }
-
-                if ( y < 0 ) {
-                    y = 0;
-                }
-
-                float[] hsb = new float[3];
-                palette.getHSBForLocation( x, y, hsb );
-                updateHSB( hsb[0], hsb[1], hsb[2] );
-            }
-        });
-    }
-
-    private void updatePalette( float h, float s, float b ) {
-        int x = 0;
-        int y = 0;
-
-        switch ( currentMode ) {
-        case HUE_MODE:
-            if ( h != palette.getHue() ) {
-                palette.setHue( h );
-                palette.nextFrame();
-            }
-            x = PALETTE_DIMENSION - (int)(s * PALETTE_DIMENSION);
-            y = PALETTE_DIMENSION - (int)(b * PALETTE_DIMENSION);
-            break;
-        case SATURATION_MODE:
-            if ( s != palette.getSaturation() ) {
-                palette.setSaturation( s );
-                palette.nextFrame();
-            }
-            x = (int)(h * PALETTE_DIMENSION);
-            y = PALETTE_DIMENSION - (int)(b * PALETTE_DIMENSION);
-            break;
-        case BRIGHTNESS_MODE:
-            if ( b != palette.getBrightness() ) {
-                palette.setBrightness( b );
-                palette.nextFrame();
-            }
-            x = (int)(h * PALETTE_DIMENSION);
-            y = PALETTE_DIMENSION - (int)(s * PALETTE_DIMENSION);
-            break;
-        }
-
-        paletteSelection.setLocation( x, y );
-        paletteLabel.repaint();
-    }
-
-    private void updateSlider( float h, float s, float b ) {
-        // Update the slider palette if necessary.
-        // When the slider is the hue slider or the hue hasn't changed,
-        // the hue of the palette will not need to be updated.
-        if (currentMode != HUE_MODE && h != sliderPalette.getHue() ) {
-            sliderPalette.setHue( h );
-            sliderPalette.nextFrame();
-        }
-
-        float value = 0f;
-
-        switch ( currentMode ) {
-        case HUE_MODE:
-            value = h;
-            break;
-        case SATURATION_MODE:
-            value = s;
-            break;
-        case BRIGHTNESS_MODE:
-            value = b;
-            break;
-        }
-
-        slider.setValue( Math.round(value * (slider.getMaximum())) );
-    }
-
-    private void updateHSBTextFields( float hue, float saturation, float brightness ) {
-        int h =  Math.round(hue * 359);
-        int s =  Math.round(saturation * 100);
-        int b =  Math.round(brightness * 100);
-
-        if (((Integer)hField.getValue()).intValue() != h) {
-            hField.setValue(new Integer(h));
-        }
-        if (((Integer)sField.getValue()).intValue() != s) {
-            sField.setValue(new Integer(s));
-        }
-        if (((Integer)bField.getValue()).intValue() != b) {
-            bField.setValue(new Integer(b));
-        }
-    }
-
-    /**
-     * Updates the values of the RGB fields to reflect the new color change
-     */
-    private void updateRGBTextFields( Color color ) {
-        redField.setText(String.valueOf(color.getRed()));
-        greenField.setText(String.valueOf(color.getGreen()));
-        blueField.setText(String.valueOf(color.getBlue()));
-    }
-
-    /**
-     * Main internal method of updating the ui controls and the color model.
-     */
-    private void updateHSB( float h, float s, float b ) {
-        if ( !isAdjusting ) {
-            isAdjusting = true;
-
-            updatePalette( h, s, b );
-            updateSlider( h, s, b );
-            updateHSBTextFields( h, s, b );
-
-            Color color = Color.getHSBColor(h, s, b);
-            updateRGBTextFields( color );
-
-            getColorSelectionModel().setSelectedColor( color );
-
-            isAdjusting = false;
-        }
-    }
-
-    /**
-      * Invoked automatically when the model's state changes.
-      * It is also called by installChooserPanel to allow
-      * you to set up the initial state of your chooser.
-      * Override this method to update your ChooserPanel.
-      */
-    public void updateChooser() {
-        if ( !isAdjusting ) {
-            float[] hsb = getHSBColorFromModel();
-            updateHSB( hsb[0], hsb[1], hsb[2] );
-        }
-    }
-
-    public void installChooserPanel(JColorChooser enclosingChooser) {
-        super.installChooserPanel(enclosingChooser);
-        setInheritsPopupMenu(true);
-        addHierarchyListener(this);
-    }
-
-    /**
-     * Invoked when the panel is removed from the chooser.
-     */
-    public void uninstallChooserPanel(JColorChooser enclosingChooser) {
-        super.uninstallChooserPanel(enclosingChooser);
-        cleanupPalettesIfNecessary();
-        removeAll();
-        removeHierarchyListener(this);
-    }
-
-    /**
-     * Returns an float array containing the HSB values of the selected color from
-     * the ColorSelectionModel
-     */
-    private float[] getHSBColorFromModel()  {
-        Color color = getColorFromModel();
-        float[] hsb = new float[3];
-        Color.RGBtoHSB( color.getRed(), color.getGreen(), color.getBlue(), hsb );
-
-        return hsb;
-    }
-
-    /**
-     * Builds a new chooser panel.
-     */
-    protected void buildChooser() {
-        setLayout(new BorderLayout());
-        JComponent spp = buildSliderPalettePanel();
-        spp.setInheritsPopupMenu(true);
-        add(spp, BorderLayout.BEFORE_LINE_BEGINS);
-
-        JPanel controlHolder = new JPanel(new SmartGridLayout(1,3));
-        JComponent hsbControls = buildHSBControls();
-        hsbControls.setInheritsPopupMenu(true);
-        controlHolder.add(hsbControls);
-
-        controlHolder.add(new JLabel(" ")); // spacer
-
-        JComponent rgbControls = buildRGBControls();
-        rgbControls.setInheritsPopupMenu(true);
-        controlHolder.add(rgbControls);
-        controlHolder.setInheritsPopupMenu(true);
-
-        controlHolder.setBorder(new EmptyBorder( 10, 5, 10, 5));
-        add( controlHolder, BorderLayout.CENTER);
-    }
-
-    /**
-     * Creates the panel with the uneditable RGB field
-     */
-    private JComponent buildRGBControls() {
-        JPanel panel = new JPanel(new SmartGridLayout(2,3));
-        panel.setInheritsPopupMenu(true);
-
-        Color color = getColorFromModel();
-        redField = new JTextField( String.valueOf(color.getRed()), 3 );
-        redField.setEditable(false);
-        redField.setHorizontalAlignment( JTextField.RIGHT );
-        redField.setInheritsPopupMenu(true);
-
-        greenField = new JTextField(String.valueOf(color.getGreen()), 3 );
-        greenField.setEditable(false);
-        greenField.setHorizontalAlignment( JTextField.RIGHT );
-        greenField.setInheritsPopupMenu(true);
-
-        blueField = new JTextField( String.valueOf(color.getBlue()), 3 );
-        blueField.setEditable(false);
-        blueField.setHorizontalAlignment( JTextField.RIGHT );
-        blueField.setInheritsPopupMenu(true);
-
-        Locale locale = getLocale();
-        String redString = UIManager.getString("ColorChooser.hsbRedText", locale);
-        String greenString = UIManager.getString("ColorChooser.hsbGreenText", locale);
-        String blueString = UIManager.getString("ColorChooser.hsbBlueText", locale);
-
-        panel.add( new JLabel(redString) );
-        panel.add( redField );
-        panel.add( new JLabel(greenString) );
-        panel.add( greenField );
-        panel.add( new JLabel(blueString) );
-        panel.add( blueField );
-
-        return panel;
-    }
-
-    /**
-     * Creates the panel with the editable HSB fields and the radio buttons.
-     */
-    private JComponent buildHSBControls() {
-
-        Locale locale = getLocale();
-        String hueString = UIManager.getString("ColorChooser.hsbHueText", locale);
-        String saturationString = UIManager.getString("ColorChooser.hsbSaturationText", locale);
-        String brightnessString = UIManager.getString("ColorChooser.hsbBrightnessText", locale);
-
-        RadioButtonHandler handler = new RadioButtonHandler();
-
-        hRadio = new JRadioButton(hueString);
-        hRadio.addActionListener(handler);
-        hRadio.setSelected(true);
-        hRadio.setInheritsPopupMenu(true);
-
-        sRadio = new JRadioButton(saturationString);
-        sRadio.addActionListener(handler);
-        sRadio.setInheritsPopupMenu(true);
-
-        bRadio = new JRadioButton(brightnessString);
-        bRadio.addActionListener(handler);
-        bRadio.setInheritsPopupMenu(true);
-
-        ButtonGroup group = new ButtonGroup();
-        group.add(hRadio);
-        group.add(sRadio);
-        group.add(bRadio);
-
-        float[] hsb = getHSBColorFromModel();
-
-        hField = new JSpinner(new SpinnerNumberModel((int)(hsb[0] * 359), 0, 359, 1));
-        sField = new JSpinner(new SpinnerNumberModel((int)(hsb[1] * 100), 0, 100, 1));
-        bField = new JSpinner(new SpinnerNumberModel((int)(hsb[2] * 100), 0, 100, 1));
-
-        hField.addChangeListener(this);
-        sField.addChangeListener(this);
-        bField.addChangeListener(this);
-
-        hField.setInheritsPopupMenu(true);
-        sField.setInheritsPopupMenu(true);
-        bField.setInheritsPopupMenu(true);
-
-        JPanel panel = new JPanel( new SmartGridLayout(2, 3) );
-
-        panel.add(hRadio);
-        panel.add(hField);
-        panel.add(sRadio);
-        panel.add(sField);
-        panel.add(bRadio);
-        panel.add(bField);
-        panel.setInheritsPopupMenu(true);
-
-        return panel;
-    }
-
-    /**
-     * Handler for the radio button classes.
-     */
-    private class RadioButtonHandler implements ActionListener  {
-        public void actionPerformed(ActionEvent evt)  {
-            Object obj = evt.getSource();
-
-            if (obj instanceof JRadioButton)  {
-                JRadioButton button = (JRadioButton)obj;
-                if (button == hRadio) {
-                    setMode(HUE_MODE);
-                } else if (button == sRadio) {
-                    setMode(SATURATION_MODE);
-                } else if (button == bRadio) {
-                    setMode(BRIGHTNESS_MODE);
-                }
-            }
-        }
-    }
-
-    private void setMode(int mode) {
-        if (currentMode == mode) {
-            return;
-        }
-
-        isAdjusting = true;  // Ensure no events propagate from changing slider value.
-        currentMode = mode;
-
-        float[] hsb = getHSBColorFromModel();
-
-        switch (currentMode) {
-            case HUE_MODE:
-                slider.setInverted(true);
-                slider.setMaximum(MAX_HUE_VALUE);
-                palette.setValues(HSBImage.HSQUARE, hsb[0], 1.0f, 1.0f);
-                sliderPalette.setValues(HSBImage.HSLIDER, 0f, 1.0f, 1.0f);
-                break;
-            case SATURATION_MODE:
-                slider.setInverted(false);
-                slider.setMaximum(MAX_SATURATION_VALUE);
-                palette.setValues(HSBImage.SSQUARE, hsb[0], hsb[1], 1.0f);
-                sliderPalette.setValues(HSBImage.SSLIDER, hsb[0], 1.0f, 1.0f);
-                break;
-            case BRIGHTNESS_MODE:
-                slider.setInverted(false);
-                slider.setMaximum(MAX_BRIGHTNESS_VALUE);
-                palette.setValues(HSBImage.BSQUARE, hsb[0], 1.0f, hsb[2]);
-                sliderPalette.setValues(HSBImage.BSLIDER, hsb[0], 1.0f, 1.0f);
-                break;
-        }
-
-        isAdjusting = false;
-
-        palette.nextFrame();
-        sliderPalette.nextFrame();
-
-        updateChooser();
-    }
-
-    protected JComponent buildSliderPalettePanel() {
-
-        // This slider has to have a minimum of 0.  A lot of math in this file is simplified due to this.
-        slider = new JSlider(JSlider.VERTICAL, 0, MAX_HUE_VALUE, 0);
-        slider.setInverted(true);
-        slider.setPaintTrack(false);
-        slider.setPreferredSize(new Dimension(slider.getPreferredSize().width, PALETTE_DIMENSION + 15));
-        slider.addChangeListener(this);
-        slider.setInheritsPopupMenu(true);
-        // We're not painting ticks, but need to ask UI classes to
-        // paint arrow shape anyway, if possible.
-        slider.putClientProperty("Slider.paintThumbArrowShape", Boolean.TRUE);
-        paletteLabel = createPaletteLabel();
-        addPaletteListeners();
-        sliderPaletteLabel = new JLabel();
-
-        JPanel panel = new JPanel();
-        panel.add( paletteLabel );
-        panel.add( slider );
-        panel.add( sliderPaletteLabel );
-
-        initializePalettesIfNecessary();
-
-        return panel;
-    }
-
-    private void initializePalettesIfNecessary() {
-        if (palette != null) {
-            return;
-        }
-
-        float[] hsb = getHSBColorFromModel();
-
-        switch(currentMode){
-            case HUE_MODE:
-                palette = new HSBImage(HSBImage.HSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, hsb[0], 1.0f, 1.0f);
-                sliderPalette = new HSBImage(HSBImage.HSLIDER, 16, PALETTE_DIMENSION, 0f, 1.0f, 1.0f);
-                break;
-            case SATURATION_MODE:
-                palette = new HSBImage(HSBImage.SSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, 1.0f, hsb[1], 1.0f);
-                sliderPalette = new HSBImage(HSBImage.SSLIDER, 16, PALETTE_DIMENSION, 1.0f, 0f, 1.0f);
-                break;
-            case BRIGHTNESS_MODE:
-                palette = new HSBImage(HSBImage.BSQUARE, PALETTE_DIMENSION, PALETTE_DIMENSION, 1.0f, 1.0f, hsb[2]);
-                sliderPalette = new HSBImage(HSBImage.BSLIDER, 16, PALETTE_DIMENSION, 1.0f, 1.0f, 0f);
-                break;
-        }
-        paletteImage = Toolkit.getDefaultToolkit().createImage(palette);
-        sliderPaletteImage = Toolkit.getDefaultToolkit().createImage(sliderPalette);
-
-        paletteLabel.setIcon(new ImageIcon(paletteImage));
-        sliderPaletteLabel.setIcon(new ImageIcon(sliderPaletteImage));
-    }
-
-    private void cleanupPalettesIfNecessary() {
-        if (palette == null) {
-            return;
-        }
-
-        palette.aborted = true;
-        sliderPalette.aborted = true;
-
-        palette.nextFrame();
-        sliderPalette.nextFrame();
-
-        palette = null;
-        sliderPalette = null;
-
-        paletteImage = null;
-        sliderPaletteImage = null;
-
-        paletteLabel.setIcon(null);
-        sliderPaletteLabel.setIcon(null);
-    }
-
-    protected JLabel createPaletteLabel() {
-        return new JLabel() {
-            protected void paintComponent( Graphics g ) {
-                super.paintComponent( g );
-                g.setColor( Color.white );
-                g.drawOval( paletteSelection.x - 4, paletteSelection.y - 4, 8, 8 );
-            }
-        };
-    }
-
-    public String getDisplayName() {
-        return UIManager.getString("ColorChooser.hsbNameText", getLocale());
-    }
-
-    /**
-     * Provides a hint to the look and feel as to the
-     * KeyEvent.VK constant that can be used as a mnemonic to
-     * access the panel. A return value <= 0 indicates there is no mnemonic.
-     * 

- * The return value here is a hint, it is ultimately up to the look - * and feel to honor the return value in some meaningful way. - *

- * This implementation looks up the value from the default - * ColorChooser.hsbMnemonic, or if it - * isn't available (or not an Integer) returns -1. - * The lookup for the default is done through the UIManager: - * UIManager.get("ColorChooser.rgbMnemonic");. - * - * @return KeyEvent.VK constant identifying the mnemonic; <= 0 for no - * mnemonic - * @see #getDisplayedMnemonicIndex - * @since 1.4 - */ - public int getMnemonic() { - return getInt("ColorChooser.hsbMnemonic", -1); - } - - /** - * Provides a hint to the look and feel as to the index of the character in - * getDisplayName that should be visually identified as the - * mnemonic. The look and feel should only use this if - * getMnemonic returns a value > 0. - *

- * The return value here is a hint, it is ultimately up to the look - * and feel to honor the return value in some meaningful way. For example, - * a look and feel may wish to render each - * AbstractColorChooserPanel in a JTabbedPane, - * and further use this return value to underline a character in - * the getDisplayName. - *

- * This implementation looks up the value from the default - * ColorChooser.rgbDisplayedMnemonicIndex, or if it - * isn't available (or not an Integer) returns -1. - * The lookup for the default is done through the UIManager: - * UIManager.get("ColorChooser.hsbDisplayedMnemonicIndex");. - * - * @return Character index to render mnemonic for; -1 to provide no - * visual identifier for this panel. - * @see #getMnemonic - * @since 1.4 - */ - public int getDisplayedMnemonicIndex() { - return getInt("ColorChooser.hsbDisplayedMnemonicIndex", -1); - } - - public Icon getSmallDisplayIcon() { - return null; - } - - public Icon getLargeDisplayIcon() { - return null; - } - - /** - * Class for the slider and palette images. - */ - class HSBImage extends SyntheticImage { - protected float h = .0f; - protected float s = .0f; - protected float b = .0f; - protected float[] hsb = new float[3]; - - protected boolean isDirty = true; - protected int cachedY; - protected int cachedColor; - protected int type; - - private static final int HSQUARE = 0; - private static final int SSQUARE = 1; - private static final int BSQUARE = 2; - private static final int HSLIDER = 3; - private static final int SSLIDER = 4; - private static final int BSLIDER = 5; - - protected HSBImage(int type, int width, int height, float h, float s, float b) { - super(width, height); - setValues(type, h, s, b); - } - - public void setValues(int type, float h, float s, float b) { - this.type = type; - cachedY = -1; - cachedColor = 0; - setHue( h ); - setSaturation( s ); - setBrightness( b ); - } - - public final void setHue( float hue ) { - h = hue; - } - - public final void setSaturation( float saturation ) { - s = saturation; - } - - public final void setBrightness( float brightness ) { - b = brightness; - } - - public final float getHue() { - return h; - } - - public final float getSaturation() { - return s; - } - - public final float getBrightness() { - return b; - } - - protected boolean isStatic() { - return false; - } - - public synchronized void nextFrame() { - isDirty = true; - notifyAll(); - } - - public synchronized void addConsumer(ImageConsumer ic) { - isDirty = true; - super.addConsumer(ic); - } - - private int getRGBForLocation( int x, int y ) { - if (type >= HSLIDER && y == cachedY) { - return cachedColor; - } - - getHSBForLocation( x, y, hsb ); - cachedY = y; - cachedColor = Color.HSBtoRGB( hsb[0], hsb[1], hsb[2] ); - - return cachedColor; - } - - public void getHSBForLocation( int x, int y, float[] hsbArray ) { - switch (type) { - case HSQUARE: { - float saturationStep = ((float)x) / width; - float brightnessStep = ((float)y) / height; - hsbArray[0] = h; - hsbArray[1] = s - saturationStep; - hsbArray[2] = b - brightnessStep; - break; - } - case SSQUARE: { - float brightnessStep = ((float)y) / height; - float step = 1.0f / ((float)width); - hsbArray[0] = x * step; - hsbArray[1] = s; - hsbArray[2] = 1.0f - brightnessStep; - break; - } - case BSQUARE: { - float saturationStep = ((float)y) / height; - float step = 1.0f / ((float)width); - hsbArray[0] = x * step; - hsbArray[1] = 1.0f - saturationStep; - hsbArray[2] = b; - break; - } - case HSLIDER: { - float step = 1.0f / ((float)height); - hsbArray[0] = y * step; - hsbArray[1] = s; - hsbArray[2] = b; - break; - } - case SSLIDER: { - float saturationStep = ((float)y) / height; - hsbArray[0] = h; - hsbArray[1] = s - saturationStep; - hsbArray[2] = b; - break; - } - case BSLIDER: { - float brightnessStep = ((float)y) / height; - hsbArray[0] = h; - hsbArray[1] = s; - hsbArray[2] = b - brightnessStep; - break; - } - } - } - - /** - * Overriden method from SyntheticImage - */ - protected void computeRow( int y, int[] row ) { - if ( y == 0 ) { - synchronized ( this ) { - try { - while ( !isDirty ) { - wait(); - } - } catch (InterruptedException ie) { - } - isDirty = false; - } - } - - if (aborted) { - return; - } - - for ( int i = 0; i < row.length; ++i ) { - row[i] = getRGBForLocation( i, y ); - } - } - } - - public void stateChanged(ChangeEvent e) { - if (e.getSource() == slider) { - boolean modelIsAdjusting = slider.getModel().getValueIsAdjusting(); - - if (!modelIsAdjusting && !isAdjusting) { - int sliderValue = slider.getValue(); - int sliderRange = slider.getMaximum(); - float value = (float)sliderValue / (float)sliderRange; - - float[] hsb = getHSBColorFromModel(); - - switch ( currentMode ){ - case HUE_MODE: - updateHSB(value, hsb[1], hsb[2]); - break; - case SATURATION_MODE: - updateHSB(hsb[0], value, hsb[2]); - break; - case BRIGHTNESS_MODE: - updateHSB(hsb[0], hsb[1], value); - break; - } - } - } else if (e.getSource() instanceof JSpinner) { - float hue = ((Integer)hField.getValue()).floatValue() / 359f; - float saturation = ((Integer)sField.getValue()).floatValue() / 100f; - float brightness = ((Integer)bField.getValue()).floatValue() / 100f; - - updateHSB(hue, saturation, brightness); - } - } - - public void hierarchyChanged(HierarchyEvent he) { - if ((he.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) { - if (isDisplayable()) { - initializePalettesIfNecessary(); - } else { - cleanupPalettesIfNecessary(); - } - } - } - -} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/DefaultRGBChooserPanel.java --- a/jdk/src/share/classes/javax/swing/colorchooser/DefaultRGBChooserPanel.java Fri Oct 10 13:29:11 2008 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,294 +0,0 @@ -/* - * Copyright 1998-2004 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package javax.swing.colorchooser; - -import javax.swing.*; -import javax.swing.event.*; -import java.awt.*; -import java.util.Locale; - -/** - * The standard RGB chooser. - *

- * Warning: - * Serialized objects of this class will not be compatible with - * future Swing releases. The current serialization support is - * appropriate for short term storage or RMI between applications running - * the same version of Swing. As of 1.4, support for long term storage - * of all JavaBeansTM - * has been added to the java.beans package. - * Please see {@link java.beans.XMLEncoder}. - * - * @author Steve Wilson - * @author Mark Davidson - * @see JColorChooser - * @see AbstractColorChooserPanel - */ -class DefaultRGBChooserPanel extends AbstractColorChooserPanel implements ChangeListener { - - protected JSlider redSlider; - protected JSlider greenSlider; - protected JSlider blueSlider; - protected JSpinner redField; - protected JSpinner blueField; - protected JSpinner greenField; - - private final int minValue = 0; - private final int maxValue = 255; - - private boolean isAdjusting = false; // indicates the fields are being set internally - - public DefaultRGBChooserPanel() { - super(); - setInheritsPopupMenu(true); - } - - /** - * Sets the values of the controls to reflect the color - */ - private void setColor( Color newColor ) { - int red = newColor.getRed(); - int blue = newColor.getBlue(); - int green = newColor.getGreen(); - - if (redSlider.getValue() != red) { - redSlider.setValue(red); - } - if (greenSlider.getValue() != green) { - greenSlider.setValue(green); - } - if (blueSlider.getValue() != blue) { - blueSlider.setValue(blue); - } - - if (((Integer)redField.getValue()).intValue() != red) - redField.setValue(new Integer(red)); - if (((Integer)greenField.getValue()).intValue() != green) - greenField.setValue(new Integer(green)); - if (((Integer)blueField.getValue()).intValue() != blue ) - blueField.setValue(new Integer(blue)); - } - - public String getDisplayName() { - return UIManager.getString("ColorChooser.rgbNameText", getLocale()); - } - - /** - * Provides a hint to the look and feel as to the - * KeyEvent.VK constant that can be used as a mnemonic to - * access the panel. A return value <= 0 indicates there is no mnemonic. - *

- * The return value here is a hint, it is ultimately up to the look - * and feel to honor the return value in some meaningful way. - *

- * This implementation looks up the value from the default - * ColorChooser.rgbMnemonic, or if it - * isn't available (or not an Integer) returns -1. - * The lookup for the default is done through the UIManager: - * UIManager.get("ColorChooser.rgbMnemonic");. - * - * @return KeyEvent.VK constant identifying the mnemonic; <= 0 for no - * mnemonic - * @see #getDisplayedMnemonicIndex - * @since 1.4 - */ - public int getMnemonic() { - return getInt("ColorChooser.rgbMnemonic", -1); - } - - /** - * Provides a hint to the look and feel as to the index of the character in - * getDisplayName that should be visually identified as the - * mnemonic. The look and feel should only use this if - * getMnemonic returns a value > 0. - *

- * The return value here is a hint, it is ultimately up to the look - * and feel to honor the return value in some meaningful way. For example, - * a look and feel may wish to render each - * AbstractColorChooserPanel in a JTabbedPane, - * and further use this return value to underline a character in - * the getDisplayName. - *

- * This implementation looks up the value from the default - * ColorChooser.rgbDisplayedMnemonicIndex, or if it - * isn't available (or not an Integer) returns -1. - * The lookup for the default is done through the UIManager: - * UIManager.get("ColorChooser.rgbDisplayedMnemonicIndex");. - * - * @return Character index to render mnemonic for; -1 to provide no - * visual identifier for this panel. - * @see #getMnemonic - * @since 1.4 - */ - public int getDisplayedMnemonicIndex() { - return getInt("ColorChooser.rgbDisplayedMnemonicIndex", -1); - } - - public Icon getSmallDisplayIcon() { - return null; - } - - public Icon getLargeDisplayIcon() { - return null; - } - - /** - * The background color, foreground color, and font are already set to the - * defaults from the defaults table before this method is called. - */ - public void installChooserPanel(JColorChooser enclosingChooser) { - super.installChooserPanel(enclosingChooser); - } - - protected void buildChooser() { - - Locale locale = getLocale(); - String redString = UIManager.getString("ColorChooser.rgbRedText", locale); - String greenString = UIManager.getString("ColorChooser.rgbGreenText", locale); - String blueString = UIManager.getString("ColorChooser.rgbBlueText", locale); - - setLayout( new BorderLayout() ); - Color color = getColorFromModel(); - - - JPanel enclosure = new JPanel(); - enclosure.setLayout( new SmartGridLayout( 3, 3 ) ); - enclosure.setInheritsPopupMenu(true); - - // The panel that holds the sliders - - add( enclosure, BorderLayout.CENTER ); - // sliderPanel.setBorder(new LineBorder(Color.black)); - - // The row for the red value - JLabel l = new JLabel(redString); - l.setDisplayedMnemonic(getInt("ColorChooser.rgbRedMnemonic", -1)); - enclosure.add(l); - redSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getRed()); - redSlider.setMajorTickSpacing( 85 ); - redSlider.setMinorTickSpacing( 17 ); - redSlider.setPaintTicks( true ); - redSlider.setPaintLabels( true ); - redSlider.setInheritsPopupMenu(true); - enclosure.add( redSlider ); - redField = new JSpinner( - new SpinnerNumberModel(color.getRed(), minValue, maxValue, 1)); - l.setLabelFor(redSlider); - redField.setInheritsPopupMenu(true); - JPanel redFieldHolder = new JPanel(new CenterLayout()); - redFieldHolder.setInheritsPopupMenu(true); - redField.addChangeListener(this); - redFieldHolder.add(redField); - enclosure.add(redFieldHolder); - - - // The row for the green value - l = new JLabel(greenString); - l.setDisplayedMnemonic(getInt("ColorChooser.rgbGreenMnemonic", -1)); - enclosure.add(l); - greenSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getGreen()); - greenSlider.setMajorTickSpacing( 85 ); - greenSlider.setMinorTickSpacing( 17 ); - greenSlider.setPaintTicks( true ); - greenSlider.setPaintLabels( true ); - greenSlider.setInheritsPopupMenu(true); - enclosure.add(greenSlider); - greenField = new JSpinner( - new SpinnerNumberModel(color.getGreen(), minValue, maxValue, 1)); - l.setLabelFor(greenSlider); - greenField.setInheritsPopupMenu(true); - JPanel greenFieldHolder = new JPanel(new CenterLayout()); - greenFieldHolder.add(greenField); - greenFieldHolder.setInheritsPopupMenu(true); - greenField.addChangeListener(this); - enclosure.add(greenFieldHolder); - - // The slider for the blue value - l = new JLabel(blueString); - l.setDisplayedMnemonic(getInt("ColorChooser.rgbBlueMnemonic", -1)); - enclosure.add(l); - blueSlider = new JSlider(JSlider.HORIZONTAL, 0, 255, color.getBlue()); - blueSlider.setMajorTickSpacing( 85 ); - blueSlider.setMinorTickSpacing( 17 ); - blueSlider.setPaintTicks( true ); - blueSlider.setPaintLabels( true ); - blueSlider.setInheritsPopupMenu(true); - enclosure.add(blueSlider); - blueField = new JSpinner( - new SpinnerNumberModel(color.getBlue(), minValue, maxValue, 1)); - l.setLabelFor(blueSlider); - blueField.setInheritsPopupMenu(true); - JPanel blueFieldHolder = new JPanel(new CenterLayout()); - blueFieldHolder.add(blueField); - blueField.addChangeListener(this); - blueFieldHolder.setInheritsPopupMenu(true); - enclosure.add(blueFieldHolder); - - redSlider.addChangeListener( this ); - greenSlider.addChangeListener( this ); - blueSlider.addChangeListener( this ); - - redSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE); - greenSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE); - blueSlider.putClientProperty("JSlider.isFilled", Boolean.TRUE); - } - - public void uninstallChooserPanel(JColorChooser enclosingChooser) { - super.uninstallChooserPanel(enclosingChooser); - removeAll(); - } - - public void updateChooser() { - if (!isAdjusting) { - isAdjusting = true; - - setColor(getColorFromModel()); - - isAdjusting = false; - } - } - - public void stateChanged( ChangeEvent e ) { - if ( e.getSource() instanceof JSlider && !isAdjusting) { - - int red = redSlider.getValue(); - int green = greenSlider.getValue(); - int blue = blueSlider.getValue() ; - Color color = new Color (red, green, blue); - - getColorSelectionModel().setSelectedColor(color); - } else if (e.getSource() instanceof JSpinner && !isAdjusting) { - - int red = ((Integer)redField.getValue()).intValue(); - int green = ((Integer)greenField.getValue()).intValue(); - int blue = ((Integer)blueField.getValue()).intValue(); - Color color = new Color (red, green, blue); - - getColorSelectionModel().setSelectedColor(color); - } - } - -} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/DefaultSwatchChooserPanel.java --- a/jdk/src/share/classes/javax/swing/colorchooser/DefaultSwatchChooserPanel.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/colorchooser/DefaultSwatchChooserPanel.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1998-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -213,17 +213,15 @@ class RecentSwatchListener extends MouseAdapter implements Serializable { public void mousePressed(MouseEvent e) { Color color = recentSwatchPanel.getColorForLocation(e.getX(), e.getY()); - getColorSelectionModel().setSelectedColor(color); - + setSelectedColor(color); } } class MainSwatchListener extends MouseAdapter implements Serializable { public void mousePressed(MouseEvent e) { Color color = swatchPanel.getColorForLocation(e.getX(), e.getY()); - getColorSelectionModel().setSelectedColor(color); + setSelectedColor(color); recentSwatchPanel.setMostRecentColor(color); - } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/DiagramComponent.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/javax/swing/colorchooser/DiagramComponent.java Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,160 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Insets; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.awt.image.BufferedImage; +import javax.swing.JComponent; + +final class DiagramComponent extends JComponent implements MouseListener, MouseMotionListener { + + private final ColorPanel panel; + private final boolean diagram; + + private final Insets insets = new Insets(0, 0, 0, 0); + + private int width; + private int height; + + private int[] array; + private BufferedImage image; + + DiagramComponent(ColorPanel panel, boolean diagram) { + this.panel = panel; + this.diagram = diagram; + addMouseListener(this); + addMouseMotionListener(this); + } + + @Override + protected void paintComponent(Graphics g) { + getInsets(this.insets); + this.width = getWidth() - this.insets.left - this.insets.right; + this.height = getHeight() - this.insets.top - this.insets.bottom; + + boolean update = (this.image == null) + || (this.width != this.image.getWidth()) + || (this.height != this.image.getHeight()); + if (update) { + int size = this.width * this.height; + if ((this.array == null) || (this.array.length < size)) { + this.array = new int[size]; + } + this.image = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_RGB); + } + { + float dx = 1.0f / (float) (this.width - 1); + float dy = 1.0f / (float) (this.height - 1); + + int offset = 0; + float y = 0.0f; + for (int h = 0; h < this.height; h++, y += dy) { + if (this.diagram) { + float x = 0.0f; + for (int w = 0; w < this.width; w++, x += dx, offset++) { + this.array[offset] = this.panel.getColor(x, y); + } + } + else { + int color = this.panel.getColor(y); + for (int w = 0; w < this.width; w++, offset++) { + this.array[offset] = color; + } + } + } + } + this.image.setRGB(0, 0, this.width, this.height, this.array, 0, this.width); + g.drawImage(this.image, this.insets.left, this.insets.top, this.width, this.height, this); + if (isEnabled()) { + this.width--; + this.height--; + g.setXORMode(Color.WHITE); + g.setColor(Color.BLACK); + if (this.diagram) { + int x = getValue(this.panel.getValueX(), this.insets.left, this.width); + int y = getValue(this.panel.getValueY(), this.insets.top, this.height); + g.drawLine(x - 8, y, x + 8, y); + g.drawLine(x, y - 8, x, y + 8); + } + else { + int z = getValue(this.panel.getValueZ(), this.insets.top, this.height); + g.drawLine(this.insets.left, z, this.insets.left + this.width, z); + } + g.setPaintMode(); + } + } + + public void mousePressed(MouseEvent event) { + mouseDragged(event); + } + + public void mouseReleased(MouseEvent event) { + } + + public void mouseClicked(MouseEvent event) { + } + + public void mouseEntered(MouseEvent event) { + } + + public void mouseExited(MouseEvent event) { + } + + public void mouseMoved(MouseEvent event) { + } + + public void mouseDragged(MouseEvent event) { + if (isEnabled()) { + float y = getValue(event.getY(), this.insets.top, this.height); + if (this.diagram) { + float x = getValue(event.getX(), this.insets.left, this.width); + this.panel.setValue(x, y); + } + else { + this.panel.setValue(y); + } + } + } + + private static int getValue(float value, int min, int max) { + return min + (int) (value * (float) (max)); + } + + private static float getValue(int value, int min, int max) { + if (min < value) { + value -= min; + return (value < max) + ? (float) value / (float) max + : 1.0f; + } + return 0.0f; + } +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/SlidingSpinner.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/javax/swing/colorchooser/SlidingSpinner.java Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,118 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.colorchooser; + +import javax.swing.JComponent; +import javax.swing.JSlider; +import javax.swing.JSpinner; +import javax.swing.JSpinner.DefaultEditor; +import javax.swing.SpinnerNumberModel; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +final class SlidingSpinner implements ChangeListener { + + private final ColorPanel panel; + private final JComponent label; + private final SpinnerNumberModel model = new SpinnerNumberModel(); + private final JSlider slider = new JSlider(); + private final JSpinner spinner = new JSpinner(this.model); + private float value; + private boolean internal; + + SlidingSpinner(ColorPanel panel, JComponent label) { + this.panel = panel; + this.label = label; + this.slider.addChangeListener(this); + this.spinner.addChangeListener(this); + DefaultEditor editor = (DefaultEditor) this.spinner.getEditor(); + ValueFormatter.init(3, false, editor.getTextField()); + editor.setFocusable(false); + this.spinner.setFocusable(false); + } + + JComponent getLabel() { + return this.label; + } + + JSlider getSlider() { + return this.slider; + } + + JSpinner getSpinner() { + return this.spinner; + } + + float getValue() { + return this.value; + } + + void setValue(float value) { + int min = this.slider.getMinimum(); + int max = this.slider.getMaximum(); + this.internal = true; + this.slider.setValue(min + (int) (value * (float) (max - min))); + this.spinner.setValue(Integer.valueOf(this.slider.getValue())); + this.internal = false; + this.value = value; + } + + void setRange(int min, int max) { + this.internal = true; + this.slider.setMinimum(min); + this.slider.setMaximum(max); + this.model.setMinimum(Integer.valueOf(min)); + this.model.setMaximum(Integer.valueOf(max)); + this.internal = false; + } + + void setVisible(boolean visible) { + this.label.setVisible(visible); + this.slider.setVisible(visible); + this.spinner.setVisible(visible); + } + + public void stateChanged(ChangeEvent event) { + if (!this.internal) { + if (this.spinner == event.getSource()) { + Object value = this.spinner.getValue(); + if (value instanceof Integer) { + this.internal = true; + this.slider.setValue((Integer) value); + this.internal = false; + } + } + int value = this.slider.getValue(); + this.internal = true; + this.spinner.setValue(Integer.valueOf(value)); + this.internal = false; + int min = this.slider.getMinimum(); + int max = this.slider.getMaximum(); + this.value = (float) (value - min) / (float) (max - min); + this.panel.colorChanged(); + } + } +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/colorchooser/SyntheticImage.java --- a/jdk/src/share/classes/javax/swing/colorchooser/SyntheticImage.java Fri Oct 10 13:29:11 2008 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,166 +0,0 @@ -/* - * Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -package javax.swing.colorchooser; - -import java.awt.*; -import java.awt.image.*; - -/** A helper class to make computing synthetic images a little easier. - * All you need to do is define a subclass that overrides computeRow - * to compute a row of the image. It is passed the y coordinate of the - * row and an array into which to put the pixels in - * - * standard ARGB format. - *

Normal usage looks something like this: - *

 Image i = createImage(new SyntheticImage(200, 100) {
- *       protected void computeRow(int y, int[] row) {
- *         for(int i = width; --i>=0; ) {
- *             int grey = i*255/(width-1);
- *             row[i] = (255<<24)|(grey<<16)|(grey<<8)|grey;
- *         }
- *       }
- *   }
- *  
This creates a image 200 pixels wide and 100 pixels high - * that is a horizontal grey ramp, going from black on the left to - * white on the right. - *

- * If the image is to be a movie, override isStatic to return false, - * y cycling back to 0 is computeRow's signal that the next - * frame has started. It is acceptable (expected?) for computeRow(0,r) - * to pause until the appropriate time to start the next frame. - * - * @author James Gosling - */ -abstract class SyntheticImage implements ImageProducer { - private SyntheticImageGenerator root; - protected int width=10, height=100; - static final ColorModel cm = ColorModel.getRGBdefault(); - public static final int pixMask = 0xFF; - private Thread runner; - protected SyntheticImage() { } - protected SyntheticImage(int w, int h) { width = w; height = h; } - protected void computeRow(int y, int[] row) { - int p = 255-255*y/(height-1); - p = (pixMask<<24)|(p<<16)|(p<<8)|p; - for (int i = row.length; --i>=0; ) row[i] = p; - } - public synchronized void addConsumer(ImageConsumer ic){ - for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) - if (ics.ic == ic) return; - root = new SyntheticImageGenerator(ic, root, this); - } - public synchronized boolean isConsumer(ImageConsumer ic){ - for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) - if (ics.ic == ic) return true; - return false; - } - public synchronized void removeConsumer(ImageConsumer ic) { - SyntheticImageGenerator prev = null; - for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) { - if (ics.ic == ic) { - ics.useful = false; - if (prev!=null) prev.next = ics.next; - else root = ics.next; - return; - } - prev = ics; - } - } - public synchronized void startProduction(ImageConsumer ic) { - addConsumer(ic); - for (SyntheticImageGenerator ics = root; ics != null; ics = ics.next) - if (ics.useful && !ics.isAlive()) - ics.start(); - } - protected boolean isStatic() { return true; } - public void nextFrame(int param) {}//Override if !isStatic - public void requestTopDownLeftRightResend(ImageConsumer ic){} - - protected volatile boolean aborted = false; -} - -class SyntheticImageGenerator extends Thread { - ImageConsumer ic; - boolean useful; - SyntheticImageGenerator next; - SyntheticImage parent; - SyntheticImageGenerator(ImageConsumer ic, SyntheticImageGenerator next, - SyntheticImage parent) { - super("SyntheticImageGenerator"); - this.ic = ic; - this.next = next; - this.parent = parent; - useful = true; - setDaemon(true); - } - public void run() { - ImageConsumer ic = this.ic; - int w = parent.width; - int h = parent.height; - int hints = ic.SINGLEPASS|ic.COMPLETESCANLINES|ic.TOPDOWNLEFTRIGHT; - if (parent.isStatic()) - hints |= ic.SINGLEFRAME; - ic.setHints(hints); - ic.setDimensions(w, h); - ic.setProperties(null); - ic.setColorModel(parent.cm); - - if (useful) { - int[] row=new int[w]; - doPrivileged( new Runnable() { - public void run() { - Thread.currentThread().setPriority(Thread.MIN_PRIORITY); - } - }); - - do { - for (int y = 0; y>= 4; + } + return new String(array).toUpperCase(ENGLISH); + } + throw new ParseException("illegal object", 0); + } + + @Override + protected DocumentFilter getDocumentFilter() { + return this.filter; + } + + public void focusGained(FocusEvent event) { + Object source = event.getSource(); + if (source instanceof JFormattedTextField) { + this.text = (JFormattedTextField) source; + SwingUtilities.invokeLater(this); + } + } + + public void focusLost(FocusEvent event) { + } + + public void run() { + if (this.text != null) { + this.text.selectAll(); + } + } + + private boolean isValid(int length) { + return (0 <= length) && (length <= this.length); + } + + private boolean isValid(String text) { + int length = text.length(); + for (int i = 0; i < length; i++) { + char ch = text.charAt(i); + if (Character.digit(ch, this.radix) < 0) { + return false; + } + } + return true; + } +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/filechooser/FileSystemView.java --- a/jdk/src/share/classes/javax/swing/filechooser/FileSystemView.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/filechooser/FileSystemView.java Wed Jul 05 16:42:37 2017 +0200 @@ -136,8 +136,8 @@ } File[] roots = getRoots(); - for (int i = 0; i < roots.length; i++) { - if (roots[i].equals(f)) { + for (File root : roots) { + if (root.equals(f)) { return true; } } @@ -252,8 +252,8 @@ return true; } File[] children = getFiles(folder, false); - for (int i = 0; i < children.length; i++) { - if (file.equals(children[i])) { + for (File child : children) { + if (file.equals(child)) { return true; } } @@ -276,9 +276,9 @@ public File getChild(File parent, String fileName) { if (parent instanceof ShellFolder) { File[] children = getFiles(parent, false); - for (int i = 0; i < children.length; i++) { - if (children[i].getName().equals(fileName)) { - return children[i]; + for (File child : children) { + if (child.getName().equals(fileName)) { + return child; } } } @@ -444,7 +444,7 @@ * Gets the list of shown (i.e. not hidden) files. */ public File[] getFiles(File dir, boolean useFileHiding) { - Vector files = new Vector(); + Vector files = new Vector(); // add all files in dir @@ -483,7 +483,7 @@ } } - return (File[])files.toArray(new File[files.size()]); + return files.toArray(new File[files.size()]); } @@ -590,7 +590,7 @@ if(containingDir == null) { throw new IOException("Containing directory is null:"); } - File newFolder = null; + File newFolder; // Unix - using OpenWindows' default folder name. Can't find one for Motif/CDE. newFolder = createFileObject(containingDir, newFolderString); int i = 1; @@ -614,11 +614,7 @@ } public boolean isDrive(File dir) { - if (isFloppyDrive(dir)) { - return true; - } else { - return false; - } + return isFloppyDrive(dir); } public boolean isFloppyDrive(File dir) { @@ -700,9 +696,8 @@ if(containingDir == null) { throw new IOException("Containing directory is null:"); } - File newFolder = null; // Using NT's default folder name - newFolder = createFileObject(containingDir, newFolderString); + File newFolder = createFileObject(containingDir, newFolderString); int i = 2; while (newFolder.exists() && (i < 100)) { newFolder = createFileObject(containingDir, MessageFormat.format( @@ -770,9 +765,8 @@ if(containingDir == null) { throw new IOException("Containing directory is null:"); } - File newFolder = null; // Using NT's default folder name - newFolder = createFileObject(containingDir, newFolderString); + File newFolder = createFileObject(containingDir, newFolderString); if(newFolder.exists()) { throw new IOException("Directory already exists:" + newFolder.getAbsolutePath()); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonListener.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonListener.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonListener.java Wed Jul 05 16:42:37 2017 +0200 @@ -165,7 +165,7 @@ JRootPane root = b.getRootPane(); if (root != null) { BasicButtonUI ui = (BasicButtonUI)BasicLookAndFeel.getUIOfType( - ((AbstractButton)b).getUI(), BasicButtonUI.class); + b.getUI(), BasicButtonUI.class); if (ui != null && DefaultLookup.getBoolean(b, ui, ui.getPropertyPrefix() + "defaultButtonFollowsFocus", true)) { @@ -185,7 +185,7 @@ JButton initialDefault = (JButton)root.getClientProperty("initialDefaultButton"); if (b != initialDefault) { BasicButtonUI ui = (BasicButtonUI)BasicLookAndFeel.getUIOfType( - ((AbstractButton)b).getUI(), BasicButtonUI.class); + b.getUI(), BasicButtonUI.class); if (ui != null && DefaultLookup.getBoolean(b, ui, ui.getPropertyPrefix() + "defaultButtonFollowsFocus", true)) { @@ -239,7 +239,7 @@ } } } - }; + } public void mouseReleased(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { @@ -253,7 +253,7 @@ model.setPressed(false); model.setArmed(false); } - }; + } public void mouseEntered(MouseEvent e) { AbstractButton b = (AbstractButton) e.getSource(); @@ -263,7 +263,7 @@ } if (model.isPressed()) model.setArmed(true); - }; + } public void mouseExited(MouseEvent e) { AbstractButton b = (AbstractButton) e.getSource(); @@ -272,7 +272,7 @@ model.setRollover(false); } model.setArmed(false); - }; + } /** diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -237,7 +237,7 @@ /* the fallback icon should be based on the selected state */ if (model.isSelected()) { - selectedIcon = (Icon) b.getSelectedIcon(); + selectedIcon = b.getSelectedIcon(); if (selectedIcon != null) { icon = selectedIcon; } @@ -245,31 +245,31 @@ if(!model.isEnabled()) { if(model.isSelected()) { - tmpIcon = (Icon) b.getDisabledSelectedIcon(); + tmpIcon = b.getDisabledSelectedIcon(); if (tmpIcon == null) { tmpIcon = selectedIcon; } } if (tmpIcon == null) { - tmpIcon = (Icon) b.getDisabledIcon(); + tmpIcon = b.getDisabledIcon(); } } else if(model.isPressed() && model.isArmed()) { - tmpIcon = (Icon) b.getPressedIcon(); + tmpIcon = b.getPressedIcon(); if(tmpIcon != null) { // revert back to 0 offset clearTextShiftOffset(); } } else if(b.isRolloverEnabled() && model.isRollover()) { if(model.isSelected()) { - tmpIcon = (Icon) b.getRolloverSelectedIcon(); + tmpIcon = b.getRolloverSelectedIcon(); if (tmpIcon == null) { tmpIcon = selectedIcon; } } if (tmpIcon == null) { - tmpIcon = (Icon) b.getRolloverIcon(); + tmpIcon = b.getRolloverIcon(); } } @@ -451,9 +451,9 @@ MouseMotionListener[] listeners = b.getMouseMotionListeners(); if (listeners != null) { - for (int counter = 0; counter < listeners.length; counter++) { - if (listeners[counter] instanceof BasicButtonListener) { - return (BasicButtonListener)listeners[counter]; + for (MouseMotionListener listener : listeners) { + if (listener instanceof BasicButtonListener) { + return (BasicButtonListener) listener; } } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -299,8 +299,10 @@ tabbedPane.addTab(name, centerWrapper); if (mnemonic > 0) { tabbedPane.setMnemonicAt(i, mnemonic); - tabbedPane.setDisplayedMnemonicIndexAt( - i, newPanels[i].getDisplayedMnemonicIndex()); + int index = newPanels[i].getDisplayedMnemonicIndex(); + if (index >= 0) { + tabbedPane.setDisplayedMnemonicIndexAt(i, index); + } } } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java Wed Jul 05 16:42:37 2017 +0200 @@ -92,7 +92,7 @@ return oldValue; } else { // Must take the value from the editor and get the value and cast it to the new type. - Class cls = oldValue.getClass(); + Class cls = oldValue.getClass(); try { Method method = cls.getMethod("valueOf", new Class[]{String.class}); newValue = method.invoke(oldValue, new Object[] { editor.getText()}); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -1509,15 +1509,21 @@ || ui.isTableCellEditor) { Object listItem = ui.popup.getList().getSelectedValue(); if (listItem != null) { - comboBox.getModel().setSelectedItem(listItem); - // Ensure that JComboBox.actionPerformed() - // doesn't set editor value as selected item + // Use the selected value from popup + // to set the selected item in combo box, + // but ensure before that JComboBox.actionPerformed() + // won't use editor's value to set the selected item comboBox.getEditor().setItem(listItem); + comboBox.setSelectedItem(listItem); } } comboBox.setPopupVisible(false); } else { + // Hide combo box if it is a table cell editor + if (ui.isTableCellEditor && !comboBox.isEditable()) { + comboBox.setSelectedItem(comboBox.getSelectedItem()); + } // Call the default button binding. // This is a pretty messy way of passing an event through // to the root pane. diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicDesktopIconUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,6 +47,7 @@ protected JInternalFrame.JDesktopIcon desktopIcon; protected JInternalFrame frame; + private DesktopIconMover desktopIconMover; /** * The title pane component used in the desktop icon. @@ -127,12 +128,21 @@ mouseInputListener = createMouseInputListener(); desktopIcon.addMouseMotionListener(mouseInputListener); desktopIcon.addMouseListener(mouseInputListener); + getDesktopIconMover().installListeners(); } protected void uninstallListeners() { desktopIcon.removeMouseMotionListener(mouseInputListener); desktopIcon.removeMouseListener(mouseInputListener); mouseInputListener = null; + getDesktopIconMover().uninstallListeners(); + } + + private DesktopIconMover getDesktopIconMover() { + if (desktopIconMover == null) { + desktopIconMover = new DesktopIconMover(desktopIcon); + } + return desktopIconMover; } protected void installDefaults() { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicDirectoryModel.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicDirectoryModel.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicDirectoryModel.java Wed Jul 05 16:42:37 2017 +0200 @@ -43,10 +43,10 @@ private JFileChooser filechooser = null; // PENDING(jeff) pick the size more sensibly - private Vector fileCache = new Vector(50); + private Vector fileCache = new Vector(50); private LoadFilesThread loadThread = null; - private Vector files = null; - private Vector directories = null; + private Vector files = null; + private Vector directories = null; private int fetchID = 0; private PropertyChangeSupport changeSupport; @@ -106,14 +106,14 @@ if (files != null) { return files; } - files = new Vector(); - directories = new Vector(); + files = new Vector(); + directories = new Vector(); directories.addElement(filechooser.getFileSystemView().createFileObject( filechooser.getCurrentDirectory(), "..") ); for (int i = 0; i < getSize(); i++) { - File f = (File)fileCache.get(i); + File f = fileCache.get(i); if (filechooser.isTraversable(f)) { directories.add(f); } else { @@ -215,7 +215,7 @@ class LoadFilesThread extends Thread { File currentDirectory = null; int fid; - Vector runnables = new Vector(10); + Vector runnables = new Vector(10); public LoadFilesThread(File currentDirectory, int fid) { super("Basic L&F File Loading Thread"); @@ -223,7 +223,7 @@ this.fid = fid; } - private void invokeLater(Runnable runnable) { + private void invokeLater(DoChangeContents runnable) { runnables.addElement(runnable); SwingUtilities.invokeLater(runnable); } @@ -245,9 +245,9 @@ } // run through the file list, add directories and selectable files to fileCache - for (int i = 0; i < list.length; i++) { - if(filechooser.accept(list[i])) { - acceptsList.addElement(list[i]); + for (File file : list) { + if (filechooser.accept(file)) { + acceptsList.addElement(file); } } @@ -258,11 +258,11 @@ // First sort alphabetically by filename sort(acceptsList); - Vector newDirectories = new Vector(50); - Vector newFiles = new Vector(); + Vector newDirectories = new Vector(50); + Vector newFiles = new Vector(); // run through list grabbing directories in chunks of ten for(int i = 0; i < acceptsList.size(); i++) { - File f = (File) acceptsList.elementAt(i); + File f = acceptsList.elementAt(i); boolean isTraversable = filechooser.isTraversable(f); if (isTraversable) { newDirectories.addElement(f); @@ -274,7 +274,7 @@ } } - Vector newFileCache = new Vector(newDirectories); + Vector newFileCache = new Vector(newDirectories); newFileCache.addAll(newFiles); int newSize = newFileCache.size(); @@ -320,7 +320,7 @@ if(isInterrupted()) { return; } - invokeLater(new DoChangeContents(null, 0, new Vector(fileCache.subList(start, end)), + invokeLater(new DoChangeContents(null, 0, new Vector(fileCache.subList(start, end)), start, fid)); newFileCache = null; } @@ -334,9 +334,9 @@ } - public void cancelRunnables(Vector runnables) { - for(int i = 0; i < runnables.size(); i++) { - ((DoChangeContents)runnables.elementAt(i)).cancel(); + public void cancelRunnables(Vector runnables) { + for (DoChangeContents runnable : runnables) { + runnable.cancel(); } } @@ -449,15 +449,14 @@ class DoChangeContents implements Runnable { - private List addFiles; - private List remFiles; + private List addFiles; + private List remFiles; private boolean doFire = true; private int fid; private int addStart = 0; private int remStart = 0; - private int change; - public DoChangeContents(List addFiles, int addStart, List remFiles, int remStart, int fid) { + public DoChangeContents(List addFiles, int addStart, List remFiles, int remStart, int fid) { this.addFiles = addFiles; this.addStart = addStart; this.remFiles = remFiles; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicFileChooserUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -36,6 +36,7 @@ import java.beans.*; import java.io.*; import java.util.*; +import java.util.List; import java.util.regex.*; import sun.awt.shell.ShellFolder; import sun.swing.*; @@ -159,9 +160,9 @@ } public void uninstallUI(JComponent c) { - uninstallListeners((JFileChooser) filechooser); - uninstallComponents((JFileChooser) filechooser); - uninstallDefaults((JFileChooser) filechooser); + uninstallListeners(filechooser); + uninstallComponents(filechooser); + uninstallDefaults(filechooser); if(accessoryPanel != null) { accessoryPanel.removeAll(); @@ -506,9 +507,9 @@ setDirectorySelected(true); setDirectory(((File)objects[0])); } else { - ArrayList fList = new ArrayList(objects.length); - for (int i = 0; i < objects.length; i++) { - File f = (File)objects[i]; + ArrayList fList = new ArrayList(objects.length); + for (Object object : objects) { + File f = (File) object; boolean isDir = f.isDirectory(); if ((chooser.isFileSelectionEnabled() && !isDir) || (chooser.isDirectorySelectionEnabled() @@ -518,7 +519,7 @@ } } if (fList.size() > 0) { - files = (File[])fList.toArray(new File[fList.size()]); + files = fList.toArray(new File[fList.size()]); } setDirectorySelected(false); } @@ -829,11 +830,17 @@ File dir = chooser.getCurrentDirectory(); if (filename != null) { - // Remove whitespace from beginning and end of filename - filename = filename.trim(); + // Remove whitespaces from end of filename + int i = filename.length() - 1; + + while (i >=0 && filename.charAt(i) <= ' ') { + i--; + } + + filename = filename.substring(0, i + 1); } - if (filename == null || filename.equals("")) { + if (filename == null || filename.length() == 0) { // no file selected, multiple selection off, therefore cancel the approve action resetGlobFilter(); return; @@ -842,100 +849,93 @@ File selectedFile = null; File[] selectedFiles = null; - if (filename != null && !filename.equals("")) { - // Unix: Resolve '~' to user's home directory - if (File.separatorChar == '/') { - if (filename.startsWith("~/")) { - filename = System.getProperty("user.home") + filename.substring(1); - } else if (filename.equals("~")) { - filename = System.getProperty("user.home"); + // Unix: Resolve '~' to user's home directory + if (File.separatorChar == '/') { + if (filename.startsWith("~/")) { + filename = System.getProperty("user.home") + filename.substring(1); + } else if (filename.equals("~")) { + filename = System.getProperty("user.home"); + } + } + + if (chooser.isMultiSelectionEnabled() && filename.length() > 1 && + filename.charAt(0) == '"' && filename.charAt(filename.length() - 1) == '"') { + List fList = new ArrayList(); + + String[] files = filename.substring(1, filename.length() - 1).split("\" \""); + // Optimize searching files by names in "children" array + Arrays.sort(files); + + File[] children = null; + int childIndex = 0; + + for (String str : files) { + File file = fs.createFileObject(str); + if (!file.isAbsolute()) { + if (children == null) { + children = fs.getFiles(dir, false); + Arrays.sort(children); + } + for (int k = 0; k < children.length; k++) { + int l = (childIndex + k) % children.length; + if (children[l].getName().equals(str)) { + file = children[l]; + childIndex = l + 1; + break; + } + } + } + fList.add(file); + } + + if (!fList.isEmpty()) { + selectedFiles = fList.toArray(new File[fList.size()]); + } + resetGlobFilter(); + } else { + selectedFile = fs.createFileObject(filename); + if (!selectedFile.isAbsolute()) { + selectedFile = fs.getChild(dir, filename); + } + // check for wildcard pattern + FileFilter currentFilter = chooser.getFileFilter(); + if (!selectedFile.exists() && isGlobPattern(filename)) { + changeDirectory(selectedFile.getParentFile()); + if (globFilter == null) { + globFilter = new GlobFilter(); + } + try { + globFilter.setPattern(selectedFile.getName()); + if (!(currentFilter instanceof GlobFilter)) { + actualFileFilter = currentFilter; + } + chooser.setFileFilter(null); + chooser.setFileFilter(globFilter); + return; + } catch (PatternSyntaxException pse) { + // Not a valid glob pattern. Abandon filter. } } - if (chooser.isMultiSelectionEnabled() && filename.startsWith("\"")) { - ArrayList fList = new ArrayList(); + resetGlobFilter(); - filename = filename.substring(1); - if (filename.endsWith("\"")) { - filename = filename.substring(0, filename.length()-1); - } - File[] children = null; - int childIndex = 0; - do { - String str; - int i = filename.indexOf("\" \""); - if (i > 0) { - str = filename.substring(0, i); - filename = filename.substring(i+3); - } else { - str = filename; - filename = ""; - } - File file = fs.createFileObject(str); - if (!file.isAbsolute()) { - if (children == null) { - children = fs.getFiles(dir, false); - Arrays.sort(children); - } - for (int k = 0; k < children.length; k++) { - int l = (childIndex + k) % children.length; - if (children[l].getName().equals(str)) { - file = children[l]; - childIndex = l + 1; - break; - } - } - } - fList.add(file); - } while (filename.length() > 0); - if (fList.size() > 0) { - selectedFiles = (File[])fList.toArray(new File[fList.size()]); - } - resetGlobFilter(); - } else { - selectedFile = fs.createFileObject(filename); - if(!selectedFile.isAbsolute()) { - selectedFile = fs.getChild(dir, filename); - } - // check for wildcard pattern - FileFilter currentFilter = chooser.getFileFilter(); - if (!selectedFile.exists() && isGlobPattern(filename)) { - changeDirectory(selectedFile.getParentFile()); - if (globFilter == null) { - globFilter = new GlobFilter(); - } - try { - globFilter.setPattern(selectedFile.getName()); - if (!(currentFilter instanceof GlobFilter)) { - actualFileFilter = currentFilter; - } - chooser.setFileFilter(null); - chooser.setFileFilter(globFilter); - return; - } catch (PatternSyntaxException pse) { - // Not a valid glob pattern. Abandon filter. - } - } + // Check for directory change action + boolean isDir = (selectedFile != null && selectedFile.isDirectory()); + boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile)); + boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled(); + boolean isFileSelEnabled = chooser.isFileSelectionEnabled(); + boolean isCtrl = (e != null && (e.getModifiers() & ActionEvent.CTRL_MASK) != 0); - resetGlobFilter(); - - // Check for directory change action - boolean isDir = (selectedFile != null && selectedFile.isDirectory()); - boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile)); - boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled(); - boolean isFileSelEnabled = chooser.isFileSelectionEnabled(); - boolean isCtrl = (e != null && (e.getModifiers() & ActionEvent.CTRL_MASK) != 0); - - if (isDir && isTrav && (isCtrl || !isDirSelEnabled)) { - changeDirectory(selectedFile); - return; - } else if ((isDir || !isFileSelEnabled) - && (!isDir || !isDirSelEnabled) - && (!isDirSelEnabled || selectedFile.exists())) { - selectedFile = null; - } + if (isDir && isTrav && (isCtrl || !isDirSelEnabled)) { + changeDirectory(selectedFile); + return; + } else if ((isDir || !isFileSelEnabled) + && (!isDir || !isDirSelEnabled) + && (!isDirSelEnabled || selectedFile.exists())) { + selectedFile = null; } } + if (selectedFiles != null || selectedFile != null) { if (selectedFiles != null || chooser.isMultiSelectionEnabled()) { if (selectedFiles == null) { @@ -1213,7 +1213,7 @@ } public Icon getCachedIcon(File f) { - return (Icon) iconCache.get(f); + return iconCache.get(f); } public void cacheIcon(File f, Icon i) { @@ -1296,8 +1296,7 @@ htmlBuf.append("\n\n

    \n"); - for (int i = 0; i < values.length; i++) { - Object obj = values[i]; + for (Object obj : values) { String val = ((obj == null) ? "" : obj.toString()); plainBuf.append(val + "\n"); htmlBuf.append("
  • " + val + "\n"); @@ -1337,9 +1336,9 @@ */ protected Object getRicherData(DataFlavor flavor) { if (DataFlavor.javaFileListFlavor.equals(flavor)) { - ArrayList files = new ArrayList(); - for (int i = 0; i < fileData.length; i++) { - files.add(fileData[i]); + ArrayList files = new ArrayList(); + for (Object file : this.fileData) { + files.add(file); } return files; } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java Wed Jul 05 16:42:37 2017 +0200 @@ -266,7 +266,7 @@ return null; } - Icon icon = (Icon) b.getIcon(); + Icon icon = b.getIcon(); String text = b.getText(); Font font = b.getFont(); @@ -277,7 +277,7 @@ Rectangle viewR = new Rectangle(Short.MAX_VALUE, Short.MAX_VALUE); SwingUtilities.layoutCompoundLabel( - (JComponent) b, fm, text, icon, + b, fm, text, icon, b.getVerticalAlignment(), b.getHorizontalAlignment(), b.getVerticalTextPosition(), b.getHorizontalTextPosition(), viewR, iconR, textR, (text == null ? 0 : textIconGap) diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java Wed Jul 05 16:42:37 2017 +0200 @@ -86,6 +86,7 @@ protected Action moveAction; protected Action sizeAction; + // These constants are not used in JDK code protected static final String CLOSE_CMD = UIManager.getString("InternalFrameTitlePane.closeButtonText"); protected static final String ICONIFY_CMD = @@ -268,18 +269,18 @@ } protected void addSystemMenuItems(JMenu systemMenu) { - JMenuItem mi = (JMenuItem)systemMenu.add(restoreAction); + JMenuItem mi = systemMenu.add(restoreAction); mi.setMnemonic('R'); - mi = (JMenuItem)systemMenu.add(moveAction); + mi = systemMenu.add(moveAction); mi.setMnemonic('M'); - mi = (JMenuItem)systemMenu.add(sizeAction); + mi = systemMenu.add(sizeAction); mi.setMnemonic('S'); - mi = (JMenuItem)systemMenu.add(iconifyAction); + mi = systemMenu.add(iconifyAction); mi.setMnemonic('n'); - mi = (JMenuItem)systemMenu.add(maximizeAction); + mi = systemMenu.add(maximizeAction); mi.setMnemonic('x'); systemMenu.add(new JSeparator()); - mi = (JMenuItem)systemMenu.add(closeAction); + mi = systemMenu.add(closeAction); mi.setMnemonic('C'); } @@ -413,7 +414,7 @@ // PropertyChangeListener // public void propertyChange(PropertyChangeEvent evt) { - String prop = (String)evt.getPropertyName(); + String prop = evt.getPropertyName(); if (prop == JInternalFrame.IS_SELECTED_PROPERTY) { repaint(); @@ -428,19 +429,19 @@ } if ("closable" == prop) { - if ((Boolean)evt.getNewValue() == Boolean.TRUE) { + if (evt.getNewValue() == Boolean.TRUE) { add(closeButton); } else { remove(closeButton); } } else if ("maximizable" == prop) { - if ((Boolean)evt.getNewValue() == Boolean.TRUE) { + if (evt.getNewValue() == Boolean.TRUE) { add(maxButton); } else { remove(maxButton); } } else if ("iconable" == prop) { - if ((Boolean)evt.getNewValue() == Boolean.TRUE) { + if (evt.getNewValue() == Boolean.TRUE) { add(iconButton); } else { remove(iconButton); @@ -600,7 +601,8 @@ */ public class CloseAction extends AbstractAction { public CloseAction() { - super(CLOSE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.closeButtonText")); } public void actionPerformed(ActionEvent e) { @@ -616,7 +618,8 @@ */ public class MaximizeAction extends AbstractAction { public MaximizeAction() { - super(MAXIMIZE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.maximizeButtonText")); } public void actionPerformed(ActionEvent evt) { @@ -644,7 +647,8 @@ */ public class IconifyAction extends AbstractAction { public IconifyAction() { - super(ICONIFY_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.minimizeButtonText")); } public void actionPerformed(ActionEvent e) { @@ -664,7 +668,8 @@ */ public class RestoreAction extends AbstractAction { public RestoreAction() { - super(RESTORE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.restoreButtonText")); } public void actionPerformed(ActionEvent evt) { @@ -690,7 +695,8 @@ */ public class MoveAction extends AbstractAction { public MoveAction() { - super(MOVE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.moveButtonText")); } public void actionPerformed(ActionEvent e) { @@ -723,7 +729,8 @@ */ public class SizeAction extends AbstractAction { public SizeAction() { - super(SIZE_CMD); + super(UIManager.getString( + "InternalFrameTitlePane.sizeButtonText")); } public void actionPerformed(ActionEvent e) { @@ -774,7 +781,7 @@ } } public boolean isFocusTraversable() { return false; } - public void requestFocus() {}; + public void requestFocus() {} public AccessibleContext getAccessibleContext() { AccessibleContext ac = super.getAccessibleContext(); if (uiKey != null) { @@ -783,6 +790,6 @@ } return ac; } - }; // end NoFocusButton + } // end NoFocusButton } // End Title Pane Class diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,7 +55,6 @@ protected MouseInputAdapter borderListener; protected PropertyChangeListener propertyChangeListener; protected LayoutManager internalFrameLayout; - protected ComponentListener componentListener; protected MouseInputListener glassPaneDispatcher; private InternalFrameListener internalFrameListener; @@ -67,9 +66,9 @@ protected BasicInternalFrameTitlePane titlePane; // access needs this private static DesktopManager sharedDesktopManager; - private boolean componentListenerAdded = false; private Rectangle parentBounds; + private DesktopIconMover desktopIconMover; private boolean dragging = false; private boolean resizing = false; @@ -210,14 +209,17 @@ frame.getGlassPane().addMouseListener(glassPaneDispatcher); frame.getGlassPane().addMouseMotionListener(glassPaneDispatcher); } - componentListener = createComponentListener(); if (frame.getParent() != null) { parentBounds = frame.getParent().getBounds(); } - if ((frame.getParent() != null) && !componentListenerAdded) { - frame.getParent().addComponentListener(componentListener); - componentListenerAdded = true; + getDesktopIconMover().installListeners(); + } + + private DesktopIconMover getDesktopIconMover() { + if (desktopIconMover == null) { + desktopIconMover = new DesktopIconMover(frame); } + return desktopIconMover; } // Provide a FocusListener to listen for a WINDOW_LOST_FOCUS event, @@ -288,11 +290,7 @@ * @since 1.3 */ protected void uninstallListeners() { - if ((frame.getParent() != null) && componentListenerAdded) { - frame.getParent().removeComponentListener(componentListener); - componentListenerAdded = false; - } - componentListener = null; + getDesktopIconMover().uninstallListeners(); if (glassPaneDispatcher != null) { frame.getGlassPane().removeMouseListener(glassPaneDispatcher); frame.getGlassPane().removeMouseMotionListener(glassPaneDispatcher); @@ -320,7 +318,7 @@ if (resizing) { return; } - Cursor s = (Cursor)frame.getLastCursor(); + Cursor s = frame.getLastCursor(); if (s == null) { s = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); } @@ -338,13 +336,13 @@ public Dimension getPreferredSize(JComponent x) { - if((JComponent)frame == x) + if(frame == x) return frame.getLayout().preferredLayoutSize(x); return new Dimension(100, 100); } public Dimension getMinimumSize(JComponent x) { - if((JComponent)frame == x) { + if(frame == x) { return frame.getLayout().minimumLayoutSize(x); } return new Dimension(0, 0); @@ -1095,7 +1093,7 @@ updateFrameCursor(); } - }; /// End BorderListener Class + } /// End BorderListener Class protected class ComponentHandler implements ComponentListener { // NOTE: This class exists only for backward compatability. All @@ -1198,7 +1196,6 @@ } } - private static boolean isDragging = false; private class Handler implements ComponentListener, InternalFrameListener, LayoutManager, MouseInputListener, PropertyChangeListener, WindowFocusListener, SwingConstants { @@ -1230,15 +1227,6 @@ } } - // Relocate the icon base on the new parent bounds. - if (icon != null) { - Rectangle iconBounds = icon.getBounds(); - int y = iconBounds.y + - (parentNewBounds.height - parentBounds.height); - icon.setBounds(iconBounds.x, y, - iconBounds.width, iconBounds.height); - } - // Update the new parent bounds for next resize. if (!parentBounds.equals(parentNewBounds)) { parentBounds = parentNewBounds; @@ -1384,9 +1372,6 @@ // MouseInputListener - private Component mouseEventTarget = null; - private Component dragSource = null; - public void mousePressed(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } @@ -1403,7 +1388,7 @@ // PropertyChangeListener public void propertyChange(PropertyChangeEvent evt) { - String prop = (String)evt.getPropertyName(); + String prop = evt.getPropertyName(); JInternalFrame f = (JInternalFrame)evt.getSource(); Object newValue = evt.getNewValue(); Object oldValue = evt.getOldValue(); @@ -1413,10 +1398,6 @@ // Cancel a resize in progress if the internal frame // gets a setClosed(true) or dispose(). cancelResize(); - if ((frame.getParent() != null) && componentListenerAdded) { - frame.getParent().removeComponentListener( - componentListener); - } closeFrame(f); } } else if (JInternalFrame.IS_MAXIMUM_PROPERTY == prop) { @@ -1449,16 +1430,6 @@ } else { parentBounds = null; } - if ((frame.getParent() != null) && !componentListenerAdded) { - f.getParent().addComponentListener(componentListener); - componentListenerAdded = true; - } else if ((newValue == null) && componentListenerAdded) { - if (f.getParent() != null) { - f.getParent().removeComponentListener( - componentListener); - } - componentListenerAdded = false; - } } else if (JInternalFrame.TITLE_PROPERTY == prop || prop == "closable" || prop == "iconable" || prop == "maximizable") { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicLabelUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicLabelUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicLabelUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -65,6 +65,9 @@ protected static BasicLabelUI labelUI = new BasicLabelUI(); private final static BasicLabelUI SAFE_BASIC_LABEL_UI = new BasicLabelUI(); + private Rectangle paintIconR = new Rectangle(); + private Rectangle paintTextR = new Rectangle(); + static void loadActionMap(LazyActionMap map) { map.put(new Actions(Actions.PRESS)); map.put(new Actions(Actions.RELEASE)); @@ -135,17 +138,6 @@ textX, textY); } - - /* These rectangles/insets are allocated once for this shared LabelUI - * implementation. Re-using rectangles rather than allocating - * them in each paint call halved the time it took paint to run. - */ - private static Rectangle paintIconR = new Rectangle(); - private static Rectangle paintTextR = new Rectangle(); - private static Rectangle paintViewR = new Rectangle(); - private static Insets paintViewInsets = new Insets(0, 0, 0, 0); - - /** * Paint the label text in the foreground color, if the label * is opaque then paint the entire background with the background @@ -194,10 +186,11 @@ private String layout(JLabel label, FontMetrics fm, int width, int height) { - Insets insets = label.getInsets(paintViewInsets); + Insets insets = label.getInsets(null); String text = label.getText(); Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon(); + Rectangle paintViewR = new Rectangle(); paintViewR.x = insets.left; paintViewR.y = insets.top; paintViewR.width = width - (insets.left + insets.right); @@ -208,24 +201,13 @@ paintTextR); } - - /* These rectangles/insets are allocated once for this shared LabelUI - * implementation. Re-using rectangles rather than allocating - * them in each getPreferredSize call sped up the method substantially. - */ - private static Rectangle iconR = new Rectangle(); - private static Rectangle textR = new Rectangle(); - private static Rectangle viewR = new Rectangle(); - private static Insets viewInsets = new Insets(0, 0, 0, 0); - - public Dimension getPreferredSize(JComponent c) { JLabel label = (JLabel)c; String text = label.getText(); Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon(); - Insets insets = label.getInsets(viewInsets); + Insets insets = label.getInsets(null); Font font = label.getFont(); int dx = insets.left + insets.right; @@ -242,6 +224,9 @@ } else { FontMetrics fm = label.getFontMetrics(font); + Rectangle iconR = new Rectangle(); + Rectangle textR = new Rectangle(); + Rectangle viewR = new Rectangle(); iconR.x = iconR.y = iconR.width = iconR.height = 0; textR.x = textR.y = textR.width = textR.height = 0; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java Wed Jul 05 16:42:37 2017 +0200 @@ -2102,8 +2102,6 @@ * soundFile passed into this method, it will * return null. * - * @param baseClass used as the root class/location to get the - * soundFile from * @param soundFile the name of the audio file to be retrieved * from disk * @return A byte[] with audio data or null @@ -2120,9 +2118,9 @@ * Class.getResourceAsStream just returns raw * bytes, which we can convert to a sound. */ - byte[] buffer = (byte[])AccessController.doPrivileged( - new PrivilegedAction() { - public Object run() { + byte[] buffer = AccessController.doPrivileged( + new PrivilegedAction() { + public byte[] run() { try { InputStream resource = BasicLookAndFeel.this. getClass().getResourceAsStream(soundFile); @@ -2184,9 +2182,9 @@ UIManager.get("AuditoryCues.playList"); if (audioStrings != null) { // create a HashSet to help us decide to play or not - HashSet audioCues = new HashSet(); - for (int i = 0; i < audioStrings.length; i++) { - audioCues.add(audioStrings[i]); + HashSet audioCues = new HashSet(); + for (Object audioString : audioStrings) { + audioCues.add(audioString); } // get the name of the Action String actionName = (String)audioAction.getValue(Action.NAME); @@ -2237,7 +2235,7 @@ * This class contains listener that watches for all the mouse * events that can possibly invoke popup on the component */ - class AWTEventHelper implements AWTEventListener,PrivilegedAction { + class AWTEventHelper implements AWTEventListener,PrivilegedAction { AWTEventHelper() { super(); AccessController.doPrivileged(this); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -25,9 +25,6 @@ package javax.swing.plaf.basic; -import sun.swing.MenuItemCheckIconFactory; -import sun.swing.SwingUtilities2; -import static sun.swing.SwingUtilities2.BASICMENUITEMUI_MAX_TEXT_OFFSET; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; @@ -39,8 +36,7 @@ import javax.swing.plaf.*; import javax.swing.text.View; -import sun.swing.UIAction; -import sun.swing.StringUIClientPropertyKey; +import sun.swing.*; /** * BasicMenuItem implementation @@ -91,24 +87,6 @@ private static final boolean VERBOSE = false; // show reuse hits/misses private static final boolean DEBUG = false; // show bad params, misc. - // Allows to reuse layoutInfo object. - // Shouldn't be used directly. Use getLayoutInfo() instead. - private final transient LayoutInfo layoutInfo = new LayoutInfo(); - - /* Client Property keys for calculation of maximal widths */ - static final StringUIClientPropertyKey MAX_ARROW_WIDTH = - new StringUIClientPropertyKey("maxArrowWidth"); - static final StringUIClientPropertyKey MAX_CHECK_WIDTH = - new StringUIClientPropertyKey("maxCheckWidth"); - static final StringUIClientPropertyKey MAX_ICON_WIDTH = - new StringUIClientPropertyKey("maxIconWidth"); - static final StringUIClientPropertyKey MAX_TEXT_WIDTH = - new StringUIClientPropertyKey("maxTextWidth"); - static final StringUIClientPropertyKey MAX_ACC_WIDTH = - new StringUIClientPropertyKey("maxAccWidth"); - static final StringUIClientPropertyKey MAX_LABEL_WIDTH = - new StringUIClientPropertyKey("maxLabelWidth"); - static void loadActionMap(LazyActionMap map) { // NOTE: BasicMenuUI also calls into this method. map.put(new Actions(Actions.CLICK)); @@ -199,13 +177,14 @@ //In case of column layout, .checkIconFactory is defined for this UI, //the icon is compatible with it and useCheckAndArrow() is true, //then the icon is handled by the checkIcon. - boolean isColumnLayout = LayoutInfo.isColumnLayout( + boolean isColumnLayout = MenuItemLayoutHelper.isColumnLayout( BasicGraphicsUtils.isLeftToRight(menuItem), menuItem); if (isColumnLayout) { MenuItemCheckIconFactory iconFactory = (MenuItemCheckIconFactory) UIManager.get(prefix + ".checkIconFactory"); - if (iconFactory != null && useCheckAndArrow() + if (iconFactory != null + && MenuItemLayoutHelper.useCheckAndArrow(menuItem) && iconFactory.isCompatible(checkIcon, prefix)) { checkIcon = iconFactory.getIcon(menuItem); } @@ -256,20 +235,7 @@ uninstallComponents(menuItem); uninstallListeners(); uninstallKeyboardActions(); - - - // Remove values from the parent's Client Properties. - JComponent p = getMenuItemParent(menuItem); - if(p != null) { - p.putClientProperty(BasicMenuItemUI.MAX_ARROW_WIDTH, null ); - p.putClientProperty(BasicMenuItemUI.MAX_CHECK_WIDTH, null ); - p.putClientProperty(BasicMenuItemUI.MAX_ACC_WIDTH, null ); - p.putClientProperty(BasicMenuItemUI.MAX_TEXT_WIDTH, null ); - p.putClientProperty(BasicMenuItemUI.MAX_ICON_WIDTH, null ); - p.putClientProperty(BasicMenuItemUI.MAX_LABEL_WIDTH, null ); - p.putClientProperty(BASICMENUITEMUI_MAX_TEXT_OFFSET, null ); - } - + MenuItemLayoutHelper.clearUsedParentClientProperties(menuItem); menuItem = null; } @@ -405,19 +371,6 @@ return d; } - // Returns parent of this component if it is not a top-level menu - // Otherwise returns null - private static JComponent getMenuItemParent(JMenuItem mi) { - Container parent = mi.getParent(); - if ((parent instanceof JComponent) && - (!(mi instanceof JMenu) || - !((JMenu)mi).isTopLevelMenu())) { - return (JComponent) parent; - } else { - return null; - } - } - protected Dimension getPreferredMenuItemSize(JComponent c, Icon checkIcon, Icon arrowIcon, @@ -447,32 +400,36 @@ // the icon and text when user points a menu item by mouse. JMenuItem mi = (JMenuItem) c; - LayoutInfo li = getLayoutInfo(mi, checkIcon, arrowIcon, - createMaxViewRect(), defaultTextIconGap, acceleratorDelimiter, - BasicGraphicsUtils.isLeftToRight(mi), acceleratorFont, - useCheckAndArrow(), getPropertyPrefix()); + MenuItemLayoutHelper lh = new MenuItemLayoutHelper(mi, checkIcon, + arrowIcon, MenuItemLayoutHelper.createMaxRect(), defaultTextIconGap, + acceleratorDelimiter, BasicGraphicsUtils.isLeftToRight(mi), + mi.getFont(), acceleratorFont, + MenuItemLayoutHelper.useCheckAndArrow(menuItem), + getPropertyPrefix()); Dimension result = new Dimension(); // Calculate the result width - result.width = li.leadingGap; - addWidth(li.maxCheckWidth, li.afterCheckIconGap, result); + result.width = lh.getLeadingGap(); + MenuItemLayoutHelper.addMaxWidth(lh.getCheckSize(), + lh.getAfterCheckIconGap(), result); // Take into account mimimal text offset. - if ((!li.isTopLevelMenu) - && (li.minTextOffset > 0) - && (result.width < li.minTextOffset)) { - result.width = li.minTextOffset; + if ((!lh.isTopLevelMenu()) + && (lh.getMinTextOffset() > 0) + && (result.width < lh.getMinTextOffset())) { + result.width = lh.getMinTextOffset(); } - addWidth(li.maxLabelWidth, li.gap, result); - addWidth(li.maxAccWidth, li.gap, result); - addWidth(li.maxArrowWidth, li.gap, result); + MenuItemLayoutHelper.addMaxWidth(lh.getLabelSize(), lh.getGap(), result); + MenuItemLayoutHelper.addMaxWidth(lh.getAccSize(), lh.getGap(), result); + MenuItemLayoutHelper.addMaxWidth(lh.getArrowSize(), lh.getGap(), result); // Calculate the result height - result.height = max(li.checkRect.height, li.labelRect.height, - li.accRect.height, li.arrowRect.height); + result.height = MenuItemLayoutHelper.max(lh.getCheckSize().getHeight(), + lh.getLabelSize().getHeight(), lh.getAccSize().getHeight(), + lh.getArrowSize().getHeight()); // Take into account menu item insets - Insets insets = li.mi.getInsets(); + Insets insets = lh.getMenuItem().getInsets(); if(insets != null) { result.width += insets.left + insets.right; result.height += insets.top + insets.bottom; @@ -492,500 +449,9 @@ result.height++; } - li.clear(); return result; } - private Rectangle createMaxViewRect() { - return new Rectangle(0,0,Short.MAX_VALUE, Short.MAX_VALUE); - } - - private void addWidth(int width, int gap, Dimension result) { - if (width > 0) { - result.width += width + gap; - } - } - - private static int max(int... values) { - int maxValue = Integer.MIN_VALUE; - for (int i : values) { - if (i > maxValue) { - maxValue = i; - } - } - return maxValue; - } - - // LayoutInfo helps to calculate preferred size and to paint a menu item - private static class LayoutInfo { - JMenuItem mi; - JComponent miParent; - - FontMetrics fm; - FontMetrics accFm; - - Icon icon; - Icon checkIcon; - Icon arrowIcon; - String text; - String accText; - - boolean isColumnLayout; - boolean useCheckAndArrow; - boolean isLeftToRight; - boolean isTopLevelMenu; - View htmlView; - - int verticalAlignment; - int horizontalAlignment; - int verticalTextPosition; - int horizontalTextPosition; - int gap; - int leadingGap; - int afterCheckIconGap; - int minTextOffset; - - Rectangle viewRect; - Rectangle iconRect; - Rectangle textRect; - Rectangle accRect; - Rectangle checkRect; - Rectangle arrowRect; - Rectangle labelRect; - - int origIconWidth; - int origTextWidth; - int origAccWidth; - int origCheckWidth; - int origArrowWidth; - - int maxIconWidth; - int maxTextWidth; - int maxAccWidth; - int maxCheckWidth; - int maxArrowWidth; - int maxLabelWidth; - - // Empty constructor helps to create "final" LayoutInfo object - public LayoutInfo() { - } - - public LayoutInfo(JMenuItem mi, Icon checkIcon, Icon arrowIcon, - Rectangle viewRect, int gap, String accDelimiter, - boolean isLeftToRight, Font acceleratorFont, - boolean useCheckAndArrow, String propertyPrefix) { - reset(mi, checkIcon, arrowIcon, viewRect, gap, accDelimiter, - isLeftToRight, acceleratorFont, useCheckAndArrow, - propertyPrefix); - } - - // Allows to reuse a LayoutInfo object - public void reset(JMenuItem mi, Icon checkIcon, Icon arrowIcon, - Rectangle viewRect, int gap, String accDelimiter, - boolean isLeftToRight, Font acceleratorFont, - boolean useCheckAndArrow, String propertyPrefix) { - this.mi = mi; - this.miParent = getMenuItemParent(mi); - this.accText = getAccText(accDelimiter); - this.verticalAlignment = mi.getVerticalAlignment(); - this.horizontalAlignment = mi.getHorizontalAlignment(); - this.verticalTextPosition = mi.getVerticalTextPosition(); - this.horizontalTextPosition = mi.getHorizontalTextPosition(); - this.useCheckAndArrow = useCheckAndArrow; - this.fm = mi.getFontMetrics(mi.getFont()); - this.accFm = mi.getFontMetrics(acceleratorFont); - this.isLeftToRight = isLeftToRight; - this.isColumnLayout = isColumnLayout(); - this.isTopLevelMenu = (this.miParent == null)? true : false; - this.checkIcon = checkIcon; - this.icon = getIcon(propertyPrefix); - this.arrowIcon = arrowIcon; - this.text = mi.getText(); - this.gap = gap; - this.afterCheckIconGap = getAfterCheckIconGap(propertyPrefix); - this.minTextOffset = getMinTextOffset(propertyPrefix); - this.htmlView = (View) mi.getClientProperty(BasicHTML.propertyKey); - - this.viewRect = viewRect; - this.iconRect = new Rectangle(); - this.textRect = new Rectangle(); - this.accRect = new Rectangle(); - this.checkRect = new Rectangle(); - this.arrowRect = new Rectangle(); - this.labelRect = new Rectangle(); - - calcWidthsAndHeights(); - this.origIconWidth = iconRect.width; - this.origTextWidth = textRect.width; - this.origAccWidth = accRect.width; - this.origCheckWidth = checkRect.width; - this.origArrowWidth = arrowRect.width; - - calcMaxWidths(); - this.leadingGap = getLeadingGap(propertyPrefix); - calcMaxTextOffset(); - } - - // Clears fields to remove all links to other objects - // to prevent memory leaks - public void clear() { - mi = null; - miParent = null; - fm = null; - accFm = null; - icon = null; - checkIcon = null; - arrowIcon = null; - text = null; - accText = null; - htmlView = null; - viewRect = null; - iconRect = null; - textRect = null; - accRect = null; - checkRect = null; - arrowRect = null; - labelRect = null; - } - - private String getAccText(String acceleratorDelimiter) { - String accText = ""; - KeyStroke accelerator = mi.getAccelerator(); - if (accelerator != null) { - int modifiers = accelerator.getModifiers(); - if (modifiers > 0) { - accText = KeyEvent.getKeyModifiersText(modifiers); - accText += acceleratorDelimiter; - } - int keyCode = accelerator.getKeyCode(); - if (keyCode != 0) { - accText += KeyEvent.getKeyText(keyCode); - } else { - accText += accelerator.getKeyChar(); - } - } - return accText; - } - - // In case of column layout, .checkIconFactory is defined for this UI, - // the icon is compatible with it and useCheckAndArrow() is true, - // then the icon is handled by the checkIcon. - private Icon getIcon(String propertyPrefix) { - Icon icon = null; - MenuItemCheckIconFactory iconFactory = - (MenuItemCheckIconFactory) UIManager.get(propertyPrefix - + ".checkIconFactory"); - if (!isColumnLayout || !useCheckAndArrow || iconFactory == null - || !iconFactory.isCompatible(checkIcon, propertyPrefix)) { - icon = mi.getIcon(); - } - return icon; - } - - private int getMinTextOffset(String propertyPrefix) { - int minimumTextOffset = 0; - Object minimumTextOffsetObject = - UIManager.get(propertyPrefix + ".minimumTextOffset"); - if (minimumTextOffsetObject instanceof Integer) { - minimumTextOffset = (Integer) minimumTextOffsetObject; - } - return minimumTextOffset; - } - - private int getAfterCheckIconGap(String propertyPrefix) { - int afterCheckIconGap = gap; - Object afterCheckIconGapObject = - UIManager.get(propertyPrefix + ".afterCheckIconGap"); - if (afterCheckIconGapObject instanceof Integer) { - afterCheckIconGap = (Integer) afterCheckIconGapObject; - } - return afterCheckIconGap; - } - - private int getLeadingGap(String propertyPrefix) { - if (maxCheckWidth > 0) { - return getCheckOffset(propertyPrefix); - } else { - return gap; // There is no any check icon - } - } - - private int getCheckOffset(String propertyPrefix) { - int checkIconOffset = gap; - Object checkIconOffsetObject = - UIManager.get(propertyPrefix + ".checkIconOffset"); - if (checkIconOffsetObject instanceof Integer) { - checkIconOffset = (Integer) checkIconOffsetObject; - } - return checkIconOffset; - } - - private void calcWidthsAndHeights() - { - // iconRect - if (icon != null) { - iconRect.width = icon.getIconWidth(); - iconRect.height = icon.getIconHeight(); - } - - // accRect - if (!accText.equals("")) { - accRect.width = SwingUtilities2.stringWidth( - mi, accFm, accText); - accRect.height = accFm.getHeight(); - } - - // textRect - if (text == null) { - text = ""; - } else if (!text.equals("")) { - if (htmlView != null) { - // Text is HTML - textRect.width = - (int) htmlView.getPreferredSpan(View.X_AXIS); - textRect.height = - (int) htmlView.getPreferredSpan(View.Y_AXIS); - } else { - // Text isn't HTML - textRect.width = - SwingUtilities2.stringWidth(mi, fm, text); - textRect.height = fm.getHeight(); - } - } - - if (useCheckAndArrow) { - // checkIcon - if (checkIcon != null) { - checkRect.width = checkIcon.getIconWidth(); - checkRect.height = checkIcon.getIconHeight(); - } - // arrowRect - if (arrowIcon != null) { - arrowRect.width = arrowIcon.getIconWidth(); - arrowRect.height = arrowIcon.getIconHeight(); - } - } - - // labelRect - if (isColumnLayout) { - labelRect.width = iconRect.width + textRect.width + gap; - labelRect.height = max(checkRect.height, iconRect.height, - textRect.height, accRect.height, arrowRect.height); - } else { - textRect = new Rectangle(); - iconRect = new Rectangle(); - SwingUtilities.layoutCompoundLabel(mi, fm, text, icon, - verticalAlignment, horizontalAlignment, - verticalTextPosition, horizontalTextPosition, - viewRect, iconRect, textRect, gap); - labelRect = iconRect.union(textRect); - } - } - - private void calcMaxWidths() { - maxCheckWidth = calcMaxValue(BasicMenuItemUI.MAX_CHECK_WIDTH, - checkRect.width); - maxArrowWidth = calcMaxValue(BasicMenuItemUI.MAX_ARROW_WIDTH, - arrowRect.width); - maxAccWidth = calcMaxValue(BasicMenuItemUI.MAX_ACC_WIDTH, - accRect.width); - - if (isColumnLayout) { - maxIconWidth = calcMaxValue(BasicMenuItemUI.MAX_ICON_WIDTH, - iconRect.width); - maxTextWidth = calcMaxValue(BasicMenuItemUI.MAX_TEXT_WIDTH, - textRect.width); - int curGap = gap; - if ((maxIconWidth == 0) || (maxTextWidth == 0)) { - curGap = 0; - } - maxLabelWidth = - calcMaxValue(BasicMenuItemUI.MAX_LABEL_WIDTH, - maxIconWidth + maxTextWidth + curGap); - } else { - // We shouldn't use current icon and text widths - // in maximal widths calculation for complex layout. - maxIconWidth = getParentIntProperty(BasicMenuItemUI.MAX_ICON_WIDTH); - maxLabelWidth = calcMaxValue(BasicMenuItemUI.MAX_LABEL_WIDTH, - labelRect.width); - // If maxLabelWidth is wider - // than the widest icon + the widest text + gap, - // we should update the maximal text witdh - int candidateTextWidth = maxLabelWidth - maxIconWidth; - if (maxIconWidth > 0) { - candidateTextWidth -= gap; - } - maxTextWidth = calcMaxValue(BasicMenuItemUI.MAX_TEXT_WIDTH, - candidateTextWidth); - } - } - - // Calculates and returns maximal value - // through specified parent component client property. - private int calcMaxValue(Object propertyName, int value) { - // Get maximal value from parent client property - int maxValue = getParentIntProperty(propertyName); - // Store new maximal width in parent client property - if (value > maxValue) { - if (miParent != null) { - miParent.putClientProperty(propertyName, value); - } - return value; - } else { - return maxValue; - } - } - - // Returns parent client property as int - private int getParentIntProperty(Object propertyName) { - Object value = null; - if (miParent != null) { - value = miParent.getClientProperty(propertyName); - } - if ((value == null) || !(value instanceof Integer)){ - value = 0; - } - return (Integer)value; - } - - private boolean isColumnLayout() { - return isColumnLayout(isLeftToRight, horizontalAlignment, - horizontalTextPosition, verticalTextPosition); - } - - public static boolean isColumnLayout(boolean isLeftToRight, - JMenuItem mi) { - assert(mi != null); - return isColumnLayout(isLeftToRight, mi.getHorizontalAlignment(), - mi.getHorizontalTextPosition(), mi.getVerticalTextPosition()); - } - - // Answers should we do column layout for a menu item or not. - // We do it when a user doesn't set any alignments - // and text positions manually, except the vertical alignment. - public static boolean isColumnLayout( boolean isLeftToRight, - int horizontalAlignment, int horizontalTextPosition, - int verticalTextPosition) { - if (verticalTextPosition != SwingConstants.CENTER) { - return false; - } - if (isLeftToRight) { - if (horizontalAlignment != SwingConstants.LEADING - && horizontalAlignment != SwingConstants.LEFT) { - return false; - } - if (horizontalTextPosition != SwingConstants.TRAILING - && horizontalTextPosition != SwingConstants.RIGHT) { - return false; - } - } else { - if (horizontalAlignment != SwingConstants.LEADING - && horizontalAlignment != SwingConstants.RIGHT) { - return false; - } - if (horizontalTextPosition != SwingConstants.TRAILING - && horizontalTextPosition != SwingConstants.LEFT) { - return false; - } - } - return true; - } - - // Calculates maximal text offset. - // It is required for some L&Fs (ex: Vista L&F). - // The offset is meaningful only for L2R column layout. - private void calcMaxTextOffset() { - if (!isColumnLayout || !isLeftToRight) { - return; - } - - // Calculate the current text offset - int offset = viewRect.x + leadingGap + maxCheckWidth - + afterCheckIconGap + maxIconWidth + gap; - if (maxCheckWidth == 0) { - offset -= afterCheckIconGap; - } - if (maxIconWidth == 0) { - offset -= gap; - } - - // maximal text offset shouldn't be less than minimal text offset; - if (offset < minTextOffset) { - offset = minTextOffset; - } - - // Calculate and store the maximal text offset - calcMaxValue(BASICMENUITEMUI_MAX_TEXT_OFFSET, offset); - } - - public String toString() { - StringBuilder result = new StringBuilder(); - result.append(super.toString()).append("\n"); - result.append("accFm = ").append(accFm).append("\n"); - result.append("accRect = ").append(accRect).append("\n"); - result.append("accText = ").append(accText).append("\n"); - result.append("afterCheckIconGap = ").append(afterCheckIconGap) - .append("\n"); - result.append("arrowIcon = ").append(arrowIcon).append("\n"); - result.append("arrowRect = ").append(arrowRect).append("\n"); - result.append("checkIcon = ").append(checkIcon).append("\n"); - result.append("checkRect = ").append(checkRect).append("\n"); - result.append("fm = ").append(fm).append("\n"); - result.append("gap = ").append(gap).append("\n"); - result.append("horizontalAlignment = ").append(horizontalAlignment) - .append("\n"); - result.append("horizontalTextPosition = ") - .append(horizontalTextPosition).append("\n"); - result.append("htmlView = ").append(htmlView).append("\n"); - result.append("icon = ").append(icon).append("\n"); - result.append("iconRect = ").append(iconRect).append("\n"); - result.append("isColumnLayout = ").append(isColumnLayout).append("\n"); - result.append("isLeftToRight = ").append(isLeftToRight).append("\n"); - result.append("isTopLevelMenu = ").append(isTopLevelMenu).append("\n"); - result.append("labelRect = ").append(labelRect).append("\n"); - result.append("leadingGap = ").append(leadingGap).append("\n"); - result.append("maxAccWidth = ").append(maxAccWidth).append("\n"); - result.append("maxArrowWidth = ").append(maxArrowWidth).append("\n"); - result.append("maxCheckWidth = ").append(maxCheckWidth).append("\n"); - result.append("maxIconWidth = ").append(maxIconWidth).append("\n"); - result.append("maxLabelWidth = ").append(maxLabelWidth).append("\n"); - result.append("maxTextWidth = ").append(maxTextWidth).append("\n"); - result.append("maxTextOffset = ") - .append(getParentIntProperty(BASICMENUITEMUI_MAX_TEXT_OFFSET)) - .append("\n"); - result.append("mi = ").append(mi).append("\n"); - result.append("minTextOffset = ").append(minTextOffset).append("\n"); - result.append("miParent = ").append(miParent).append("\n"); - result.append("origAccWidth = ").append(origAccWidth).append("\n"); - result.append("origArrowWidth = ").append(origArrowWidth).append("\n"); - result.append("origCheckWidth = ").append(origCheckWidth).append("\n"); - result.append("origIconWidth = ").append(origIconWidth).append("\n"); - result.append("origTextWidth = ").append(origTextWidth).append("\n"); - result.append("text = ").append(text).append("\n"); - result.append("textRect = ").append(textRect).append("\n"); - result.append("useCheckAndArrow = ").append(useCheckAndArrow) - .append("\n"); - result.append("verticalAlignment = ").append(verticalAlignment) - .append("\n"); - result.append("verticalTextPosition = ") - .append(verticalTextPosition).append("\n"); - result.append("viewRect = ").append(viewRect).append("\n"); - return result.toString(); - } - } // End of LayoutInfo - - // Reuses layoutInfo object to reduce the amount of produced garbage - private LayoutInfo getLayoutInfo(JMenuItem mi, Icon checkIcon, Icon arrowIcon, - Rectangle viewRect, int gap, String accDelimiter, - boolean isLeftToRight, Font acceleratorFont, - boolean useCheckAndArrow, String propertyPrefix) { - // layoutInfo is final and always not null - layoutInfo.reset(mi, checkIcon, arrowIcon, viewRect, - gap, accDelimiter, isLeftToRight, acceleratorFont, - useCheckAndArrow, propertyPrefix); - return layoutInfo; - } - /** * We draw the background in paintMenuItem() * so override update (which fills the background of opaque @@ -1016,122 +482,132 @@ Rectangle viewRect = new Rectangle(0, 0, mi.getWidth(), mi.getHeight()); applyInsets(viewRect, mi.getInsets()); - LayoutInfo li = getLayoutInfo(mi, checkIcon, arrowIcon, - viewRect, defaultTextIconGap, acceleratorDelimiter, - BasicGraphicsUtils.isLeftToRight(mi), acceleratorFont, - useCheckAndArrow(), getPropertyPrefix()); - layoutMenuItem(li); + MenuItemLayoutHelper lh = new MenuItemLayoutHelper(mi, checkIcon, + arrowIcon, viewRect, defaultTextIconGap, acceleratorDelimiter, + BasicGraphicsUtils.isLeftToRight(mi), mi.getFont(), + acceleratorFont, MenuItemLayoutHelper.useCheckAndArrow(menuItem), + getPropertyPrefix()); + MenuItemLayoutHelper.LayoutResult lr = lh.layoutMenuItem(); paintBackground(g, mi, background); - paintCheckIcon(g, li, holdc, foreground); - paintIcon(g, li, holdc); - paintText(g, li); - paintAccText(g, li); - paintArrowIcon(g, li, foreground); + paintCheckIcon(g, lh, lr, holdc, foreground); + paintIcon(g, lh, lr, holdc); + paintText(g, lh, lr); + paintAccText(g, lh, lr); + paintArrowIcon(g, lh, lr, foreground); // Restore original graphics font and color g.setColor(holdc); g.setFont(holdf); - - li.clear(); } - private void paintIcon(Graphics g, LayoutInfo li, Color holdc) { - if (li.icon != null) { + private void paintIcon(Graphics g, MenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr, Color holdc) { + if (lh.getIcon() != null) { Icon icon; - ButtonModel model = li.mi.getModel(); + ButtonModel model = lh.getMenuItem().getModel(); if (!model.isEnabled()) { - icon = (Icon) li.mi.getDisabledIcon(); + icon = lh.getMenuItem().getDisabledIcon(); } else if (model.isPressed() && model.isArmed()) { - icon = (Icon) li.mi.getPressedIcon(); + icon = lh.getMenuItem().getPressedIcon(); if (icon == null) { // Use default icon - icon = (Icon) li.mi.getIcon(); + icon = lh.getMenuItem().getIcon(); } } else { - icon = (Icon) li.mi.getIcon(); + icon = lh.getMenuItem().getIcon(); } if (icon != null) { - icon.paintIcon(li.mi, g, li.iconRect.x, li.iconRect.y); + icon.paintIcon(lh.getMenuItem(), g, lr.getIconRect().x, + lr.getIconRect().y); g.setColor(holdc); } } } - private void paintCheckIcon(Graphics g, LayoutInfo li, + private void paintCheckIcon(Graphics g, MenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr, Color holdc, Color foreground) { - if (li.checkIcon != null) { - ButtonModel model = li.mi.getModel(); - if (model.isArmed() - || (li.mi instanceof JMenu && model.isSelected())) { + if (lh.getCheckIcon() != null) { + ButtonModel model = lh.getMenuItem().getModel(); + if (model.isArmed() || (lh.getMenuItem() instanceof JMenu + && model.isSelected())) { g.setColor(foreground); } else { g.setColor(holdc); } - if (li.useCheckAndArrow) { - li.checkIcon.paintIcon(li.mi, g, li.checkRect.x, - li.checkRect.y); + if (lh.useCheckAndArrow()) { + lh.getCheckIcon().paintIcon(lh.getMenuItem(), g, + lr.getCheckRect().x, lr.getCheckRect().y); } g.setColor(holdc); } } - private void paintAccText(Graphics g, LayoutInfo li) { - if (!li.accText.equals("")) { - ButtonModel model = li.mi.getModel(); - g.setFont(acceleratorFont); + private void paintAccText(Graphics g, MenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + if (!lh.getAccText().equals("")) { + ButtonModel model = lh.getMenuItem().getModel(); + g.setFont(lh.getAccFontMetrics().getFont()); if (!model.isEnabled()) { // *** paint the accText disabled if (disabledForeground != null) { g.setColor(disabledForeground); - SwingUtilities2.drawString(li.mi, g, li.accText, - li.accRect.x, - li.accRect.y + li.accFm.getAscent()); + SwingUtilities2.drawString(lh.getMenuItem(), g, + lh.getAccText(), lr.getAccRect().x, + lr.getAccRect().y + lh.getAccFontMetrics().getAscent()); } else { - g.setColor(li.mi.getBackground().brighter()); - SwingUtilities2.drawString(li.mi, g, li.accText, li.accRect.x, - li.accRect.y + li.accFm.getAscent()); - g.setColor(li.mi.getBackground().darker()); - SwingUtilities2.drawString(li.mi, g, li.accText, - li.accRect.x - 1, - li.accRect.y + li.accFm.getAscent() - 1); + g.setColor(lh.getMenuItem().getBackground().brighter()); + SwingUtilities2.drawString(lh.getMenuItem(), g, + lh.getAccText(), lr.getAccRect().x, + lr.getAccRect().y + lh.getAccFontMetrics().getAscent()); + g.setColor(lh.getMenuItem().getBackground().darker()); + SwingUtilities2.drawString(lh.getMenuItem(), g, + lh.getAccText(), lr.getAccRect().x - 1, + lr.getAccRect().y + lh.getFontMetrics().getAscent() - 1); } } else { // *** paint the accText normally - if (model.isArmed() || - (li.mi instanceof JMenu && model.isSelected())) { + if (model.isArmed() + || (lh.getMenuItem() instanceof JMenu + && model.isSelected())) { g.setColor(acceleratorSelectionForeground); } else { g.setColor(acceleratorForeground); } - SwingUtilities2.drawString(li.mi, g, li.accText, li.accRect.x, - li.accRect.y + li.accFm.getAscent()); + SwingUtilities2.drawString(lh.getMenuItem(), g, lh.getAccText(), + lr.getAccRect().x, lr.getAccRect().y + + lh.getAccFontMetrics().getAscent()); } } } - private void paintText(Graphics g, LayoutInfo li) { - if (!li.text.equals("")) { - if (li.htmlView != null) { + private void paintText(Graphics g, MenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + if (!lh.getText().equals("")) { + if (lh.getHtmlView() != null) { // Text is HTML - li.htmlView.paint(g, li.textRect); + lh.getHtmlView().paint(g, lr.getTextRect()); } else { // Text isn't HTML - paintText(g, li.mi, li.textRect, li.text); + paintText(g, lh.getMenuItem(), lr.getTextRect(), lh.getText()); } } } - private void paintArrowIcon(Graphics g, LayoutInfo li, Color foreground) { - if (li.arrowIcon != null) { - ButtonModel model = li.mi.getModel(); - if (model.isArmed() - || (li.mi instanceof JMenu && model.isSelected())) { + private void paintArrowIcon(Graphics g, MenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr, + Color foreground) { + if (lh.getArrowIcon() != null) { + ButtonModel model = lh.getMenuItem().getModel(); + if (model.isArmed() || (lh.getMenuItem() instanceof JMenu + && model.isSelected())) { g.setColor(foreground); } - if (li.useCheckAndArrow) { - li.arrowIcon.paintIcon(li.mi, g, li.arrowRect.x, li.arrowRect.y); + if (lh.useCheckAndArrow()) { + lh.getArrowIcon().paintIcon(lh.getMenuItem(), g, + lr.getArrowRect().x, lr.getArrowRect().y); } } } @@ -1216,346 +692,6 @@ } } - - /** - * Layout icon, text, check icon, accelerator text and arrow icon - * in the viewRect and return their positions. - * - * If horizontalAlignment, verticalTextPosition and horizontalTextPosition - * are default (user doesn't set any manually) the layouting algorithm is: - * Elements are layouted in the five columns: - * check icon + icon + text + accelerator text + arrow icon - * - * In the other case elements are layouted in the four columns: - * check icon + label + accelerator text + arrow icon - * Label is icon and text rectangles union. - * - * The order of columns can be reversed. - * It depends on the menu item orientation. - */ - private void layoutMenuItem(LayoutInfo li) - { - li.checkRect.width = li.maxCheckWidth; - li.accRect.width = li.maxAccWidth; - li.arrowRect.width = li.maxArrowWidth; - - if (li.isColumnLayout) { - if (li.isLeftToRight) { - doLTRColumnLayout(li); - } else { - doRTLColumnLayout(li); - } - } else { - if (li.isLeftToRight) { - doLTRComplexLayout(li); - } else { - doRTLComplexLayout(li); - } - } - - alignAccCheckAndArrowVertically(li); - } - - // Aligns the accelertor text and the check and arrow icons vertically - // with the center of the label rect. - private void alignAccCheckAndArrowVertically(LayoutInfo li) { - li.accRect.y = (int)(li.labelRect.y + (float)li.labelRect.height/2 - - (float)li.accRect.height/2); - fixVerticalAlignment(li, li.accRect); - if (li.useCheckAndArrow) { - li.arrowRect.y = (int)(li.labelRect.y + (float)li.labelRect.height/2 - - (float)li.arrowRect.height/2); - li.checkRect.y = (int)(li.labelRect.y + (float)li.labelRect.height/2 - - (float)li.checkRect.height/2); - fixVerticalAlignment(li, li.arrowRect); - fixVerticalAlignment(li, li.checkRect); - } - } - - // Fixes vertical alignment of all menu item elements if a rect.y - // or (rect.y + rect.height) is out of viewRect bounds - private void fixVerticalAlignment(LayoutInfo li, Rectangle r) { - int delta = 0; - if (r.y < li.viewRect.y) { - delta = li.viewRect.y - r.y; - } else if (r.y + r.height > li.viewRect.y + li.viewRect.height) { - delta = li.viewRect.y + li.viewRect.height - r.y - r.height; - } - if (delta != 0) { - li.checkRect.y += delta; - li.iconRect.y += delta; - li.textRect.y += delta; - li.accRect.y += delta; - li.arrowRect.y += delta; - } - } - - private void doLTRColumnLayout(LayoutInfo li) { - // Set maximal width for all the five basic rects - // (three other ones are already maximal) - li.iconRect.width = li.maxIconWidth; - li.textRect.width = li.maxTextWidth; - - // Set X coordinates - // All rects will be aligned at the left side - calcXPositionsL2R(li.viewRect.x, li.leadingGap, li.gap, li.checkRect, - li.iconRect, li.textRect); - - // Tune afterCheckIconGap - if (li.checkRect.width > 0) { // there is the afterCheckIconGap - li.iconRect.x += li.afterCheckIconGap - li.gap; - li.textRect.x += li.afterCheckIconGap - li.gap; - } - - calcXPositionsR2L(li.viewRect.x + li.viewRect.width, li.gap, - li.arrowRect, li.accRect); - - // Take into account minimal text offset - int textOffset = li.textRect.x - li.viewRect.x; - if (!li.isTopLevelMenu && (textOffset < li.minTextOffset)) { - li.textRect.x += li.minTextOffset - textOffset; - } - - // Take into account the left side bearings for text and accelerator text. - fixTextRects(li); - - // Set Y coordinate for text and icon. - // Y coordinates for other rects - // will be calculated later in layoutMenuItem. - calcTextAndIconYPositions(li); - - // Calculate valid X and Y coordinates for labelRect - li.labelRect = li.textRect.union(li.iconRect); - } - - private void doLTRComplexLayout(LayoutInfo li) { - li.labelRect.width = li.maxLabelWidth; - - // Set X coordinates - calcXPositionsL2R(li.viewRect.x, li.leadingGap, li.gap, li.checkRect, - li.labelRect); - - // Tune afterCheckIconGap - if (li.checkRect.width > 0) { // there is the afterCheckIconGap - li.labelRect.x += li.afterCheckIconGap - li.gap; - } - - calcXPositionsR2L(li.viewRect.x + li.viewRect.width, li.gap, - li.arrowRect, li.accRect); - - // Take into account minimal text offset - int labelOffset = li.labelRect.x - li.viewRect.x; - if (!li.isTopLevelMenu && (labelOffset < li.minTextOffset)) { - li.labelRect.x += li.minTextOffset - labelOffset; - } - - // Take into account the left side bearing for accelerator text. - // The LSB for text is taken into account in layoutCompoundLabel() below. - fixAccTextRect(li); - - // Layout icon and text with SwingUtilities.layoutCompoundLabel() - // within the labelRect - li.textRect = new Rectangle(); - li.iconRect = new Rectangle(); - SwingUtilities.layoutCompoundLabel( - li.mi, li.fm, li.text, li.icon, li.verticalAlignment, - li.horizontalAlignment, li.verticalTextPosition, - li.horizontalTextPosition, li.labelRect, - li.iconRect, li.textRect, li.gap); - } - - private void doRTLColumnLayout(LayoutInfo li) { - // Set maximal width for all the five basic rects - // (three other ones are already maximal) - li.iconRect.width = li.maxIconWidth; - li.textRect.width = li.maxTextWidth; - - // Set X coordinates - calcXPositionsR2L(li.viewRect.x + li.viewRect.width, li.leadingGap, - li.gap, li.checkRect, li.iconRect, li.textRect); - - // Tune the gap after check icon - if (li.checkRect.width > 0) { // there is the gap after check icon - li.iconRect.x -= li.afterCheckIconGap - li.gap; - li.textRect.x -= li.afterCheckIconGap - li.gap; - } - - calcXPositionsL2R(li.viewRect.x, li.gap, li.arrowRect, - li.accRect); - - // Take into account minimal text offset - int textOffset = (li.viewRect.x + li.viewRect.width) - - (li.textRect.x + li.textRect.width); - if (!li.isTopLevelMenu && (textOffset < li.minTextOffset)) { - li.textRect.x -= li.minTextOffset - textOffset; - } - - // Align icon, text, accelerator text, check icon and arrow icon - // at the right side - rightAlignAllRects(li); - - // Take into account the left side bearings for text and accelerator text. - fixTextRects(li); - - // Set Y coordinates for text and icon. - // Y coordinates for other rects - // will be calculated later in layoutMenuItem. - calcTextAndIconYPositions(li); - - // Calculate valid X and Y coordinate for labelRect - li.labelRect = li.textRect.union(li.iconRect); - } - - private void doRTLComplexLayout(LayoutInfo li) { - li.labelRect.width = li.maxLabelWidth; - - // Set X coordinates - calcXPositionsR2L(li.viewRect.x + li.viewRect.width, li.leadingGap, - li.gap, li.checkRect, li.labelRect); - - // Tune the gap after check icon - if (li.checkRect.width > 0) { // there is the gap after check icon - li.labelRect.x -= li.afterCheckIconGap - li.gap; - } - - calcXPositionsL2R(li.viewRect.x, li.gap, li.arrowRect, - li.accRect); - - // Take into account minimal text offset - int labelOffset = (li.viewRect.x + li.viewRect.width) - - (li.labelRect.x + li.labelRect.width); - if (!li.isTopLevelMenu && (labelOffset < li.minTextOffset)) { - li.labelRect.x -= li.minTextOffset - labelOffset; - } - - // Align icon, text, accelerator text, check icon and arrow icon - // at the right side - rightAlignAllRects(li); - - // Take into account the left side bearing for accelerator text. - // The LSB for text is taken into account in layoutCompoundLabel() below. - fixAccTextRect(li); - - // Layout icon and text with SwingUtilities.layoutCompoundLabel() - // within the labelRect - li.textRect = new Rectangle(); - li.iconRect = new Rectangle(); - SwingUtilities.layoutCompoundLabel( - menuItem, li.fm, li.text, li.icon, li.verticalAlignment, - li.horizontalAlignment, li.verticalTextPosition, - li.horizontalTextPosition, li.labelRect, - li.iconRect, li.textRect, li.gap); - } - - private void calcXPositionsL2R(int startXPos, int leadingGap, - int gap, Rectangle... rects) { - int curXPos = startXPos + leadingGap; - for (Rectangle rect : rects) { - rect.x = curXPos; - if (rect.width > 0) { - curXPos += rect.width + gap; - } - } - } - - private void calcXPositionsL2R(int startXPos, int gap, Rectangle... rects) { - calcXPositionsL2R(startXPos, gap, gap, rects); - } - - private void calcXPositionsR2L(int startXPos, int leadingGap, - int gap, Rectangle... rects) { - int curXPos = startXPos - leadingGap; - for (Rectangle rect : rects) { - rect.x = curXPos - rect.width; - if (rect.width > 0) { - curXPos -= rect.width + gap; - } - } - } - - private void calcXPositionsR2L(int startXPos, int gap, Rectangle... rects) { - calcXPositionsR2L(startXPos, gap, gap, rects); - } - - // Takes into account the left side bearings for text and accelerator text - private void fixTextRects(LayoutInfo li) { - if (li.htmlView == null) { // The text isn't a HTML - int lsb = SwingUtilities2.getLeftSideBearing(li.mi, li.fm, li.text); - if (lsb < 0) { - li.textRect.x -= lsb; - } - } - fixAccTextRect(li); - } - - // Takes into account the left side bearing for accelerator text - private void fixAccTextRect(LayoutInfo li) { - int lsb = SwingUtilities2 - .getLeftSideBearing(li.mi, li.accFm, li.accText); - if (lsb < 0) { - li.accRect.x -= lsb; - } - } - - // Sets Y coordinates of text and icon - // taking into account the vertical alignment - private void calcTextAndIconYPositions(LayoutInfo li) { - if (li.verticalAlignment == SwingUtilities.TOP) { - li.textRect.y = (int)(li.viewRect.y - + (float)li.labelRect.height/2 - - (float)li.textRect.height/2); - li.iconRect.y = (int)(li.viewRect.y - + (float)li.labelRect.height/2 - - (float)li.iconRect.height/2); - } else if (li.verticalAlignment == SwingUtilities.CENTER) { - li.textRect.y = (int)(li.viewRect.y - + (float)li.viewRect.height/2 - - (float)li.textRect.height/2); - li.iconRect.y = (int)(li.viewRect.y - + (float)li.viewRect.height/2 - - (float)li.iconRect.height/2); - } - else if (li.verticalAlignment == SwingUtilities.BOTTOM) { - li.textRect.y = (int)(li.viewRect.y + li.viewRect.height - - (float)li.labelRect.height/2 - - (float)li.textRect.height/2); - li.iconRect.y = (int)(li.viewRect.y + li.viewRect.height - - (float)li.labelRect.height/2 - - (float)li.iconRect.height/2); - } - } - - // Aligns icon, text, accelerator text, check icon and arrow icon - // at the right side - private void rightAlignAllRects(LayoutInfo li) { - li.iconRect.x = li.iconRect.x + li.iconRect.width - li.origIconWidth; - li.iconRect.width = li.origIconWidth; - li.textRect.x = li.textRect.x + li.textRect.width - li.origTextWidth; - li.textRect.width = li.origTextWidth; - li.accRect.x = li.accRect.x + li.accRect.width - - li.origAccWidth; - li.accRect.width = li.origAccWidth; - li.checkRect.x = li.checkRect.x + li.checkRect.width - - li.origCheckWidth; - li.checkRect.width = li.origCheckWidth; - li.arrowRect.x = li.arrowRect.x + li.arrowRect.width - - li.origArrowWidth; - li.arrowRect.width = li.origArrowWidth; - } - - /* - * Returns false if the component is a JMenu and it is a top - * level menu (on the menubar). - */ - private boolean useCheckAndArrow(){ - boolean b = true; - if((menuItem instanceof JMenu) && - (((JMenu)menuItem).isTopLevelMenu())) { - b = false; - } - return b; - } - public MenuElement[] getPath() { MenuSelectionManager m = MenuSelectionManager.defaultManager(); MenuElement oldPath[] = m.getSelectedPath(); @@ -1601,7 +737,7 @@ for(i=0,j=path.length; i 0) { me = new MenuElement[4]; me[0] = (MenuElement) cnt; - me[1] = (MenuElement) menu; - me[2] = (MenuElement) menu.getPopupMenu(); + me[1] = menu; + me[2] = menu.getPopupMenu(); me[3] = subElements[0]; } else { me = new MenuElement[3]; me[0] = (MenuElement)cnt; me[1] = menu; - me[2] = (MenuElement) menu.getPopupMenu(); + me[2] = menu.getPopupMenu(); } defaultManager.setSelectedPath(me); } @@ -606,7 +605,7 @@ MenuSelectionManager manager = e.getMenuSelectionManager(); if (key == Character.toLowerCase(e.getKeyChar())) { JPopupMenu popupMenu = ((JMenu)menuItem).getPopupMenu(); - ArrayList newList = new ArrayList(Arrays.asList(path)); + ArrayList newList = new ArrayList(Arrays.asList(path)); newList.add(popupMenu); MenuElement subs[] = popupMenu.getSubElements(); MenuElement sub = @@ -614,8 +613,8 @@ if(sub != null) { newList.add(sub); } - MenuElement newPath[] = new MenuElement[0];; - newPath = (MenuElement[]) newList.toArray(newPath); + MenuElement newPath[] = new MenuElement[0]; + newPath = newList.toArray(newPath); manager.setSelectedPath(newPath); e.consume(); } else if (((JMenu)menuItem).isTopLevelMenu() diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -109,7 +109,7 @@ static { - newline = (String)java.security.AccessController.doPrivileged( + newline = java.security.AccessController.doPrivileged( new GetPropertyAction("line.separator")); if (newline == null) { newline = "\n"; @@ -262,7 +262,7 @@ * getMinimumOptionPaneSize. */ public Dimension getPreferredSize(JComponent c) { - if ((JOptionPane)c == optionPane) { + if (c == optionPane) { Dimension ourMin = getMinimumOptionPaneSize(); LayoutManager lm = c.getLayout(); @@ -366,8 +366,8 @@ } else if (msg instanceof Object[]) { Object [] msgs = (Object[]) msg; - for (int i = 0; i < msgs.length; i++) { - addMessageComponents(container, cons, msgs[i], maxll, false); + for (Object o : msgs) { + addMessageComponents(container, cons, o, maxll, false); } } else if (msg instanceof Icon) { @@ -381,7 +381,7 @@ if (len <= 0) { return; } - int nl = -1; + int nl; int nll = 0; if ((nl = s.indexOf(newline)) >= 0) { @@ -1320,7 +1320,7 @@ else if (changeName == "componentOrientation") { ComponentOrientation o = (ComponentOrientation)e.getNewValue(); JOptionPane op = (JOptionPane)e.getSource(); - if (o != (ComponentOrientation)e.getOldValue()) { + if (o != e.getOldValue()) { op.applyComponentOrientation(o); } } @@ -1418,7 +1418,7 @@ } JButton createButton() { - JButton button = null; + JButton button; if (minimumWidth > 0) { button = new ConstrainedButton(text, minimumWidth); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -225,14 +225,14 @@ return popup; } - static List getPopups() { + static List getPopups() { MenuSelectionManager msm = MenuSelectionManager.defaultManager(); MenuElement[] p = msm.getSelectedPath(); - List list = new ArrayList(p.length); - for(int i = 0; i < p.length; i++) { - if (p[i] instanceof JPopupMenu) { - list.add((JPopupMenu)p[i]); + List list = new ArrayList(p.length); + for (MenuElement element : p) { + if (element instanceof JPopupMenu) { + list.add((JPopupMenu) element); } } return list; @@ -290,14 +290,14 @@ MenuElement subitem = findEnabledChild( subpopup.getSubElements(), -1, true); - ArrayList lst = new ArrayList(Arrays.asList(e.getPath())); + ArrayList lst = new ArrayList(Arrays.asList(e.getPath())); lst.add(menuToOpen); lst.add(subpopup); if (subitem != null) { lst.add(subitem); } - MenuElement newPath[] = new MenuElement[0];; - newPath = (MenuElement[])lst.toArray(newPath); + MenuElement newPath[] = new MenuElement[0]; + newPath = lst.toArray(newPath); MenuSelectionManager.defaultManager().setSelectedPath(newPath); e.consume(); } @@ -345,7 +345,7 @@ } if (matches == 0) { - ; // no op + // no op } else if (matches == 1) { // Invoke the menu action JMenuItem item = (JMenuItem)items[firstMatch]; @@ -362,7 +362,7 @@ // Select the menu item with the matching mnemonic. If // the same mnemonic has been invoked then select the next // menu item in the cycle. - MenuElement newItem = null; + MenuElement newItem; newItem = items[indexes[(currentIndex + 1) % matches]]; @@ -372,7 +372,6 @@ manager.setSelectedPath(newPath); e.consume(); } - return; } public void menuKeyReleased(MenuKeyEvent e) { @@ -625,7 +624,7 @@ // 4234793: This action should call JPopupMenu.firePopupMenuCanceled but it's // a protected method. The real solution could be to make // firePopupMenuCanceled public and call it directly. - JPopupMenu lastPopup = (JPopupMenu)getLastPopup(); + JPopupMenu lastPopup = getLastPopup(); if (lastPopup != null) { lastPopup.putClientProperty("JPopupMenu.firePopupMenuCanceled", Boolean.TRUE); } @@ -703,7 +702,7 @@ static MenuElement findEnabledChild(MenuElement e[], int fromIndex, boolean forward) { - MenuElement result = null; + MenuElement result; if (forward) { result = nextEnabledChild(e, fromIndex+1, e.length-1); if (result == null) result = nextEnabledChild(e, 0, fromIndex-1); @@ -752,7 +751,7 @@ // A grab needs to be added final Toolkit tk = Toolkit.getDefaultToolkit(); java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction() { public Object run() { tk.addAWTEventListener(MouseGrabber.this, AWTEvent.MOUSE_EVENT_MASK | @@ -785,7 +784,7 @@ final Toolkit tk = Toolkit.getDefaultToolkit(); // The grab should be removed java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction() { public Object run() { tk.removeAWTEventListener(MouseGrabber.this); return null; @@ -911,10 +910,8 @@ // 4234793: This action should call firePopupMenuCanceled but it's // a protected method. The real solution could be to make // firePopupMenuCanceled public and call it directly. - List popups = getPopups(); - Iterator iter = popups.iterator(); - while (iter.hasNext()) { - JPopupMenu popup = (JPopupMenu) iter.next(); + List popups = getPopups(); + for (JPopupMenu popup : popups) { popup.putClientProperty("JPopupMenu.firePopupMenuCanceled", Boolean.TRUE); } MenuSelectionManager.defaultManager().clearSelectedPath(); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicRadioButtonUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicRadioButtonUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicRadioButtonUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -150,15 +150,15 @@ } } else if(model.isSelected()) { if(b.isRolloverEnabled() && model.isRollover()) { - altIcon = (Icon) b.getRolloverSelectedIcon(); + altIcon = b.getRolloverSelectedIcon(); if (altIcon == null) { - altIcon = (Icon) b.getSelectedIcon(); + altIcon = b.getSelectedIcon(); } } else { - altIcon = (Icon) b.getSelectedIcon(); + altIcon = b.getSelectedIcon(); } } else if(b.isRolloverEnabled() && model.isRollover()) { - altIcon = (Icon) b.getRolloverIcon(); + altIcon = b.getRolloverIcon(); } if(altIcon == null) { @@ -214,7 +214,7 @@ String text = b.getText(); - Icon buttonIcon = (Icon) b.getIcon(); + Icon buttonIcon = b.getIcon(); if(buttonIcon == null) { buttonIcon = getDefaultIcon(); } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -106,13 +106,13 @@ * Keys to use for forward focus traversal when the JComponent is * managing focus. */ - private static Set managingFocusForwardTraversalKeys; + private static Set managingFocusForwardTraversalKeys; /** * Keys to use for backward focus traversal when the JComponent is * managing focus. */ - private static Set managingFocusBackwardTraversalKeys; + private static Set managingFocusBackwardTraversalKeys; /** @@ -370,7 +370,7 @@ // focus forward traversal key if (managingFocusForwardTraversalKeys==null) { - managingFocusForwardTraversalKeys = new HashSet(); + managingFocusForwardTraversalKeys = new HashSet(); managingFocusForwardTraversalKeys.add( KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)); } @@ -378,7 +378,7 @@ managingFocusForwardTraversalKeys); // focus backward traversal key if (managingFocusBackwardTraversalKeys==null) { - managingFocusBackwardTraversalKeys = new HashSet(); + managingFocusBackwardTraversalKeys = new HashSet(); managingFocusBackwardTraversalKeys.add( KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK)); } @@ -2170,7 +2170,7 @@ Component focusOn = (direction > 0) ? policy.getComponentAfter(rootAncestor, splitPane) : policy.getComponentBefore(rootAncestor, splitPane); - HashSet focusFrom = new HashSet(); + HashSet focusFrom = new HashSet(); if (splitPane.isAncestorOf(focusOn)) { do { focusFrom.add(focusOn); @@ -2212,7 +2212,7 @@ private Component getNextSide(JSplitPane splitPane, Component focus) { Component left = splitPane.getLeftComponent(); Component right = splitPane.getRightComponent(); - Component next = null; + Component next; if (focus!=null && SwingUtilities.isDescendingFrom(focus, left) && right!=null) { next = getFirstAvailableComponent(right); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicTabbedPaneUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicTabbedPaneUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicTabbedPaneUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -142,9 +142,9 @@ private Component visibleComponent; // PENDING(api): See comment for ContainerHandler - private Vector htmlViews; - - private Hashtable mnemonicToIndexMap; + private Vector htmlViews; + + private Hashtable mnemonicToIndexMap; /** * InputMap used for mnemonics. Only non-null if the JTabbedPane has @@ -546,7 +546,7 @@ * Installs the state needed for mnemonics. */ private void initMnemonics() { - mnemonicToIndexMap = new Hashtable(); + mnemonicToIndexMap = new Hashtable(); mnemonicInputMap = new ComponentInputMapUIResource(tabPane); mnemonicInputMap.setParent(SwingUtilities.getUIInputMap(tabPane, JComponent.WHEN_IN_FOCUSED_WINDOW)); @@ -909,10 +909,10 @@ private static final int CROP_SEGMENT = 12; private static Polygon createCroppedTabShape(int tabPlacement, Rectangle tabRect, int cropline) { - int rlen = 0; - int start = 0; - int end = 0; - int ostart = 0; + int rlen; + int start; + int end; + int ostart; switch(tabPlacement) { case LEFT: @@ -1014,7 +1014,7 @@ tabPane.putClientProperty("html", v); } - SwingUtilities.layoutCompoundLabel((JComponent) tabPane, + SwingUtilities.layoutCompoundLabel(tabPane, metrics, title, icon, SwingUtilities.CENTER, SwingUtilities.CENTER, @@ -1694,7 +1694,7 @@ */ protected View getTextViewForTab(int tabIndex) { if (htmlViews != null) { - return (View)htmlViews.elementAt(tabIndex); + return htmlViews.elementAt(tabIndex); } return null; } @@ -2230,8 +2230,7 @@ if (mnemonic >= 'a' && mnemonic <='z') { mnemonic -= ('a' - 'A'); } - Integer index = (Integer)ui.mnemonicToIndexMap. - get(Integer.valueOf(mnemonic)); + Integer index = ui.mnemonicToIndexMap.get(Integer.valueOf(mnemonic)); if (index != null && pane.isEnabledAt(index.intValue())) { pane.setSelectedIndex(index.intValue()); } @@ -2292,8 +2291,7 @@ for (int i = 0; i < tabPane.getTabCount(); i++) { Component component = tabPane.getComponentAt(i); if (component != null) { - Dimension size = zeroSize; - size = minimum? component.getMinimumSize() : + Dimension size = minimum ? component.getMinimumSize() : component.getPreferredSize(); if (size != null) { @@ -2305,7 +2303,7 @@ // Add content border insets to minimum size width += cWidth; height += cHeight; - int tabExtent = 0; + int tabExtent; // Calculate how much space the tabs will need, based on the // minimum size required to display largest child + content border @@ -3143,7 +3141,7 @@ Insets tabAreaInsets = getTabAreaInsets(tabPlacement); int fontHeight = metrics.getHeight(); int selectedIndex = tabPane.getSelectedIndex(); - int i, j; + int i; boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT); boolean leftToRight = BasicGraphicsUtils.isLeftToRight(tabPane); int x = tabAreaInsets.left; @@ -3433,10 +3431,10 @@ } public String toString() { - return new String("viewport.viewSize="+viewport.getViewSize()+"\n"+ + return "viewport.viewSize=" + viewport.getViewSize() + "\n" + "viewport.viewRectangle="+viewport.getViewRect()+"\n"+ "leadingTabIndex="+leadingTabIndex+"\n"+ - "tabViewPosition="+tabViewPosition); + "tabViewPosition=" + tabViewPosition; } } @@ -3788,8 +3786,8 @@ } } - private Vector createHTMLVector() { - Vector htmlViews = new Vector(); + private Vector createHTMLVector() { + Vector htmlViews = new Vector(); int count = tabPane.getTabCount(); if (count>0) { for (int i=0 ; i storedForwardTraversalKeys = editor. getFocusTraversalKeys(KeyboardFocusManager. FORWARD_TRAVERSAL_KEYS); - Set storedBackwardTraversalKeys = editor. + Set storedBackwardTraversalKeys = editor. getFocusTraversalKeys(KeyboardFocusManager. BACKWARD_TRAVERSAL_KEYS); - Set forwardTraversalKeys = - new HashSet(storedForwardTraversalKeys); - Set backwardTraversalKeys = - new HashSet(storedBackwardTraversalKeys); + Set forwardTraversalKeys = + new HashSet(storedForwardTraversalKeys); + Set backwardTraversalKeys = + new HashSet(storedBackwardTraversalKeys); if (editor.isEditable()) { forwardTraversalKeys. remove(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)); @@ -1888,7 +1888,7 @@ * * @param e The change notification from the currently associated * document. - * @see DocumentListener#changeUpdate + * @see DocumentListener#changedUpdate(DocumentEvent) */ public final void changedUpdate(DocumentEvent e) { Rectangle alloc = (painted) ? getVisibleEditorRect() : null; @@ -1964,9 +1964,9 @@ } try { rootView.setSize(alloc.width, alloc.height); - Enumeration components = constraints.keys(); + Enumeration components = constraints.keys(); while (components.hasMoreElements()) { - Component comp = (Component) components.nextElement(); + Component comp = components.nextElement(); View v = (View) constraints.get(comp); Shape ca = calculateViewPosition(alloc, v); if (ca != null) { @@ -2009,7 +2009,7 @@ public void addLayoutComponent(Component comp, Object constraint) { if (constraint instanceof View) { if (constraints == null) { - constraints = new Hashtable(7); + constraints = new Hashtable(7); } constraints.put(comp, constraint); } @@ -2060,7 +2060,7 @@ * These are View objects for those components that are represented * by a View in the View tree. */ - private Hashtable constraints; + private Hashtable constraints; private boolean i18nView = false; } @@ -2457,8 +2457,7 @@ JTextComponent c = (JTextComponent)comp; int pos = modeBetween - ? ((JTextComponent.DropLocation)c.getDropLocation()).getIndex() - : c.getCaretPosition(); + ? c.getDropLocation().getIndex() : c.getCaretPosition(); // if we are importing to the same component that we exported from // then don't actually do anything if the drop location is inside diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicToggleButtonUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicToggleButtonUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicToggleButtonUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -125,31 +125,31 @@ if(!model.isEnabled()) { if(model.isSelected()) { - icon = (Icon) b.getDisabledSelectedIcon(); + icon = b.getDisabledSelectedIcon(); } else { - icon = (Icon) b.getDisabledIcon(); + icon = b.getDisabledIcon(); } } else if(model.isPressed() && model.isArmed()) { - icon = (Icon) b.getPressedIcon(); + icon = b.getPressedIcon(); if(icon == null) { // Use selected icon - icon = (Icon) b.getSelectedIcon(); + icon = b.getSelectedIcon(); } } else if(model.isSelected()) { if(b.isRolloverEnabled() && model.isRollover()) { - icon = (Icon) b.getRolloverSelectedIcon(); + icon = b.getRolloverSelectedIcon(); if (icon == null) { - icon = (Icon) b.getSelectedIcon(); + icon = b.getSelectedIcon(); } } else { - icon = (Icon) b.getSelectedIcon(); + icon = b.getSelectedIcon(); } } else if(b.isRolloverEnabled() && model.isRollover()) { - icon = (Icon) b.getRolloverIcon(); + icon = b.getRolloverIcon(); } if(icon == null) { - icon = (Icon) b.getIcon(); + icon = b.getIcon(); } icon.paintIcon(b, g, iconRect.x, iconRect.y); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -83,8 +83,8 @@ private static Border nonRolloverToggleBorder; private boolean rolloverBorders = false; - private HashMap borderTable = new HashMap(); - private Hashtable rolloverTable = new Hashtable(); + private HashMap borderTable = new HashMap(); + private Hashtable rolloverTable = new Hashtable(); /** @@ -171,7 +171,7 @@ uninstallKeyboardActions(); // Clear instance vars - if (isFloating() == true) + if (isFloating()) setFloating(false, null); floatingToolBar = null; @@ -273,9 +273,8 @@ // Put focus listener on all components in toolbar Component[] components = toolBar.getComponents(); - for ( int i = 0; i < components.length; ++i ) - { - components[ i ].addFocusListener( toolBarFocusListener ); + for (Component component : components) { + component.addFocusListener(toolBarFocusListener); } } } @@ -307,9 +306,8 @@ // Remove focus listener from all components in toolbar Component[] components = toolBar.getComponents(); - for ( int i = 0; i < components.length; ++i ) - { - components[ i ].removeFocusListener( toolBarFocusListener ); + for (Component component : components) { + component.removeFocusListener(toolBarFocusListener); } toolBarFocusListener = null; @@ -616,10 +614,10 @@ // Put rollover borders on buttons Component[] components = c.getComponents(); - for ( int i = 0; i < components.length; ++i ) { - if ( components[ i ] instanceof JComponent ) { - ( (JComponent)components[ i ] ).updateUI(); - setBorderToRollover( components[ i ] ); + for (Component component : components) { + if (component instanceof JComponent) { + ((JComponent) component).updateUI(); + setBorderToRollover(component); } } } @@ -640,10 +638,10 @@ // Put non-rollover borders on buttons. These borders reduce the margin. Component[] components = c.getComponents(); - for ( int i = 0; i < components.length; ++i ) { - if ( components[ i ] instanceof JComponent ) { - ( (JComponent)components[ i ] ).updateUI(); - setBorderToNonRollover( components[ i ] ); + for (Component component : components) { + if (component instanceof JComponent) { + ((JComponent) component).updateUI(); + setBorderToNonRollover(component); } } } @@ -664,8 +662,8 @@ // Put back the normal borders on buttons Component[] components = c.getComponents(); - for ( int i = 0; i < components.length; ++i ) { - setBorderToNormal( components[ i ] ); + for (Component component : components) { + setBorderToNormal(component); } } @@ -681,7 +679,7 @@ if (c instanceof AbstractButton) { AbstractButton b = (AbstractButton)c; - Border border = (Border)borderTable.get(b); + Border border = borderTable.get(b); if (border == null || border instanceof UIResource) { borderTable.put(b, b.getBorder()); } @@ -721,7 +719,7 @@ if (c instanceof AbstractButton) { AbstractButton b = (AbstractButton)c; - Border border = (Border)borderTable.get(b); + Border border = borderTable.get(b); if (border == null || border instanceof UIResource) { borderTable.put(b, b.getBorder()); } @@ -765,10 +763,10 @@ if (c instanceof AbstractButton) { AbstractButton b = (AbstractButton)c; - Border border = (Border)borderTable.remove(b); + Border border = borderTable.remove(b); b.setBorder(border); - Boolean value = (Boolean)rolloverTable.remove(b); + Boolean value = rolloverTable.remove(b); if (value != null) { b.setRolloverEnabled(value.booleanValue()); } @@ -785,7 +783,7 @@ } public void setFloating(boolean b, Point p) { - if (toolBar.isFloatable() == true) { + if (toolBar.isFloatable()) { boolean visible = false; Window ancestor = SwingUtilities.getWindowAncestor(toolBar); if (ancestor != null) { @@ -953,7 +951,7 @@ protected void dragTo(Point position, Point origin) { - if (toolBar.isFloatable() == true) + if (toolBar.isFloatable()) { try { @@ -1003,7 +1001,7 @@ protected void floatAt(Point position, Point origin) { - if(toolBar.isFloatable() == true) + if(toolBar.isFloatable()) { try { @@ -1174,7 +1172,7 @@ if (!tb.isEnabled()) { return; } - if (isDragging == true) { + if (isDragging) { Point position = evt.getPoint(); if (origin == null) origin = evt.getComponent().getLocationOnScreen(); @@ -1242,7 +1240,7 @@ protected class FrameListener extends WindowAdapter { public void windowClosing(WindowEvent w) { - if (toolBar.isFloatable() == true) { + if (toolBar.isFloatable()) { if (dragWindow != null) dragWindow.setVisible(false); floating = false; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/BasicTreeUI.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicTreeUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicTreeUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -1263,7 +1263,7 @@ } private Rectangle getDropLineRect(JTree.DropLocation loc) { - Rectangle rect = null; + Rectangle rect; TreePath path = loc.getPath(); int index = loc.getChildIndex(); boolean ltr = leftToRight; @@ -2138,7 +2138,7 @@ compositeRequestFocus(editingComponent); boolean selectAll = true; - if(event != null && event instanceof MouseEvent) { + if(event != null) { /* Find the component that will get forwarded all the mouse events until mouseReleased. */ Point componentPoint = SwingUtilities.convertPoint @@ -3125,7 +3125,7 @@ private static final TransferHandler defaultTransferHandler = new TreeTransferHandler(); - static class TreeTransferHandler extends TransferHandler implements UIResource, Comparator { + static class TreeTransferHandler extends TransferHandler implements UIResource, Comparator { private JTree tree; @@ -3156,9 +3156,7 @@ TreePath lastPath = null; TreePath[] displayPaths = getDisplayOrderPaths(paths); - for (int i = 0; i < displayPaths.length; i++) { - TreePath path = displayPaths[i]; - + for (TreePath path : displayPaths) { Object node = path.getLastPathComponent(); boolean leaf = model.isLeaf(node); String label = getDisplayString(path, true, leaf); @@ -3179,9 +3177,9 @@ return null; } - public int compare(Object o1, Object o2) { - int row1 = tree.getRowForPath((TreePath)o1); - int row2 = tree.getRowForPath((TreePath)o2); + public int compare(TreePath o1, TreePath o2) { + int row1 = tree.getRowForPath(o1); + int row2 = tree.getRowForPath(o2); return row1 - row2; } @@ -3200,15 +3198,15 @@ */ TreePath[] getDisplayOrderPaths(TreePath[] paths) { // sort the paths to display order rather than selection order - ArrayList selOrder = new ArrayList(); - for (int i = 0; i < paths.length; i++) { - selOrder.add(paths[i]); + ArrayList selOrder = new ArrayList(); + for (TreePath path : paths) { + selOrder.add(path); } Collections.sort(selOrder, this); int n = selOrder.size(); TreePath[] displayPaths = new TreePath[n]; for (int i = 0; i < n; i++) { - displayPaths[i] = (TreePath) selOrder.get(i); + displayPaths[i] = selOrder.get(i); } return displayPaths; } @@ -3321,10 +3319,7 @@ InputMap inputMap = tree.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); KeyStroke key = KeyStroke.getKeyStrokeForEvent(event); - if (inputMap != null && inputMap.get(key) != null) { - return true; - } - return false; + return inputMap != null && inputMap.get(key) != null; } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/DefaultMenuLayout.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/DefaultMenuLayout.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/DefaultMenuLayout.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 1998-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,6 @@ import java.awt.Container; import java.awt.Dimension; -import static sun.swing.SwingUtilities2.BASICMENUITEMUI_MAX_TEXT_OFFSET; /** * The default layout manager for Popup menus and menubars. This @@ -49,18 +48,7 @@ public Dimension preferredLayoutSize(Container target) { if (target instanceof JPopupMenu) { JPopupMenu popupMenu = (JPopupMenu) target; - - // Before the calculation of menu preferred size - // clear the previously calculated maximal widths and offsets - // in menu's Client Properties - popupMenu.putClientProperty(BasicMenuItemUI.MAX_ACC_WIDTH, null); - popupMenu.putClientProperty(BasicMenuItemUI.MAX_ARROW_WIDTH, null); - popupMenu.putClientProperty(BasicMenuItemUI.MAX_CHECK_WIDTH, null); - popupMenu.putClientProperty(BasicMenuItemUI.MAX_ICON_WIDTH, null); - popupMenu.putClientProperty(BasicMenuItemUI.MAX_LABEL_WIDTH, null); - popupMenu.putClientProperty(BasicMenuItemUI.MAX_TEXT_WIDTH, null); - popupMenu.putClientProperty(BASICMENUITEMUI_MAX_TEXT_OFFSET, null); - + sun.swing.MenuItemLayoutHelper.clearUsedClientProperties(popupMenu); if (popupMenu.getComponentCount() == 0) { return new Dimension(0, 0); } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/DesktopIconMover.java Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,168 @@ +/* + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.plaf.basic; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.beans.*; + +/** + * DesktopIconMover is intended to move desktop icon + * when parent window is resized. + */ +class DesktopIconMover implements ComponentListener, PropertyChangeListener { + private Component parent; + private JInternalFrame frame; // if not null, DesktopIconMover(frame) + // constructor was used + private JInternalFrame.JDesktopIcon icon; + private Rectangle parentBounds; + private boolean componentListenerAdded = false; + + public DesktopIconMover(JInternalFrame frame) { + if (frame == null) { + throw new NullPointerException("Frame cannot be null"); + } + this.frame = frame; + this.icon = frame.getDesktopIcon(); + if (icon == null) { + throw new NullPointerException( + "frame.getDesktopIcon() cannot be null"); + } + this.parent = frame.getParent(); + if (this.parent != null) { + parentBounds = this.parent.getBounds(); + } + } + + public DesktopIconMover(JInternalFrame.JDesktopIcon icon) { + if (icon == null) { + throw new NullPointerException("Icon cannot be null"); + } + this.icon = icon; + this.parent = icon.getParent(); + if (this.parent != null) { + parentBounds = this.parent.getBounds(); + } + } + + public void installListeners() { + if (frame != null) { + frame.addPropertyChangeListener(this); + } else { + icon.addPropertyChangeListener(this); + } + addComponentListener(); + } + + public void uninstallListeners() { + if (frame != null) { + frame.removePropertyChangeListener(this); + } else { + icon.removePropertyChangeListener(this); + } + removeComponentListener(); + } + + public void propertyChange(PropertyChangeEvent evt) { + String propName = evt.getPropertyName(); + if ("ancestor".equals(propName)) { + Component newAncestor = (Component) evt.getNewValue(); + + // Remove component listener if parent is changing + Component probablyNewParent = getCurrentParent(); + if ((probablyNewParent != null) && + (!probablyNewParent.equals(parent))) { + removeComponentListener(); + parent = probablyNewParent; + } + + if (newAncestor == null) { + removeComponentListener(); + } else { + addComponentListener(); + } + + // Update parentBounds + if (parent != null) { + parentBounds = parent.getBounds(); + } else { + parentBounds = null; + } + } else if (JInternalFrame.IS_CLOSED_PROPERTY.equals(propName)) { + removeComponentListener(); + } + } + + private void addComponentListener() { + if (!componentListenerAdded && (parent != null)) { + parent.addComponentListener(this); + componentListenerAdded = true; + } + } + + private void removeComponentListener() { + if ((parent != null) && componentListenerAdded) { + parent.removeComponentListener(this); + componentListenerAdded = false; + } + } + + private Component getCurrentParent() { + if (frame != null) { + return frame.getParent(); + } else { + return icon.getParent(); + } + } + + public void componentResized(ComponentEvent e) { + if ((parent == null) || (parentBounds == null)) { + return; + } + + Rectangle parentNewBounds = parent.getBounds(); + if ((parentNewBounds == null) || parentNewBounds.equals(parentBounds)) { + return; + } + + // Move desktop icon only in up-down direction + int newIconY = icon.getLocation().y + + (parentNewBounds.height - parentBounds.height); + icon.setLocation(icon.getLocation().x, newIconY); + + parentBounds = parentNewBounds; + } + + public void componentMoved(ComponentEvent e) { + } + + public void componentShown(ComponentEvent e) { + } + + public void componentHidden(ComponentEvent e) { + } +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/DragRecognitionSupport.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/DragRecognitionSupport.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/DragRecognitionSupport.java Wed Jul 05 16:42:37 2017 +0200 @@ -73,8 +73,7 @@ * Returns whether or not the event is potentially part of a drag sequence. */ public static boolean mousePressed(MouseEvent me) { - return ((DragRecognitionSupport)getDragRecognitionSupport()). - mousePressedImpl(me); + return getDragRecognitionSupport().mousePressedImpl(me); } /** @@ -82,16 +81,14 @@ * that started the recognition. Otherwise, return null. */ public static MouseEvent mouseReleased(MouseEvent me) { - return ((DragRecognitionSupport)getDragRecognitionSupport()). - mouseReleasedImpl(me); + return getDragRecognitionSupport().mouseReleasedImpl(me); } /** * Returns whether or not a drag gesture recognition is ongoing. */ public static boolean mouseDragged(MouseEvent me, BeforeDrag bd) { - return ((DragRecognitionSupport)getDragRecognitionSupport()). - mouseDraggedImpl(me, bd); + return getDragRecognitionSupport().mouseDraggedImpl(me, bd); } private void clearState() { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/basic/LazyActionMap.java --- a/jdk/src/share/classes/javax/swing/plaf/basic/LazyActionMap.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/basic/LazyActionMap.java Wed Jul 05 16:42:37 2017 +0200 @@ -142,7 +142,7 @@ Object loader = _loader; _loader = null; - Class klass = (Class)loader; + Class klass = (Class)loader; try { Method method = klass.getDeclaredMethod("loadActionMap", new Class[] { LazyActionMap.class }); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java --- a/jdk/src/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/metal/DefaultMetalTheme.java Wed Jul 05 16:42:37 2017 +0200 @@ -387,9 +387,9 @@ * that it is wrapped inside a doPrivileged call. */ protected Font getPrivilegedFont(final int key) { - return (Font)java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + return java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public Font run() { return Font.getFont(getDefaultPropertyName(key)); } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/metal/MetalBumps.java --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalBumps.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalBumps.java Wed Jul 05 16:42:37 2017 +0200 @@ -49,7 +49,7 @@ protected Color shadowColor; protected Color backColor; - protected static Vector buffers = new Vector(); + protected static Vector buffers = new Vector(); protected BumpBuffer buffer; public MetalBumps( Dimension bumpArea ) { @@ -81,10 +81,7 @@ } BumpBuffer result = null; - Enumeration elements = buffers.elements(); - - while ( elements.hasMoreElements() ) { - BumpBuffer aBuffer = (BumpBuffer)elements.nextElement(); + for (BumpBuffer aBuffer : buffers) { if ( aBuffer.hasSameConfiguration(gc, aTopColor, aShadowColor, aBackColor)) { result = aBuffer; @@ -120,8 +117,7 @@ public void paintIcon( Component c, Graphics g, int x, int y ) { GraphicsConfiguration gc = (g instanceof Graphics2D) ? - (GraphicsConfiguration)((Graphics2D)g). - getDeviceConfiguration() : null; + ((Graphics2D) g).getDeviceConfiguration() : null; buffer = getBuffer(gc, topColor, shadowColor, backColor); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -782,7 +782,7 @@ } else if (s.equals("componentOrientation")) { ComponentOrientation o = (ComponentOrientation)e.getNewValue(); JFileChooser cc = (JFileChooser)e.getSource(); - if (o != (ComponentOrientation)e.getOldValue()) { + if (o != e.getOldValue()) { cc.applyComponentOrientation(o); } } else if (s == "FileChooser.useShellFolder") { @@ -927,7 +927,7 @@ * Data model for a type-face selection combo-box. */ protected class DirectoryComboBoxModel extends AbstractListModel implements ComboBoxModel { - Vector directories = new Vector(); + Vector directories = new Vector(); int[] depths = null; File selectedDirectory = null; JFileChooser chooser = getFileChooser(); @@ -966,7 +966,7 @@ // Get the canonical (full) path. This has the side // benefit of removing extraneous chars from the path, // for example /foo/bar/ becomes /foo/bar - File canonical = null; + File canonical; try { canonical = ShellFolder.getNormalizedFile(directory); } catch (IOException e) { @@ -979,7 +979,7 @@ File sf = useShellFolder ? ShellFolder.getShellFolder(canonical) : canonical; File f = sf; - Vector path = new Vector(10); + Vector path = new Vector(10); do { path.addElement(f); } while ((f = f.getParentFile()) != null); @@ -987,7 +987,7 @@ int pathCount = path.size(); // Insert chain at appropriate place in vector for (int i = 0; i < pathCount; i++) { - f = (File)path.get(i); + f = path.get(i); if (directories.contains(f)) { int topIndex = directories.indexOf(f); for (int j = i-1; j >= 0; j--) { @@ -1006,12 +1006,12 @@ private void calculateDepths() { depths = new int[directories.size()]; for (int i = 0; i < depths.length; i++) { - File dir = (File)directories.get(i); + File dir = directories.get(i); File parent = dir.getParentFile(); depths[i] = 0; if (parent != null) { for (int j = i-1; j >= 0; j--) { - if (parent.equals((File)directories.get(j))) { + if (parent.equals(directories.get(j))) { depths[i] = depths[j] + 1; break; } @@ -1110,8 +1110,8 @@ FileFilter currentFilter = getFileChooser().getFileFilter(); boolean found = false; if(currentFilter != null) { - for(int i=0; i < filters.length; i++) { - if(filters[i] == currentFilter) { + for (FileFilter filter : filters) { + if (filter == currentFilter) { found = true; } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/metal/MetalIconFactory.java --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalIconFactory.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalIconFactory.java Wed Jul 05 16:42:37 2017 +0200 @@ -598,7 +598,7 @@ } // Some calculations that are needed more than once later on. - int oneHalf = (int)(iconSize / 2); // 16 -> 8 + int oneHalf = iconSize / 2; // 16 -> 8 g.translate(x, y); @@ -1502,7 +1502,7 @@ // PENDING: Replace this class with CachedPainter. - Vector images = new Vector(1, 1); + Vector images = new Vector(1, 1); ImageGcPair currentImageGcPair; class ImageGcPair { @@ -1514,12 +1514,8 @@ } boolean hasSameConfiguration(GraphicsConfiguration newGC) { - if (((newGC != null) && (newGC.equals(gc))) || - ((newGC == null) && (gc == null))) - { - return true; - } - return false; + return ((newGC != null) && (newGC.equals(gc))) || + ((newGC == null) && (gc == null)); } } @@ -1528,9 +1524,7 @@ if ((currentImageGcPair == null) || !(currentImageGcPair.hasSameConfiguration(newGC))) { - Enumeration elements = images.elements(); - while (elements.hasMoreElements()) { - ImageGcPair imgGcPair = (ImageGcPair)elements.nextElement(); + for (ImageGcPair imgGcPair : images) { if (imgGcPair.hasSameConfiguration(newGC)) { currentImageGcPair = imgGcPair; return imgGcPair.image; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameTitlePane.java --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameTitlePane.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameTitlePane.java Wed Jul 05 16:42:37 2017 +0200 @@ -191,7 +191,7 @@ extends BasicInternalFrameTitlePane.PropertyChangeHandler { public void propertyChange(PropertyChangeEvent evt) { - String prop = (String)evt.getPropertyName(); + String prop = evt.getPropertyName(); if( prop.equals(JInternalFrame.IS_SELECTED_PROPERTY) ) { Boolean b = (Boolean)evt.getNewValue(); iconButton.putClientProperty("paintActive", b); @@ -242,7 +242,7 @@ } // Compute height. - int height = 0; + int height; if (isPalette) { height = paletteTitleHeight; } else { @@ -410,7 +410,7 @@ g.drawLine ( width - 1, 0 , width -1, 0); - int titleLength = 0; + int titleLength; int xOffset = leftToRight ? 5 : width - 5; String frameTitle = frame.getTitle(); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java Wed Jul 05 16:42:37 2017 +0200 @@ -2208,9 +2208,9 @@ if (methodName == null) { return c.newInstance(); } - Method method = (Method)AccessController.doPrivileged( - new PrivilegedAction() { - public Object run() { + Method method = AccessController.doPrivileged( + new PrivilegedAction() { + public Method run() { Method[] methods = c.getDeclaredMethods(); for (int counter = methods.length - 1; counter >= 0; counter--) { @@ -2273,7 +2273,7 @@ } } - static ReferenceQueue queue = new ReferenceQueue(); + static ReferenceQueue queue = new ReferenceQueue(); static void flushUnreferenced() { AATextListener aatl; @@ -2283,7 +2283,7 @@ } static class AATextListener - extends WeakReference implements PropertyChangeListener { + extends WeakReference implements PropertyChangeListener { private String key = SunToolkit.DESKTOPFONTHINTS; @@ -2294,7 +2294,7 @@ } public void propertyChange(PropertyChangeEvent pce) { - LookAndFeel laf = (LookAndFeel)get(); + LookAndFeel laf = get(); if (laf == null || laf != UIManager.getLookAndFeel()) { dispose(); return; @@ -2318,8 +2318,8 @@ private static void updateWindowUI(Window window) { SwingUtilities.updateComponentTreeUI(window); Window ownedWins[] = window.getOwnedWindows(); - for (int i=0; i < ownedWins.length; i++) { - updateWindowUI(ownedWins[i]); + for (Window w : ownedWins) { + updateWindowUI(w); } } @@ -2328,8 +2328,8 @@ */ private static void updateAllUIs() { Frame appFrames[] = Frame.getFrames(); - for (int j=0; j < appFrames.length; j++) { - updateWindowUI(appFrames[j]); + for (Frame frame : appFrames) { + updateWindowUI(frame); } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/metal/MetalRadioButtonUI.java --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalRadioButtonUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalRadioButtonUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -164,15 +164,15 @@ } } else if(model.isSelected()) { if(b.isRolloverEnabled() && model.isRollover()) { - altIcon = (Icon) b.getRolloverSelectedIcon(); + altIcon = b.getRolloverSelectedIcon(); if (altIcon == null) { - altIcon = (Icon) b.getSelectedIcon(); + altIcon = b.getSelectedIcon(); } } else { - altIcon = (Icon) b.getSelectedIcon(); + altIcon = b.getSelectedIcon(); } } else if(b.isRolloverEnabled() && model.isRollover()) { - altIcon = (Icon) b.getRolloverIcon(); + altIcon = b.getRolloverIcon(); } if(altIcon == null) { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -27,23 +27,13 @@ import javax.swing.plaf.basic.BasicSliderUI; -import java.awt.Component; -import java.awt.Container; import java.awt.Graphics; import java.awt.Dimension; import java.awt.Rectangle; -import java.awt.Point; -import java.awt.Insets; import java.awt.Color; -import java.io.Serializable; -import java.awt.IllegalComponentStateException; -import java.awt.Polygon; import java.beans.*; -import javax.swing.border.AbstractBorder; - import javax.swing.*; -import javax.swing.event.*; import javax.swing.plaf.*; /** @@ -131,10 +121,7 @@ scrollListener.setScrollByBlock( false ); - Object sliderFillProp = c.getClientProperty( SLIDER_FILL ); - if ( sliderFillProp != null ) { - filledSlider = ((Boolean)sliderFillProp).booleanValue(); - } + prepareFilledSliderField(); } protected PropertyChangeListener createPropertyChangeListener( JSlider slider ) { @@ -145,18 +132,23 @@ public void propertyChange( PropertyChangeEvent e ) { // listen for slider fill super.propertyChange( e ); - String name = e.getPropertyName(); - if ( name.equals( SLIDER_FILL ) ) { - if ( e.getNewValue() != null ) { - filledSlider = ((Boolean)e.getNewValue()).booleanValue(); - } - else { - filledSlider = false; - } + if (e.getPropertyName().equals(SLIDER_FILL)) { + prepareFilledSliderField(); } } } + private void prepareFilledSliderField() { + // Use true for Ocean theme + filledSlider = MetalLookAndFeel.usingOcean(); + + Object sliderFillProp = slider.getClientProperty(SLIDER_FILL); + + if (sliderFillProp != null) { + filledSlider = ((Boolean) sliderFillProp).booleanValue(); + } + } + public void paintThumb(Graphics g) { Rectangle knobBounds = thumbRect; @@ -173,21 +165,10 @@ } /** - * If chooseFirstis true, c1 is returned, - * otherwise c2. - */ - private Color chooseColor(boolean chooseFirst, Color c1, Color c2) { - if (chooseFirst) { - return c2; - } - return c1; - } - - /** * Returns a rectangle enclosing the track that will be painted. */ private Rectangle getPaintTrackRect() { - int trackLeft = 0, trackRight = 0, trackTop = 0, trackBottom = 0; + int trackLeft = 0, trackRight, trackTop = 0, trackBottom; if (slider.getOrientation() == JSlider.HORIZONTAL) { trackBottom = (trackRect.height - 1) - getThumbOverhang(); trackTop = trackBottom - (getTrackWidth() - 1); @@ -223,8 +204,8 @@ int trackLeft = 0; int trackTop = 0; - int trackRight = 0; - int trackBottom = 0; + int trackRight; + int trackBottom; // Draw the track if ( slider.getOrientation() == JSlider.HORIZONTAL ) { @@ -266,11 +247,11 @@ // Draw the fill if ( filledSlider ) { - int middleOfThumb = 0; - int fillTop = 0; - int fillLeft = 0; - int fillBottom = 0; - int fillRight = 0; + int middleOfThumb; + int fillTop; + int fillLeft; + int fillBottom; + int fillRight; if ( slider.getOrientation() == JSlider.HORIZONTAL ) { middleOfThumb = thumbRect.x + (thumbRect.width / 2); @@ -314,8 +295,7 @@ } else { g.setColor( MetalLookAndFeel.getControlShadow() ); - g.fillRect( fillLeft, fillTop, - fillRight - fillLeft, trackBottom - trackTop ); + g.fillRect(fillLeft, fillTop, fillRight - fillLeft, fillBottom - fillTop); } } @@ -336,105 +316,137 @@ int w = paintRect.width; int h = paintRect.height; - if (!slider.isEnabled()) { - g.setColor(MetalLookAndFeel.getControlShadow()); - g.drawRect(0, 0, w - 1, h - 1); - } - else if (slider.getOrientation() == JSlider.HORIZONTAL) { - int middleOfThumb = thumbRect.x + (thumbRect.width / 2) - - paintRect.x; - int fillMinX; - int fillMaxX; + if (slider.getOrientation() == JSlider.HORIZONTAL) { + int middleOfThumb = thumbRect.x + thumbRect.width / 2 - paintRect.x; + + if (slider.isEnabled()) { + int fillMinX; + int fillMaxX; + + if (middleOfThumb > 0) { + g.setColor(drawInverted ? MetalLookAndFeel.getControlDarkShadow() : + MetalLookAndFeel.getPrimaryControlDarkShadow()); + + g.drawRect(0, 0, middleOfThumb - 1, h - 1); + } + + if (middleOfThumb < w) { + g.setColor(drawInverted ? MetalLookAndFeel.getPrimaryControlDarkShadow() : + MetalLookAndFeel.getControlDarkShadow()); + + g.drawRect(middleOfThumb, 0, w - middleOfThumb - 1, h - 1); + } - if (middleOfThumb > 0) { - g.setColor(chooseColor(drawInverted, - MetalLookAndFeel.getPrimaryControlDarkShadow(), - MetalLookAndFeel.getControlDarkShadow())); - g.drawRect(0, 0, middleOfThumb - 1, h - 1); - } - if (middleOfThumb < w) { - g.setColor(chooseColor(drawInverted, - MetalLookAndFeel.getControlDarkShadow(), - MetalLookAndFeel.getPrimaryControlDarkShadow())); - g.drawRect(middleOfThumb, 0, w - middleOfThumb - 1, h - 1); - } - g.setColor(MetalLookAndFeel.getPrimaryControlShadow()); - if (drawInverted) { - fillMinX = middleOfThumb; - fillMaxX = w - 2; - g.drawLine(1, 1, middleOfThumb, 1); - } - else { - fillMinX = 1; - fillMaxX = middleOfThumb; - g.drawLine(middleOfThumb, 1, w - 1, 1); - } - if (h == 6) { - g.setColor(MetalLookAndFeel.getWhite()); - g.drawLine(fillMinX, 1, fillMaxX, 1); - g.setColor(sliderAltTrackColor); - g.drawLine(fillMinX, 2, fillMaxX, 2); + if (filledSlider) { + g.setColor(MetalLookAndFeel.getPrimaryControlShadow()); + if (drawInverted) { + fillMinX = middleOfThumb; + fillMaxX = w - 2; + g.drawLine(1, 1, middleOfThumb, 1); + } else { + fillMinX = 1; + fillMaxX = middleOfThumb; + g.drawLine(middleOfThumb, 1, w - 1, 1); + } + if (h == 6) { + g.setColor(MetalLookAndFeel.getWhite()); + g.drawLine(fillMinX, 1, fillMaxX, 1); + g.setColor(sliderAltTrackColor); + g.drawLine(fillMinX, 2, fillMaxX, 2); + g.setColor(MetalLookAndFeel.getControlShadow()); + g.drawLine(fillMinX, 3, fillMaxX, 3); + g.setColor(MetalLookAndFeel.getPrimaryControlShadow()); + g.drawLine(fillMinX, 4, fillMaxX, 4); + } + } + } else { g.setColor(MetalLookAndFeel.getControlShadow()); - g.drawLine(fillMinX, 3, fillMaxX, 3); - g.setColor(MetalLookAndFeel.getPrimaryControlShadow()); - g.drawLine(fillMinX, 4, fillMaxX, 4); - } - } - else { - int middleOfThumb = thumbRect.y + (thumbRect.height / 2) - - paintRect.y; - int fillMinY; - int fillMaxY; - if (middleOfThumb > 0) { - g.setColor(chooseColor(drawInverted, - MetalLookAndFeel.getControlDarkShadow(), - MetalLookAndFeel.getPrimaryControlDarkShadow())); - g.drawRect(0, 0, w - 1, middleOfThumb - 1); - } - if (middleOfThumb < h) { - g.setColor(chooseColor(drawInverted, - MetalLookAndFeel.getPrimaryControlDarkShadow(), - MetalLookAndFeel.getControlDarkShadow())); - g.drawRect(0, middleOfThumb, w - 1, h - middleOfThumb - 1); - } - g.setColor(MetalLookAndFeel.getPrimaryControlShadow()); - if (drawInverted()) { - fillMinY = 1; - fillMaxY = middleOfThumb; - if (leftToRight) { - g.drawLine(1, middleOfThumb, 1, h - 1); + if (middleOfThumb > 0) { + if (!drawInverted && filledSlider) { + g.fillRect(0, 0, middleOfThumb - 1, h - 1); + } else { + g.drawRect(0, 0, middleOfThumb - 1, h - 1); + } } - else { - g.drawLine(w - 2, middleOfThumb, w - 2, h - 1); + + if (middleOfThumb < w) { + if (drawInverted && filledSlider) { + g.fillRect(middleOfThumb, 0, w - middleOfThumb - 1, h - 1); + } else { + g.drawRect(middleOfThumb, 0, w - middleOfThumb - 1, h - 1); + } } } - else { - fillMinY = middleOfThumb; - fillMaxY = h - 2; - if (leftToRight) { - g.drawLine(1, 1, 1, middleOfThumb); + } else { + int middleOfThumb = thumbRect.y + (thumbRect.height / 2) - paintRect.y; + + if (slider.isEnabled()) { + int fillMinY; + int fillMaxY; + + if (middleOfThumb > 0) { + g.setColor(drawInverted ? MetalLookAndFeel.getPrimaryControlDarkShadow() : + MetalLookAndFeel.getControlDarkShadow()); + + g.drawRect(0, 0, w - 1, middleOfThumb - 1); } - else { - g.drawLine(w - 2, 1, w - 2, middleOfThumb); + + if (middleOfThumb < h) { + g.setColor(drawInverted ? MetalLookAndFeel.getControlDarkShadow() : + MetalLookAndFeel.getPrimaryControlDarkShadow()); + + g.drawRect(0, middleOfThumb, w - 1, h - middleOfThumb - 1); } - } - if (w == 6) { - g.setColor(chooseColor(!leftToRight, - MetalLookAndFeel.getWhite(), - MetalLookAndFeel.getPrimaryControlShadow())); - g.drawLine(1, fillMinY, 1, fillMaxY); - g.setColor(chooseColor(!leftToRight, sliderAltTrackColor, - MetalLookAndFeel.getControlShadow())); - g.drawLine(2, fillMinY, 2, fillMaxY); - g.setColor(chooseColor(!leftToRight, - MetalLookAndFeel.getControlShadow(), - sliderAltTrackColor)); - g.drawLine(3, fillMinY, 3, fillMaxY); - g.setColor(chooseColor(!leftToRight, - MetalLookAndFeel.getPrimaryControlShadow(), - MetalLookAndFeel.getWhite())); - g.drawLine(4, fillMinY, 4, fillMaxY); + + if (filledSlider) { + g.setColor(MetalLookAndFeel.getPrimaryControlShadow()); + if (drawInverted()) { + fillMinY = 1; + fillMaxY = middleOfThumb; + if (leftToRight) { + g.drawLine(1, middleOfThumb, 1, h - 1); + } else { + g.drawLine(w - 2, middleOfThumb, w - 2, h - 1); + } + } else { + fillMinY = middleOfThumb; + fillMaxY = h - 2; + if (leftToRight) { + g.drawLine(1, 1, 1, middleOfThumb); + } else { + g.drawLine(w - 2, 1, w - 2, middleOfThumb); + } + } + if (w == 6) { + g.setColor(leftToRight ? MetalLookAndFeel.getWhite() : MetalLookAndFeel.getPrimaryControlShadow()); + g.drawLine(1, fillMinY, 1, fillMaxY); + g.setColor(leftToRight ? sliderAltTrackColor : MetalLookAndFeel.getControlShadow()); + g.drawLine(2, fillMinY, 2, fillMaxY); + g.setColor(leftToRight ? MetalLookAndFeel.getControlShadow() : sliderAltTrackColor); + g.drawLine(3, fillMinY, 3, fillMaxY); + g.setColor(leftToRight ? MetalLookAndFeel.getPrimaryControlShadow() : MetalLookAndFeel.getWhite()); + g.drawLine(4, fillMinY, 4, fillMaxY); + } + } + } else { + g.setColor(MetalLookAndFeel.getControlShadow()); + + if (middleOfThumb > 0) { + if (drawInverted && filledSlider) { + g.fillRect(0, 0, w - 1, middleOfThumb - 1); + } else { + g.drawRect(0, 0, w - 1, middleOfThumb - 1); + } + } + + if (middleOfThumb < h) { + if (!drawInverted && filledSlider) { + g.fillRect(0, middleOfThumb, w - 1, h - middleOfThumb - 1); + } else { + g.drawRect(0, middleOfThumb, w - 1, h - middleOfThumb - 1); + } + } } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/metal/MetalToolBarUI.java --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolBarUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolBarUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -61,7 +61,7 @@ * instances of JToolBars and JMenuBars and is used to find * JToolBars/JMenuBars that border each other. */ - private static java.util.List components = new ArrayList(); + private static List> components = new ArrayList>(); /** * This protected field is implemenation specific. Do not access directly @@ -95,7 +95,7 @@ // typed to throw an NPE. throw new NullPointerException("JComponent must be non-null"); } - components.add(new WeakReference(c)); + components.add(new WeakReference(c)); } /** @@ -105,8 +105,7 @@ for (int counter = components.size() - 1; counter >= 0; counter--) { // Search for the component, removing any flushed references // along the way. - WeakReference ref = (WeakReference)components.get(counter); - Object target = ((WeakReference)components.get(counter)).get(); + JComponent target = components.get(counter).get(); if (target == c || target == null) { components.remove(counter); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/DefaultMenuLayout.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/DefaultMenuLayout.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/DefaultMenuLayout.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,19 +47,22 @@ super(target, axis); } - public void invalidateLayout(Container target) { + public Dimension preferredLayoutSize(Container target) { if (target instanceof JPopupMenu) { - SynthPopupMenuUI popupUI = (SynthPopupMenuUI)((JPopupMenu)target). - getUI(); - popupUI.resetAlignmentHints(); + JPopupMenu popupMenu = (JPopupMenu) target; + + popupMenu.putClientProperty( + SynthMenuItemLayoutHelper.MAX_ACC_OR_ARROW_WIDTH, null); + sun.swing.MenuItemLayoutHelper.clearUsedClientProperties(popupMenu); + + if (popupMenu.getComponentCount() == 0) { + return new Dimension(0, 0); + } } + + // Make BoxLayout recalculate cached preferred sizes super.invalidateLayout(target); - } - public Dimension preferredLayoutSize(Container target) { - if (target instanceof JPopupMenu && target.getComponentCount() == 0) { - return new Dimension(0, 0); - } return super.preferredLayoutSize(target); } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/DefaultSynthStyleFactory.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/DefaultSynthStyleFactory.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/DefaultSynthStyleFactory.java Wed Jul 05 16:42:37 2017 +0200 @@ -63,7 +63,7 @@ /** * Maps from a List (BakedArrayList to be precise) to the merged style. */ - private Map _resolvedStyles; + private Map _resolvedStyles; /** * Used if there are no styles matching a widget. @@ -74,7 +74,7 @@ DefaultSynthStyleFactory() { _tmpList = new BakedArrayList(5); _styles = new ArrayList(); - _resolvedStyles = new HashMap(); + _resolvedStyles = new HashMap(); } public synchronized void addStyle(DefaultSynthStyle style, @@ -138,7 +138,7 @@ * Fetches any styles that match the passed into arguments into * matches. */ - private void getMatchingStyles(java.util.List matches, JComponent c, + private void getMatchingStyles(List matches, JComponent c, Region id) { String idName = id.getLowerCaseName(); String cName = c.getName(); @@ -166,7 +166,7 @@ /** * Caches the specified style. */ - private void cacheStyle(java.util.List styles, SynthStyle style) { + private void cacheStyle(List styles, SynthStyle style) { BakedArrayList cachedStyles = new BakedArrayList(styles); _resolvedStyles.put(cachedStyles, style); @@ -175,11 +175,11 @@ /** * Returns the cached style from the passed in arguments. */ - private SynthStyle getCachedStyle(java.util.List styles) { + private SynthStyle getCachedStyle(List styles) { if (styles.size() == 0) { return null; } - return (SynthStyle)_resolvedStyles.get(styles); + return _resolvedStyles.get(styles); } /** @@ -187,7 +187,7 @@ * is reverse sorted, that is the most recently added style found to * match will be first. */ - private SynthStyle mergeStyles(java.util.List styles) { + private SynthStyle mergeStyles(List styles) { int size = styles.size(); if (size == 0) { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/ImagePainter.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/ImagePainter.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/ImagePainter.java Wed Jul 05 16:42:37 2017 +0200 @@ -66,7 +66,7 @@ Paint9Painter painter; if (cacheRef == null || (painter = cacheRef.get()) == null) { painter = new Paint9Painter(30); - cacheRef = new WeakReference(painter); + cacheRef = new WeakReference(painter); AppContext.getAppContext().put(CACHE_KEY, cacheRef); } return painter; diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/Region.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/Region.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/Region.java Wed Jul 05 16:42:37 2017 +0200 @@ -67,8 +67,8 @@ * @author Scott Violet */ public class Region { - private static final Map uiToRegionMap = new HashMap(); - private static final Map lowerCaseNameMap = new HashMap(); + private static final Map uiToRegionMap = new HashMap(); + private static final Map lowerCaseNameMap = new HashMap(); /** * ArrowButton's are special types of buttons that also render a @@ -451,15 +451,11 @@ static Region getRegion(JComponent c) { - return (Region)uiToRegionMap.get(c.getUIClassID()); + return uiToRegionMap.get(c.getUIClassID()); } static void registerUIs(UIDefaults table) { - Iterator uis = uiToRegionMap.keySet().iterator(); - - while (uis.hasNext()) { - Object key = uis.next(); - + for (String key : uiToRegionMap.keySet()) { table.put(key, "javax.swing.plaf.synth.SynthLookAndFeel"); } } @@ -521,7 +517,7 @@ */ String getLowerCaseName() { synchronized(lowerCaseNameMap) { - String lowerCaseName = (String)lowerCaseNameMap.get(this); + String lowerCaseName = lowerCaseNameMap.get(this); if (lowerCaseName == null) { lowerCaseName = getName().toLowerCase(); lowerCaseNameMap.put(this, lowerCaseName); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -262,7 +262,7 @@ * Returns the default icon. This should NOT callback * to the JComponent. * - * @param b AbstractButton the iocn is associated with + * @param b AbstractButton the icon is associated with * @return default icon */ @@ -445,9 +445,7 @@ * Returns the Icon used in calculating the pref/min/max size. */ protected Icon getSizingIcon(AbstractButton b) { - // NOTE: this is slightly different than BasicButtonUI, where it - // would just use getIcon, but this should be ok. - Icon icon = (b.isEnabled()) ? b.getIcon() : b.getDisabledIcon(); + Icon icon = getEnabledIcon(b, b.getIcon()); if (icon == null) { icon = getDefaultIcon(b); } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -336,7 +336,7 @@ return oldValue; } else { // Must take the value from the editor and get the value and cast it to the new type. - Class cls = oldValue.getClass(); + Class cls = oldValue.getClass(); try { Method method = cls.getMethod("valueOf", new Class[]{String.class}); newValue = method.invoke(oldValue, new Object[] { editor.getText()}); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java Wed Jul 05 16:42:37 2017 +0200 @@ -39,7 +39,7 @@ * @author Scott Violet */ public class SynthContext { - private static final Map contextMap; + private static final Map> contextMap; private JComponent component; private Region region; @@ -48,7 +48,7 @@ static { - contextMap = new HashMap(); + contextMap = new HashMap>(); } @@ -58,13 +58,13 @@ SynthContext context = null; synchronized(contextMap) { - java.util.List instances = (java.util.List)contextMap.get(type); + List instances = contextMap.get(type); if (instances != null) { int size = instances.size(); if (size > 0) { - context = (SynthContext)instances.remove(size - 1); + context = instances.remove(size - 1); } } } @@ -81,11 +81,10 @@ static void releaseContext(SynthContext context) { synchronized(contextMap) { - java.util.List instances = (java.util.List)contextMap.get( - context.getClass()); + List instances = contextMap.get(context.getClass()); if (instances == null) { - instances = new ArrayList(5); + instances = new ArrayList(5); contextMap.put(context.getClass(), instances); } instances.add(context); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthEditorPaneUI.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthEditorPaneUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthEditorPaneUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -45,8 +45,8 @@ * I would prefer to use UIResource instad of this. * Unfortunately Boolean is a final class */ - private Boolean localTrue = new Boolean(true); - private Boolean localFalse = new Boolean(false); + private Boolean localTrue = Boolean.TRUE; + private Boolean localFalse = Boolean.FALSE; /** * Creates a UI for the JTextPane. @@ -69,7 +69,7 @@ c.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, localTrue); } - updateStyle((JTextComponent)getComponent()); + updateStyle(getComponent()); } protected void uninstallDefaults() { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthGraphicsUtils.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthGraphicsUtils.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthGraphicsUtils.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * 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,8 @@ package javax.swing.plaf.synth; import sun.swing.SwingUtilities2; +import sun.swing.MenuItemLayoutHelper; + import java.awt.*; import javax.swing.*; import javax.swing.plaf.basic.BasicHTML; @@ -411,12 +413,204 @@ } + /** + * A quick note about how preferred sizes are calculated... Generally + * speaking, SynthPopupMenuUI will run through the list of its children + * (from top to bottom) and ask each for its preferred size. Each menu + * item will add up the max width of each element (icons, text, + * accelerator spacing, accelerator text or arrow icon) encountered thus + * far, so by the time all menu items have been calculated, we will + * know the maximum (preferred) menu item size for that popup menu. + * Later when it comes time to paint each menu item, we can use those + * same accumulated max element sizes in order to layout the item. + */ + static Dimension getPreferredMenuItemSize(SynthContext context, + SynthContext accContext, JComponent c, + Icon checkIcon, Icon arrowIcon, int defaultTextIconGap, + String acceleratorDelimiter, boolean useCheckAndArrow, + String propertyPrefix) { + + JMenuItem mi = (JMenuItem) c; + SynthMenuItemLayoutHelper lh = new SynthMenuItemLayoutHelper( + context, accContext, mi, checkIcon, arrowIcon, + MenuItemLayoutHelper.createMaxRect(), defaultTextIconGap, + acceleratorDelimiter, SynthLookAndFeel.isLeftToRight(mi), + useCheckAndArrow, propertyPrefix); + + Dimension result = new Dimension(); + + // Calculate the result width + int gap = lh.getGap(); + result.width = 0; + MenuItemLayoutHelper.addMaxWidth(lh.getCheckSize(), gap, result); + MenuItemLayoutHelper.addMaxWidth(lh.getLabelSize(), gap, result); + MenuItemLayoutHelper.addWidth(lh.getMaxAccOrArrowWidth(), 5 * gap, result); + // The last gap is unnecessary + result.width -= gap; + + // Calculate the result height + result.height = MenuItemLayoutHelper.max(lh.getCheckSize().getHeight(), + lh.getLabelSize().getHeight(), lh.getAccSize().getHeight(), + lh.getArrowSize().getHeight()); + + // Take into account menu item insets + Insets insets = lh.getMenuItem().getInsets(); + if (insets != null) { + result.width += insets.left + insets.right; + result.height += insets.top + insets.bottom; + } + + // if the width is even, bump it up one. This is critical + // for the focus dash lhne to draw properly + if (result.width % 2 == 0) { + result.width++; + } + + // if the height is even, bump it up one. This is critical + // for the text to center properly + if (result.height % 2 == 0) { + result.height++; + } + + return result; + } + + static void applyInsets(Rectangle rect, Insets insets) { + if (insets != null) { + rect.x += insets.left; + rect.y += insets.top; + rect.width -= (insets.right + rect.x); + rect.height -= (insets.bottom + rect.y); + } + } + + static void paint(SynthContext context, SynthContext accContext, Graphics g, + Icon checkIcon, Icon arrowIcon, String acceleratorDelimiter, + int defaultTextIconGap, String propertyPrefix) { + JMenuItem mi = (JMenuItem) context.getComponent(); + SynthStyle style = context.getStyle(); + g.setFont(style.getFont(context)); + + Rectangle viewRect = new Rectangle(0, 0, mi.getWidth(), mi.getHeight()); + applyInsets(viewRect, mi.getInsets()); + + SynthMenuItemLayoutHelper lh = new SynthMenuItemLayoutHelper( + context, accContext, mi, checkIcon, + arrowIcon, viewRect, defaultTextIconGap, acceleratorDelimiter, + SynthLookAndFeel.isLeftToRight(mi), + MenuItemLayoutHelper.useCheckAndArrow(mi), propertyPrefix); + MenuItemLayoutHelper.LayoutResult lr = lh.layoutMenuItem(); + + paintMenuItem(g, lh, lr); + } + + static void paintMenuItem(Graphics g, SynthMenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + // Save original graphics font and color + Font holdf = g.getFont(); + Color holdc = g.getColor(); + + paintBackground(g, lh); + paintCheckIcon(g, lh, lr); + paintIcon(g, lh, lr); + paintText(g, lh, lr); + paintAccText(g, lh, lr); + paintArrowIcon(g, lh, lr); + + // Restore original graphics font and color + g.setColor(holdc); + g.setFont(holdf); + } + + static void paintBackground(Graphics g, SynthMenuItemLayoutHelper lh) { + paintBackground(lh.getContext(), g, lh.getMenuItem()); + } + + static void paintBackground(SynthContext context, Graphics g, JComponent c) { + context.getPainter().paintMenuItemBackground(context, g, 0, 0, + c.getWidth(), c.getHeight()); + } + + static void paintIcon(Graphics g, SynthMenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + if (lh.getIcon() != null) { + Icon icon; + JMenuItem mi = lh.getMenuItem(); + ButtonModel model = mi.getModel(); + if (!model.isEnabled()) { + icon = mi.getDisabledIcon(); + } else if (model.isPressed() && model.isArmed()) { + icon = mi.getPressedIcon(); + if (icon == null) { + // Use default icon + icon = mi.getIcon(); + } + } else { + icon = mi.getIcon(); + } + + if (icon != null) { + Rectangle iconRect = lr.getIconRect(); + SynthIcon.paintIcon(icon, lh.getContext(), g, iconRect.x, + iconRect.y, iconRect.width, iconRect.height); + } + } + } + + static void paintCheckIcon(Graphics g, SynthMenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + if (lh.getCheckIcon() != null) { + Rectangle checkRect = lr.getCheckRect(); + SynthIcon.paintIcon(lh.getCheckIcon(), lh.getContext(), g, + checkRect.x, checkRect.y, checkRect.width, checkRect.height); + } + } + + static void paintAccText(Graphics g, SynthMenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + String accText = lh.getAccText(); + if (accText != null && !accText.equals("")) { + g.setColor(lh.getAccStyle().getColor(lh.getAccContext(), + ColorType.TEXT_FOREGROUND)); + g.setFont(lh.getAccStyle().getFont(lh.getAccContext())); + lh.getAccGraphicsUtils().paintText(lh.getAccContext(), g, accText, + lr.getAccRect().x, lr.getAccRect().y, -1); + } + } + + static void paintText(Graphics g, SynthMenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + if (!lh.getText().equals("")) { + if (lh.getHtmlView() != null) { + // Text is HTML + lh.getHtmlView().paint(g, lr.getTextRect()); + } else { + // Text isn't HTML + g.setColor(lh.getStyle().getColor( + lh.getContext(), ColorType.TEXT_FOREGROUND)); + g.setFont(lh.getStyle().getFont(lh.getContext())); + lh.getGraphicsUtils().paintText(lh.getContext(), g, lh.getText(), + lr.getTextRect().x, lr.getTextRect().y, + lh.getMenuItem().getDisplayedMnemonicIndex()); + } + } + } + + static void paintArrowIcon(Graphics g, SynthMenuItemLayoutHelper lh, + MenuItemLayoutHelper.LayoutResult lr) { + if (lh.getArrowIcon() != null) { + Rectangle arrowRect = lr.getArrowRect(); + SynthIcon.paintIcon(lh.getArrowIcon(), lh.getContext(), g, + arrowRect.x, arrowRect.y, arrowRect.width, arrowRect.height); + } + } + /** * Wraps a SynthIcon around the Icon interface, forwarding calls to * the SynthIcon with a given SynthContext. */ private static class SynthIconWrapper implements Icon { - private static final java.util.List CACHE = new java.util.ArrayList(1); + private static final java.util.List CACHE = new java.util.ArrayList(1); private SynthIcon synthIcon; private SynthContext context; @@ -425,8 +619,7 @@ synchronized(CACHE) { int size = CACHE.size(); if (size > 0) { - SynthIconWrapper wrapper = (SynthIconWrapper)CACHE.remove( - size - 1); + SynthIconWrapper wrapper = CACHE.remove(size - 1); wrapper.reset(icon, context); return wrapper; } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java Wed Jul 05 16:42:37 2017 +0200 @@ -197,25 +197,25 @@ protected void addSystemMenuItems(JPopupMenu menu) { // PENDING: this should all be localizable! - JMenuItem mi = (JMenuItem)menu.add(restoreAction); + JMenuItem mi = menu.add(restoreAction); mi.setMnemonic('R'); - mi = (JMenuItem)menu.add(moveAction); + mi = menu.add(moveAction); mi.setMnemonic('M'); - mi = (JMenuItem)menu.add(sizeAction); + mi = menu.add(sizeAction); mi.setMnemonic('S'); - mi = (JMenuItem)menu.add(iconifyAction); + mi = menu.add(iconifyAction); mi.setMnemonic('n'); - mi = (JMenuItem)menu.add(maximizeAction); + mi = menu.add(maximizeAction); mi.setMnemonic('x'); menu.add(new JSeparator()); - mi = (JMenuItem)menu.add(closeAction); + mi = menu.add(closeAction); mi.setMnemonic('C'); } protected void showSystemMenu() { Insets insets = frame.getInsets(); if (!frame.isIcon()) { - systemPopupMenu.show(frame, insets.left, getY() + getHeight()); + systemPopupMenu.show(frame, menuButton.getX(), getY() + getHeight()); } else { systemPopupMenu.show(menuButton, getX() - insets.left - insets.right, diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthLookAndFeel.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthLookAndFeel.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthLookAndFeel.java Wed Jul 05 16:42:37 2017 +0200 @@ -107,7 +107,7 @@ * Map of defaults table entries. This is populated via the load * method. */ - private Map defaultsMap; + private Map defaultsMap; private Handler _handler; @@ -308,8 +308,8 @@ children = ((Container)c).getComponents(); } if (children != null) { - for(int i = 0; i < children.length; i++) { - updateStyles(children[i]); + for (Component child : children) { + updateStyles(child); } } } @@ -581,7 +581,7 @@ } if (defaultsMap == null) { - defaultsMap = new HashMap(); + defaultsMap = new HashMap(); } new SynthParser().parse(input, (DefaultSynthStyleFactory) factory, @@ -611,7 +611,7 @@ } if (defaultsMap == null) { - defaultsMap = new HashMap(); + defaultsMap = new HashMap(); } InputStream input = url.openStream(); @@ -771,7 +771,7 @@ */ private static Object getAATextInfo() { String language = Locale.getDefault().getLanguage(); - String desktop = (String) + String desktop = AccessController.doPrivileged(new GetPropertyAction("sun.desktop")); boolean isCjkLocale = (Locale.CHINESE.getLanguage().equals(language) || @@ -786,7 +786,7 @@ return aaTextInfo; } - private static ReferenceQueue queue = new ReferenceQueue(); + private static ReferenceQueue queue = new ReferenceQueue(); private static void flushUnreferenced() { AATextListener aatl; @@ -796,7 +796,7 @@ } private static class AATextListener - extends WeakReference implements PropertyChangeListener { + extends WeakReference implements PropertyChangeListener { private String key = SunToolkit.DESKTOPFONTHINTS; AATextListener(LookAndFeel laf) { @@ -812,7 +812,7 @@ return; } - LookAndFeel laf = (LookAndFeel) get(); + LookAndFeel laf = get(); if (laf == null || laf != UIManager.getLookAndFeel()) { dispose(); return; @@ -835,8 +835,8 @@ private static void updateWindowUI(Window window) { updateStyles(window); Window ownedWins[] = window.getOwnedWindows(); - for (int i = 0; i < ownedWins.length; i++) { - updateWindowUI(ownedWins[i]); + for (Window w : ownedWins) { + updateWindowUI(w); } } @@ -845,8 +845,8 @@ */ private static void updateAllUIs() { Frame appFrames[] = Frame.getFrames(); - for (int i = 0; i < appFrames.length; i++) { - updateWindowUI(appFrames[i]); + for (Frame frame : appFrames) { + updateWindowUI(frame); } } @@ -909,7 +909,7 @@ // register it on the new one. KeyboardFocusManager manager = (KeyboardFocusManager)evt.getSource(); - if (((Boolean)newValue).equals(Boolean.FALSE)) { + if (newValue.equals(Boolean.FALSE)) { manager.removePropertyChangeListener(_handler); } else { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java Wed Jul 05 16:42:37 2017 +0200 @@ -0,0 +1,308 @@ +/* + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.swing.plaf.synth; + +import sun.swing.StringUIClientPropertyKey; +import sun.swing.MenuItemLayoutHelper; +import sun.swing.plaf.synth.SynthIcon; + +import javax.swing.*; +import javax.swing.text.View; +import java.awt.*; + +/** + * Calculates preferred size and layouts synth menu items. + * + * All JMenuItems (and JMenus) include enough space for the insets + * plus one or more elements. When we say "label" below, we mean + * "icon and/or text." + * + * Cases to consider for SynthMenuItemUI (visualized here in a + * LTR orientation; the RTL case would be reversed): + * label + * check icon + label + * check icon + label + accelerator + * label + accelerator + * + * Cases to consider for SynthMenuUI (again visualized here in a + * LTR orientation): + * label + arrow + * + * Note that in the above scenarios, accelerator and arrow icon are + * mutually exclusive. This means that if a popup menu contains a mix + * of JMenus and JMenuItems, we only need to allow enough space for + * max(maxAccelerator, maxArrow), and both accelerators and arrow icons + * can occupy the same "column" of space in the menu. + */ +class SynthMenuItemLayoutHelper extends MenuItemLayoutHelper { + + public static final StringUIClientPropertyKey MAX_ACC_OR_ARROW_WIDTH = + new StringUIClientPropertyKey("maxAccOrArrowWidth"); + + public static final ColumnAlignment LTR_ALIGNMENT_1 = + new ColumnAlignment( + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.RIGHT, + SwingConstants.RIGHT + ); + public static final ColumnAlignment LTR_ALIGNMENT_2 = + new ColumnAlignment( + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.LEFT, + SwingConstants.RIGHT + ); + public static final ColumnAlignment RTL_ALIGNMENT_1 = + new ColumnAlignment( + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.LEFT, + SwingConstants.LEFT + ); + public static final ColumnAlignment RTL_ALIGNMENT_2 = + new ColumnAlignment( + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.RIGHT, + SwingConstants.LEFT + ); + + private SynthContext context; + private SynthContext accContext; + private SynthStyle style; + private SynthStyle accStyle; + private SynthGraphicsUtils gu; + private SynthGraphicsUtils accGu; + private boolean alignAcceleratorText; + private int maxAccOrArrowWidth; + + public SynthMenuItemLayoutHelper(SynthContext context, SynthContext accContext, + JMenuItem mi, Icon checkIcon, Icon arrowIcon, + Rectangle viewRect, int gap, String accDelimiter, + boolean isLeftToRight, boolean useCheckAndArrow, + String propertyPrefix) { + this.context = context; + this.accContext = accContext; + this.style = context.getStyle(); + this.accStyle = accContext.getStyle(); + this.gu = style.getGraphicsUtils(context); + this.accGu = accStyle.getGraphicsUtils(accContext); + this.alignAcceleratorText = getAlignAcceleratorText(propertyPrefix); + reset(mi, checkIcon, arrowIcon, viewRect, gap, accDelimiter, + isLeftToRight, style.getFont(context), accStyle.getFont(accContext), + useCheckAndArrow, propertyPrefix); + setLeadingGap(0); + } + + private boolean getAlignAcceleratorText(String propertyPrefix) { + return style.getBoolean(context, + propertyPrefix + ".alignAcceleratorText", true); + } + + protected void calcWidthsAndHeights() { + // iconRect + if (getIcon() != null) { + getIconSize().setWidth(SynthIcon.getIconWidth(getIcon(), context)); + getIconSize().setHeight(SynthIcon.getIconHeight(getIcon(), context)); + } + + // accRect + if (!getAccText().equals("")) { + getAccSize().setWidth(accGu.computeStringWidth(getAccContext(), + getAccFontMetrics().getFont(), getAccFontMetrics(), + getAccText())); + getAccSize().setHeight(getAccFontMetrics().getHeight()); + } + + // textRect + if (getText() == null) { + setText(""); + } else if (!getText().equals("")) { + if (getHtmlView() != null) { + // Text is HTML + getTextSize().setWidth( + (int) getHtmlView().getPreferredSpan(View.X_AXIS)); + getTextSize().setHeight( + (int) getHtmlView().getPreferredSpan(View.Y_AXIS)); + } else { + // Text isn't HTML + getTextSize().setWidth(gu.computeStringWidth(context, + getFontMetrics().getFont(), getFontMetrics(), + getText())); + getTextSize().setHeight(getFontMetrics().getHeight()); + } + } + + if (useCheckAndArrow()) { + // checkIcon + if (getCheckIcon() != null) { + getCheckSize().setWidth( + SynthIcon.getIconWidth(getCheckIcon(), context)); + getCheckSize().setHeight( + SynthIcon.getIconHeight(getCheckIcon(), context)); + } + // arrowRect + if (getArrowIcon() != null) { + getArrowSize().setWidth( + SynthIcon.getIconWidth(getArrowIcon(), context)); + getArrowSize().setHeight( + SynthIcon.getIconHeight(getArrowIcon(), context)); + } + } + + // labelRect + if (isColumnLayout()) { + getLabelSize().setWidth(getIconSize().getWidth() + + getTextSize().getWidth() + getGap()); + getLabelSize().setHeight(MenuItemLayoutHelper.max( + getCheckSize().getHeight(), + getIconSize().getHeight(), + getTextSize().getHeight(), + getAccSize().getHeight(), + getArrowSize().getHeight())); + } else { + Rectangle textRect = new Rectangle(); + Rectangle iconRect = new Rectangle(); + gu.layoutText(context, getFontMetrics(), getText(), getIcon(), + getHorizontalAlignment(), getVerticalAlignment(), + getHorizontalTextPosition(), getVerticalTextPosition(), + getViewRect(), iconRect, textRect, getGap()); + textRect.width += getLeftTextExtraWidth() + getRightTextExtraWidth(); + Rectangle labelRect = iconRect.union(textRect); + getLabelSize().setHeight(labelRect.height); + getLabelSize().setWidth(labelRect.width); + } + } + + protected void calcMaxWidths() { + calcMaxWidth(getCheckSize(), MAX_CHECK_WIDTH); + maxAccOrArrowWidth = + calcMaxValue(MAX_ACC_OR_ARROW_WIDTH, getArrowSize().getWidth()); + maxAccOrArrowWidth = + calcMaxValue(MAX_ACC_OR_ARROW_WIDTH, getAccSize().getWidth()); + + if (isColumnLayout()) { + calcMaxWidth(getIconSize(), MAX_ICON_WIDTH); + calcMaxWidth(getTextSize(), MAX_TEXT_WIDTH); + int curGap = getGap(); + if ((getIconSize().getMaxWidth() == 0) + || (getTextSize().getMaxWidth() == 0)) { + curGap = 0; + } + getLabelSize().setMaxWidth( + calcMaxValue(MAX_LABEL_WIDTH, getIconSize().getMaxWidth() + + getTextSize().getMaxWidth() + curGap)); + } else { + // We shouldn't use current icon and text widths + // in maximal widths calculation for complex layout. + getIconSize().setMaxWidth(getParentIntProperty( + MAX_ICON_WIDTH)); + calcMaxWidth(getLabelSize(), MAX_LABEL_WIDTH); + // If maxLabelWidth is wider + // than the widest icon + the widest text + gap, + // we should update the maximal text witdh + int candidateTextWidth = getLabelSize().getMaxWidth() - + getIconSize().getMaxWidth(); + if (getIconSize().getMaxWidth() > 0) { + candidateTextWidth -= getGap(); + } + getTextSize().setMaxWidth(calcMaxValue( + MAX_TEXT_WIDTH, candidateTextWidth)); + } + } + + public SynthContext getContext() { + return context; + } + + public SynthContext getAccContext() { + return accContext; + } + + public SynthStyle getStyle() { + return style; + } + + public SynthStyle getAccStyle() { + return accStyle; + } + + public SynthGraphicsUtils getGraphicsUtils() { + return gu; + } + + public SynthGraphicsUtils getAccGraphicsUtils() { + return accGu; + } + + public boolean alignAcceleratorText() { + return alignAcceleratorText; + } + + public int getMaxAccOrArrowWidth() { + return maxAccOrArrowWidth; + } + + protected void prepareForLayout(LayoutResult lr) { + lr.getCheckRect().width = getCheckSize().getMaxWidth(); + // An item can have an arrow or a check icon at once + if (useCheckAndArrow() && (!"".equals(getAccText()))) { + lr.getAccRect().width = maxAccOrArrowWidth; + } else { + lr.getArrowRect().width = maxAccOrArrowWidth; + } + } + + public ColumnAlignment getLTRColumnAlignment() { + if (alignAcceleratorText()) { + return LTR_ALIGNMENT_2; + } else { + return LTR_ALIGNMENT_1; + } + } + + public ColumnAlignment getRTLColumnAlignment() { + if (alignAcceleratorText()) { + return RTL_ALIGNMENT_2; + } else { + return RTL_ALIGNMENT_1; + } + } + + protected void layoutIconAndTextInLabelRect(LayoutResult lr) { + lr.setTextRect(new Rectangle()); + lr.setIconRect(new Rectangle()); + gu.layoutText(context, getFontMetrics(), getText(), getIcon(), + getHorizontalAlignment(), getVerticalAlignment(), + getHorizontalTextPosition(), getVerticalTextPosition(), + lr.getLabelRect(), lr.getIconRect(), lr.getTextRect(), getGap()); + } +} diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,7 +37,7 @@ import javax.swing.plaf.basic.*; import javax.swing.text.View; import sun.swing.plaf.synth.*; -import sun.swing.SwingUtilities2; +import sun.swing.MenuItemLayoutHelper; /** @@ -59,542 +59,16 @@ return new SynthMenuItemUI(); } - // - // The next handful of static methods are used by both SynthMenuUI - // and SynthMenuItemUI. This is necessitated by SynthMenuUI not - // extending SynthMenuItemUI. - // - - /* - * All JMenuItems (and JMenus) include enough space for the insets - * plus one or more elements. When we say "icon(s)" below, we mean - * "check/radio indicator and/or user icon." If both are defined for - * a given menu item, then in a LTR orientation the check/radio indicator - * is on the left side followed by the user icon to the right; it is - * just the opposite in a RTL orientation. - * - * Cases to consider for SynthMenuItemUI (visualized here in a - * LTR orientation; the RTL case would be reversed): - * text - * icon(s) + text - * icon(s) + text + accelerator - * text + accelerator - * - * Cases to consider for SynthMenuUI (again visualized here in a - * LTR orientation): - * text + arrow - * (user)icon + text + arrow - * - * Note that in the above scenarios, accelerator and arrow icon are - * mutually exclusive. This means that if a popup menu contains a mix - * of JMenus and JMenuItems, we only need to allow enough space for - * max(maxAccelerator, maxArrow), and both accelerators and arrow icons - * can occupy the same "column" of space in the menu. - * - * A quick note about how preferred sizes are calculated... Generally - * speaking, SynthPopupMenuUI will run through the list of its children - * (from top to bottom) and ask each for its preferred size. Each menu - * item will add up the max width of each element (icons, text, - * accelerator spacing, accelerator text or arrow icon) encountered thus - * far, so by the time all menu items have been calculated, we will - * know the maximum (preferred) menu item size for that popup menu. - * Later when it comes time to paint each menu item, we can use those - * same accumulated max element sizes in order to layout the item. - */ - static Dimension getPreferredMenuItemSize(SynthContext context, - SynthContext accContext, JComponent c, - Icon checkIcon, Icon arrowIcon, int defaultTextIconGap, - String acceleratorDelimiter) { - JMenuItem b = (JMenuItem) c; - Icon icon = (Icon) b.getIcon(); - String text = b.getText(); - KeyStroke accelerator = b.getAccelerator(); - String acceleratorText = ""; - - if (accelerator != null) { - int modifiers = accelerator.getModifiers(); - if (modifiers > 0) { - acceleratorText = KeyEvent.getKeyModifiersText(modifiers); - acceleratorText += acceleratorDelimiter; - } - int keyCode = accelerator.getKeyCode(); - if (keyCode != 0) { - acceleratorText += KeyEvent.getKeyText(keyCode); - } else { - acceleratorText += accelerator.getKeyChar(); - } - } - - Font font = context.getStyle().getFont(context); - FontMetrics fm = b.getFontMetrics(font); - FontMetrics fmAccel = b.getFontMetrics(accContext.getStyle(). - getFont(accContext)); - - resetRects(); - - layoutMenuItem( - context, fm, accContext, text, fmAccel, acceleratorText, - icon, checkIcon, arrowIcon, b.getVerticalAlignment(), - b.getHorizontalAlignment(), b.getVerticalTextPosition(), - b.getHorizontalTextPosition(), viewRect, iconRect, textRect, - acceleratorRect, checkIconRect, arrowIconRect, - text == null ? 0 : defaultTextIconGap, defaultTextIconGap); - - r.setBounds(textRect); - - int totalIconWidth = 0; - int maxIconHeight = 0; - if (icon != null) { - // Add in the user icon - totalIconWidth += iconRect.width; - if (textRect.width > 0) { - // Allow for some room between the user icon and the text - totalIconWidth += defaultTextIconGap; - } - maxIconHeight = Math.max(iconRect.height, maxIconHeight); - } - if (checkIcon != null) { - // Add in the checkIcon - totalIconWidth += checkIconRect.width; - if (textRect.width > 0 || icon != null) { - // Allow for some room between the check/radio indicator - // and the text (or user icon, if both are specified) - totalIconWidth += defaultTextIconGap; - } - maxIconHeight = Math.max(checkIconRect.height, maxIconHeight); - } - - int arrowWidth = 0; - if (arrowIcon != null) { - // Add in the arrowIcon - arrowWidth += defaultTextIconGap; - arrowWidth += arrowIconRect.width; - maxIconHeight = Math.max(arrowIconRect.height, maxIconHeight); - } - - int accelSpacing = 0; - if (acceleratorRect.width > 0) { - // Allow for some room between the text and the accelerator - accelSpacing += 4*defaultTextIconGap; - } - - // Take text and all icons into account when determining height - r.height = Math.max(r.height, maxIconHeight); - - // To make the accelerator texts appear in a column, - // find the widest MenuItem text and the widest accelerator text. - - // Get the parent, which stores the information. - Container parent = b.getParent(); - - if (parent instanceof JPopupMenu) { - SynthPopupMenuUI popupUI = (SynthPopupMenuUI)SynthLookAndFeel. - getUIOfType(((JPopupMenu)parent).getUI(), - SynthPopupMenuUI.class); - - if (popupUI != null) { - // This gives us the widest MenuItem text encountered thus - // far in the parent JPopupMenu - r.width = popupUI.adjustTextWidth(r.width); - - // Add in the widest icon (includes both user and - // check/radio icons) encountered thus far - r.width += popupUI.adjustIconWidth(totalIconWidth); - - // Add in the widest text/accelerator spacing - // encountered thus far - r.width += popupUI.adjustAccelSpacingWidth(accelSpacing); - - // Add in the widest accelerator text (or arrow) - // encountered thus far (at least one of these values - // will always be zero, so we combine them here to - // avoid double counting) - int totalAccelOrArrow = acceleratorRect.width + arrowWidth; - r.width += popupUI.adjustAcceleratorWidth(totalAccelOrArrow); - } - } - else if (parent != null && !(b instanceof JMenu && - ((JMenu)b).isTopLevelMenu())) { - r.width += - totalIconWidth + accelSpacing + - acceleratorRect.width + arrowWidth; - } - - Insets insets = b.getInsets(); - if(insets != null) { - r.width += insets.left + insets.right; - r.height += insets.top + insets.bottom; - } - - // if the width is even, bump it up one. This is critical - // for the focus dash line to draw properly - if(r.width%2 == 0) { - r.width++; - } - - // if the height is even, bump it up one. This is critical - // for the text to center properly - if(r.height%2 == 0) { - r.height++; - } - return r.getSize(); - } - - static void paint(SynthContext context, SynthContext accContext, - Graphics g, Icon checkIcon, Icon arrowIcon, - String acceleratorDelimiter, - int defaultTextIconGap) { - JComponent c = context.getComponent(); - JMenuItem b = (JMenuItem)c; - ButtonModel model = b.getModel(); - Insets i = b.getInsets(); - - resetRects(); - - viewRect.setBounds(0, 0, b.getWidth(), b.getHeight()); - - viewRect.x += i.left; - viewRect.y += i.top; - viewRect.width -= (i.right + viewRect.x); - viewRect.height -= (i.bottom + viewRect.y); - - SynthStyle style = context.getStyle(); - Font f = style.getFont(context); - g.setFont(f); - FontMetrics fm = SwingUtilities2.getFontMetrics(c, g, f); - FontMetrics accFM = SwingUtilities2.getFontMetrics(c, g, - accContext.getStyle(). - getFont(accContext)); - - // get Accelerator text - KeyStroke accelerator = b.getAccelerator(); - String acceleratorText = ""; - if (accelerator != null) { - int modifiers = accelerator.getModifiers(); - if (modifiers > 0) { - acceleratorText = KeyEvent.getKeyModifiersText(modifiers); - acceleratorText += acceleratorDelimiter; - } - - int keyCode = accelerator.getKeyCode(); - if (keyCode != 0) { - acceleratorText += KeyEvent.getKeyText(keyCode); - } else { - acceleratorText += accelerator.getKeyChar(); - } - } - - // Layout the text and icon - String text = layoutMenuItem(context, fm, accContext, - b.getText(), accFM, acceleratorText, b.getIcon(), - checkIcon, arrowIcon, - b.getVerticalAlignment(), b.getHorizontalAlignment(), - b.getVerticalTextPosition(), b.getHorizontalTextPosition(), - viewRect, iconRect, textRect, acceleratorRect, - checkIconRect, arrowIconRect, - b.getText() == null ? 0 : defaultTextIconGap, - defaultTextIconGap - ); - - // Paint the Check - if (checkIcon != null) { - SynthIcon.paintIcon(checkIcon, context, g, checkIconRect.x, - checkIconRect.y, checkIconRect.width, checkIconRect.height); - } - - // Paint the Icon - if(b.getIcon() != null) { - Icon icon; - if(!model.isEnabled()) { - icon = (Icon) b.getDisabledIcon(); - } else if(model.isPressed() && model.isArmed()) { - icon = (Icon) b.getPressedIcon(); - if(icon == null) { - // Use default icon - icon = (Icon) b.getIcon(); - } - } else { - icon = (Icon) b.getIcon(); - } - - if (icon!=null) { - SynthIcon.paintIcon(icon, context, g, iconRect.x, - iconRect.y, iconRect.width, iconRect.height); - } - } - - // Draw the Text - if(text != null) { - View v = (View) c.getClientProperty(BasicHTML.propertyKey); - if (v != null) { - v.paint(g, textRect); - } else { - g.setColor(style.getColor(context, ColorType.TEXT_FOREGROUND)); - g.setFont(style.getFont(context)); - style.getGraphicsUtils(context).paintText(context, g, text, - textRect.x, textRect.y, b.getDisplayedMnemonicIndex()); - } - } - - // Draw the Accelerator Text - if(acceleratorText != null && !acceleratorText.equals("")) { - // Get the maxAccWidth from the parent to calculate the offset. - int accOffset = 0; - Container parent = b.getParent(); - if (parent != null && parent instanceof JPopupMenu) { - SynthPopupMenuUI popupUI = (SynthPopupMenuUI) - ((JPopupMenu)parent).getUI(); - - // Note that we can only get here for SynthMenuItemUI - // (not SynthMenuUI) since acceleratorText is defined, - // so this cast should be safe - SynthMenuItemUI miUI = (SynthMenuItemUI) - SynthLookAndFeel.getUIOfType(b.getUI(), - SynthMenuItemUI.class); - - if (popupUI != null && miUI != null) { - String prop = - miUI.getPropertyPrefix() + ".alignAcceleratorText"; - boolean align = style.getBoolean(context, prop, true); - - // Calculate the offset, with which the accelerator texts - // will be drawn. - if (align) { - // When align==true and we're in the LTR case, - // we add an offset here so that all accelerators - // will be left-justified in their own column. - int max = popupUI.getMaxAcceleratorWidth(); - if (max > 0) { - accOffset = max - acceleratorRect.width; - if (!SynthLookAndFeel.isLeftToRight(c)) { - // In the RTL, flip the sign so that all - // accelerators will be right-justified. - accOffset = -accOffset; - } - } - } //else { - // Don't need to do anything special here; in the - // LTR case, the accelerator is already justified - // against the right edge of the menu (and against - // the left edge in the RTL case). - //} - } - } - - SynthStyle accStyle = accContext.getStyle(); - - g.setColor(accStyle.getColor(accContext, - ColorType.TEXT_FOREGROUND)); - g.setFont(accStyle.getFont(accContext)); - accStyle.getGraphicsUtils(accContext).paintText( - accContext, g, acceleratorText, acceleratorRect.x - - accOffset, acceleratorRect.y, -1); - } - - // Paint the Arrow - if (arrowIcon != null) { - SynthIcon.paintIcon(arrowIcon, context, g, arrowIconRect.x, - arrowIconRect.y, arrowIconRect.width, arrowIconRect.height); + public void uninstallUI(JComponent c) { + super.uninstallUI(c); + // Remove values from the parent's Client Properties. + JComponent p = MenuItemLayoutHelper.getMenuItemParent((JMenuItem) c); + if (p != null) { + p.putClientProperty( + SynthMenuItemLayoutHelper.MAX_ACC_OR_ARROW_WIDTH, null); } } - /** - * Compute and return the location of the icons origin, the - * location of origin of the text baseline, and a possibly clipped - * version of the compound labels string. Locations are computed - * relative to the viewRect rectangle. - */ - - private static String layoutMenuItem( - SynthContext context, - FontMetrics fm, - SynthContext accContext, - String text, - FontMetrics fmAccel, - String acceleratorText, - Icon icon, - Icon checkIcon, - Icon arrowIcon, - int verticalAlignment, - int horizontalAlignment, - int verticalTextPosition, - int horizontalTextPosition, - Rectangle viewRect, - Rectangle iconRect, - Rectangle textRect, - Rectangle acceleratorRect, - Rectangle checkIconRect, - Rectangle arrowIconRect, - int textIconGap, - int menuItemGap - ) - { - // If parent is JPopupMenu, get and store it's UI - SynthPopupMenuUI popupUI = null; - JComponent b = context.getComponent(); - Container parent = b.getParent(); - if(parent instanceof JPopupMenu) { - popupUI = (SynthPopupMenuUI)SynthLookAndFeel. - getUIOfType(((JPopupMenu)parent).getUI(), - SynthPopupMenuUI.class); - } - - context.getStyle().getGraphicsUtils(context).layoutText( - context, fm, text, icon,horizontalAlignment, verticalAlignment, - horizontalTextPosition, verticalTextPosition, viewRect, - iconRect, textRect, textIconGap); - - /* Initialize the acceleratorText bounds rectangle textRect. If a null - * or and empty String was specified we substitute "" here - * and use 0,0,0,0 for acceleratorTextRect. - */ - if( (acceleratorText == null) || acceleratorText.equals("") ) { - acceleratorRect.width = acceleratorRect.height = 0; - acceleratorText = ""; - } - else { - SynthStyle style = accContext.getStyle(); - acceleratorRect.width = style.getGraphicsUtils(accContext). - computeStringWidth(accContext, fmAccel.getFont(), fmAccel, - acceleratorText); - acceleratorRect.height = fmAccel.getHeight(); - } - - // Initialize the checkIcon bounds rectangle width & height. - if (checkIcon != null) { - checkIconRect.width = SynthIcon.getIconWidth(checkIcon, - context); - checkIconRect.height = SynthIcon.getIconHeight(checkIcon, - context); - } - else { - checkIconRect.width = checkIconRect.height = 0; - } - - // Initialize the arrowIcon bounds rectangle width & height. - if (arrowIcon != null) { - arrowIconRect.width = SynthIcon.getIconWidth(arrowIcon, - context); - arrowIconRect.height = SynthIcon.getIconHeight(arrowIcon, - context); - } else { - arrowIconRect.width = arrowIconRect.height = 0; - } - - // Note: layoutText() has already left room for - // the user icon, so no need to adjust textRect below - // to account for the user icon. However, we do have to - // reposition textRect when the check icon is visible. - - Rectangle labelRect = iconRect.union(textRect); - if( SynthLookAndFeel.isLeftToRight(context.getComponent()) ) { - // Position the check and user icons - iconRect.x = viewRect.x; - if (checkIcon != null) { - checkIconRect.x = viewRect.x; - iconRect.x += menuItemGap + checkIconRect.width; - textRect.x += menuItemGap + checkIconRect.width; - } - - // Position the arrow icon - arrowIconRect.x = - viewRect.x + viewRect.width - arrowIconRect.width; - - // Position the accelerator text rect - acceleratorRect.x = - viewRect.x + viewRect.width - acceleratorRect.width; - - /* Align icons and text horizontally */ - if(popupUI != null) { - int thisTextOffset = popupUI.adjustTextOffset(textRect.x - - viewRect.x); - textRect.x = thisTextOffset + viewRect.x; - - if(icon != null) { - // REMIND: The following code currently assumes the - // default (TRAILING) horizontalTextPosition, which means - // it will always place the icon to the left of the text. - // Other values of horizontalTextPosition aren't very - // useful for menu items, so we ignore them for now, but - // someday we might want to fix this situation. - int thisIconOffset = - popupUI.adjustIconOffset(iconRect.x - viewRect.x); - iconRect.x = thisIconOffset + viewRect.x; - } - } - } else { - // Position the accelerator text rect - acceleratorRect.x = viewRect.x; - - // Position the arrow icon - arrowIconRect.x = viewRect.x; - - // Position the check and user icons - iconRect.x = - viewRect.x + viewRect.width - iconRect.width; - if (checkIcon != null) { - checkIconRect.x = - viewRect.x + viewRect.width - checkIconRect.width; - textRect.x -= menuItemGap + checkIconRect.width; - iconRect.x -= menuItemGap + checkIconRect.width; - } - - /* Align icons and text horizontally */ - if(popupUI != null) { - int thisTextOffset = viewRect.x + viewRect.width - - textRect.x - textRect.width; - thisTextOffset = popupUI.adjustTextOffset(thisTextOffset); - textRect.x = viewRect.x + viewRect.width - - thisTextOffset - textRect.width; - if(icon != null) { - // REMIND: The following code currently assumes the - // default (TRAILING) horizontalTextPosition, which means - // it will always place the icon to the right of the text. - // Other values of horizontalTextPosition aren't very - // useful for menu items, so we ignore them for now, but - // someday we might want to fix this situation. - int thisIconOffset = viewRect.x + viewRect.width - - iconRect.x - iconRect.width; - thisIconOffset = - popupUI.adjustIconOffset(thisIconOffset); - iconRect.x = viewRect.x + viewRect.width - - thisIconOffset - iconRect.width; - } - } - } - - // Align the accelerator text and all icons vertically - // with the center of the label rect. - int midY = labelRect.y + (labelRect.height/2); - iconRect.y = midY - (iconRect.height/2); - acceleratorRect.y = midY - (acceleratorRect.height/2); - arrowIconRect.y = midY - (arrowIconRect.height/2); - checkIconRect.y = midY - (checkIconRect.height/2); - - return text; - } - - // these rects are used for painting and preferredsize calculations. - // they used to be regenerated constantly. Now they are reused. - static Rectangle iconRect = new Rectangle(); - static Rectangle textRect = new Rectangle(); - static Rectangle acceleratorRect = new Rectangle(); - static Rectangle checkIconRect = new Rectangle(); - static Rectangle arrowIconRect = new Rectangle(); - static Rectangle viewRect = new Rectangle(Short.MAX_VALUE,Short.MAX_VALUE); - static Rectangle r = new Rectangle(); - - private static void resetRects() { - iconRect.setBounds(0, 0, 0, 0); - textRect.setBounds(0, 0, 0, 0); - acceleratorRect.setBounds(0, 0, 0, 0); - checkIconRect.setBounds(0, 0, 0, 0); - arrowIconRect.setBounds(0, 0, 0, 0); - viewRect.setBounds(0,0,Short.MAX_VALUE, Short.MAX_VALUE); - r.setBounds(0, 0, 0, 0); - } - - protected void installDefaults() { updateStyle(menuItem); } @@ -718,9 +192,11 @@ int defaultTextIconGap) { SynthContext context = getContext(c); SynthContext accContext = getContext(c, Region.MENU_ITEM_ACCELERATOR); - Dimension value = getPreferredMenuItemSize(context, accContext, - c, checkIcon, arrowIcon, defaultTextIconGap, - acceleratorDelimiter); + Dimension value = SynthGraphicsUtils.getPreferredMenuItemSize( + context, accContext, c, checkIcon, arrowIcon, + defaultTextIconGap, acceleratorDelimiter, + MenuItemLayoutHelper.useCheckAndArrow(menuItem), + getPropertyPrefix()); context.dispose(); accContext.dispose(); return value; @@ -751,14 +227,13 @@ String prefix = getPropertyPrefix(); Icon checkIcon = style.getIcon(context, prefix + ".checkIcon"); Icon arrowIcon = style.getIcon(context, prefix + ".arrowIcon"); - paint(context, accContext, g, checkIcon, arrowIcon, - acceleratorDelimiter, defaultTextIconGap); + SynthGraphicsUtils.paint(context, accContext, g, checkIcon, arrowIcon, + acceleratorDelimiter, defaultTextIconGap, getPropertyPrefix()); accContext.dispose(); } void paintBackground(SynthContext context, Graphics g, JComponent c) { - context.getPainter().paintMenuItemBackground(context, g, 0, 0, - c.getWidth(), c.getHeight()); + SynthGraphicsUtils.paintBackground(context, g, c); } public void paintBorder(SynthContext context, Graphics g, int x, diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,7 +35,7 @@ import java.util.Arrays; import java.util.ArrayList; import sun.swing.plaf.synth.SynthUI; - +import sun.swing.MenuItemLayoutHelper; /** * Synth's MenuUI. @@ -86,7 +86,7 @@ acceleratorDelimiter = style.getString(context, prefix + ".acceleratorDelimiter", "+"); - if (useCheckAndArrow()) { + if (MenuItemLayoutHelper.useCheckAndArrow(menuItem)) { checkIcon = style.getIcon(context, prefix + ".checkIcon"); arrowIcon = style.getIcon(context, prefix + ".arrowIcon"); } else { @@ -111,6 +111,16 @@ accContext.dispose(); } + public void uninstallUI(JComponent c) { + super.uninstallUI(c); + // Remove values from the parent's Client Properties. + JComponent p = MenuItemLayoutHelper.getMenuItemParent((JMenuItem) c); + if (p != null) { + p.putClientProperty( + SynthMenuItemLayoutHelper.MAX_ACC_OR_ARROW_WIDTH, null); + } + } + protected void uninstallDefaults() { SynthContext context = getContext(menuItem, ENABLED); style.uninstallDefaults(context); @@ -182,9 +192,11 @@ int defaultTextIconGap) { SynthContext context = getContext(c); SynthContext accContext = getContext(c, Region.MENU_ITEM_ACCELERATOR); - Dimension value = SynthMenuItemUI.getPreferredMenuItemSize( - context, accContext, c, checkIcon, arrowIcon, - defaultTextIconGap, acceleratorDelimiter); + Dimension value = SynthGraphicsUtils.getPreferredMenuItemSize( + context, accContext, c, checkIcon, arrowIcon, + defaultTextIconGap, acceleratorDelimiter, + MenuItemLayoutHelper.useCheckAndArrow(menuItem), + getPropertyPrefix()); context.dispose(); accContext.dispose(); return value; @@ -211,21 +223,12 @@ protected void paint(SynthContext context, Graphics g) { SynthContext accContext = getContext(menuItem, Region.MENU_ITEM_ACCELERATOR); - SynthStyle style = context.getStyle(); - Icon checkIcon; - Icon arrowIcon; - if (useCheckAndArrow()) { - // Refetch the appropriate icons for the current state - String prefix = getPropertyPrefix(); - checkIcon = style.getIcon(context, prefix + ".checkIcon"); - arrowIcon = style.getIcon(context, prefix + ".arrowIcon"); - } else { - // Not needed in this case - checkIcon = null; - arrowIcon = null; - } - SynthMenuItemUI.paint(context, accContext, g, checkIcon, arrowIcon, - acceleratorDelimiter, defaultTextIconGap); + // Refetch the appropriate check indicator for the current state + String prefix = getPropertyPrefix(); + Icon checkIcon = style.getIcon(context, prefix + ".checkIcon"); + Icon arrowIcon = style.getIcon(context, prefix + ".arrowIcon"); + SynthGraphicsUtils.paint(context, accContext, g, checkIcon, arrowIcon, + acceleratorDelimiter, defaultTextIconGap, getPropertyPrefix()); accContext.dispose(); } @@ -239,8 +242,4 @@ updateStyle((JMenu)e.getSource()); } } - - private boolean useCheckAndArrow() { - return !((JMenu)menuItem).isTopLevelMenu(); - } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java Wed Jul 05 16:42:37 2017 +0200 @@ -40,6 +40,7 @@ import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; @@ -136,7 +137,7 @@ * Array of state infos for the current style. These are pushed to the * style when is received. */ - private java.util.List _stateInfos; + private List _stateInfos; /** * Current style. @@ -151,7 +152,7 @@ /** * Bindings for the current InputMap */ - private java.util.List _inputMapBindings; + private List _inputMapBindings; /** * ID for the input map. This is cached as @@ -177,30 +178,30 @@ /** * List of ColorTypes. This is populated in startColorType. */ - private java.util.List _colorTypes; + private List _colorTypes; /** * defaultsPropertys are placed here. */ - private Map _defaultsMap; + private Map _defaultsMap; /** * List of SynthStyle.Painters that will be applied to the current style. */ - private java.util.List _stylePainters; + private List _stylePainters; /** * List of SynthStyle.Painters that will be applied to the current state. */ - private java.util.List _statePainters; + private List _statePainters; SynthParser() { _mapping = new HashMap(); - _stateInfos = new ArrayList(); - _colorTypes = new ArrayList(); - _inputMapBindings = new ArrayList(); - _stylePainters = new ArrayList(); - _statePainters = new ArrayList(); + _stateInfos = new ArrayList(); + _colorTypes = new ArrayList(); + _inputMapBindings = new ArrayList(); + _stylePainters = new ArrayList(); + _statePainters = new ArrayList(); } /** @@ -219,7 +220,7 @@ public void parse(InputStream inputStream, DefaultSynthStyleFactory factory, URL urlResourceBase, Class classResourceBase, - Map defaultsMap) + Map defaultsMap) throws ParseException, IllegalArgumentException { if (inputStream == null || factory == null || (urlResourceBase == null && classResourceBase == null)) { @@ -333,7 +334,7 @@ * type type, this will throw an exception. */ private Object lookup(String key, Class type) throws SAXException { - Object value = null; + Object value; if (_handler != null) { if ((value = _handler.lookup(key)) != null) { return checkCast(value, type); @@ -423,15 +424,12 @@ private void endStyle() throws SAXException { int size = _stylePainters.size(); if (size > 0) { - _style.setPainters((ParsedSynthStyle.PainterInfo[]) - _stylePainters.toArray(new ParsedSynthStyle. - PainterInfo[size])); + _style.setPainters(_stylePainters.toArray(new ParsedSynthStyle.PainterInfo[size])); _stylePainters.clear(); } size = _stateInfos.size(); if (size > 0) { - _style.setStateInfo((ParsedSynthStyle.StateInfo[])_stateInfos. - toArray(new ParsedSynthStyle.StateInfo[size])); + _style.setStateInfo(_stateInfos.toArray(new ParsedSynthStyle.StateInfo[size])); _stateInfos.clear(); } _style = null; @@ -501,9 +499,7 @@ private void endState() throws SAXException { int size = _statePainters.size(); if (size > 0) { - _stateInfo.setPainters((ParsedSynthStyle.PainterInfo[]) - _statePainters.toArray(new ParsedSynthStyle. - PainterInfo[size])); + _stateInfo.setPainters(_statePainters.toArray(new ParsedSynthStyle.PainterInfo[size])); _statePainters.clear(); } _stateInfo = null; @@ -684,8 +680,7 @@ int max = 0; for (int counter = _colorTypes.size() - 1; counter >= 0; counter--) { - max = Math.max(max, ((ColorType)_colorTypes.get(counter)). - getID()); + max = Math.max(max, _colorTypes.get(counter).getID()); } if (colors == null || colors.length <= max) { Color[] newColors = new Color[max + 1]; @@ -696,7 +691,7 @@ } for (int counter = _colorTypes.size() - 1; counter >= 0; counter--) { - colors[((ColorType)_colorTypes.get(counter)).getID()] = color; + colors[_colorTypes.get(counter).getID()] = color; } _stateInfo.setColors(colors); } @@ -705,7 +700,7 @@ private void startProperty(AttributeList attributes, Object property) throws SAXException { Object value = null; - Object key = null; + String key = null; // Type of the value: 0=idref, 1=boolean, 2=dimension, 3=insets, // 4=integer,5=string int iType = 0; @@ -1027,7 +1022,7 @@ } } - private void addPainterOrMerge(java.util.List painters, String method, + private void addPainterOrMerge(List painters, String method, SynthPainter painter, int direction) { ParsedSynthStyle.PainterInfo painterInfo; painterInfo = new ParsedSynthStyle.PainterInfo(method, diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,34 +58,6 @@ */ class SynthPopupMenuUI extends BasicPopupMenuUI implements PropertyChangeListener, SynthUI { - /** - * Maximum size of the text portion of the children menu items. - */ - private int maxTextWidth; - - /** - * Maximum size of the icon portion of the children menu items. - */ - private int maxIconWidth; - - /** - * Maximum size of the spacing between the text and accelerator - * portions of the children menu items. - */ - private int maxAccelSpacingWidth; - - /** - * Maximum size of the text for the accelerator portion of the children - * menu items. - */ - private int maxAcceleratorWidth; - - /* - * Maximum icon and text offsets of the children menu items. - */ - private int maxTextOffset; - private int maxIconOffset; - private SynthStyle style; public static ComponentUI createUI(JComponent x) { @@ -153,90 +125,6 @@ return SynthLookAndFeel.getComponentState(c); } - /** - * Resets the max text and accerator widths, - * text and icon offsets. - */ - void resetAlignmentHints() { - maxTextWidth = maxIconWidth - = maxAccelSpacingWidth = maxAcceleratorWidth - = maxTextOffset = maxIconOffset = 0; - } - - /** - * Adjusts the width needed to display the maximum menu item string. - * - * @param width Text width. - * @return max width - */ - int adjustTextWidth(int width) { - maxTextWidth = Math.max(maxTextWidth, width); - return maxTextWidth; - } - - /** - * Adjusts the width needed to display the maximum menu item icon. - * - * @param width Icon width. - * @return max width - */ - int adjustIconWidth(int width) { - maxIconWidth = Math.max(maxIconWidth, width); - return maxIconWidth; - } - - /** - * Adjusts the width needed to pad between the maximum menu item - * text and accelerator. - * - * @param width Spacing width. - * @return max width - */ - int adjustAccelSpacingWidth(int width) { - maxAccelSpacingWidth = Math.max(maxAccelSpacingWidth, width); - return maxAccelSpacingWidth; - } - - /** - * Adjusts the width needed to display the maximum accelerator. - * - * @param width Text width. - * @return max width - */ - int adjustAcceleratorWidth(int width) { - maxAcceleratorWidth = Math.max(maxAcceleratorWidth, width); - return maxAcceleratorWidth; - } - - /** - * Maximum size needed to display accelerators of children menu items. - */ - int getMaxAcceleratorWidth() { - return maxAcceleratorWidth; - } - - /** - * Adjusts the text offset needed to align text horizontally. - * - * @param offset Text offset - * @return max offset - */ - int adjustTextOffset(int offset) { - maxTextOffset = Math.max(maxTextOffset, offset); - return maxTextOffset; - } - - /** - * Adjusts the icon offset needed to align icons horizontally - * - * @param offset Icon offset - * @return max offset - */ - int adjustIconOffset(int offset) { - maxIconOffset = Math.max(maxIconOffset, offset); - return maxIconOffset; - } - public void update(Graphics g, JComponent c) { SynthContext context = getContext(c); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -48,13 +48,13 @@ * Keys to use for forward focus traversal when the JComponent is * managing focus. */ - private static Set managingFocusForwardTraversalKeys; + private static Set managingFocusForwardTraversalKeys; /** * Keys to use for backward focus traversal when the JComponent is * managing focus. */ - private static Set managingFocusBackwardTraversalKeys; + private static Set managingFocusBackwardTraversalKeys; /** * Style for the JSplitPane. @@ -96,7 +96,7 @@ // focus forward traversal key if (managingFocusForwardTraversalKeys==null) { - managingFocusForwardTraversalKeys = new HashSet(); + managingFocusForwardTraversalKeys = new HashSet(); managingFocusForwardTraversalKeys.add( KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)); } @@ -104,7 +104,7 @@ managingFocusForwardTraversalKeys); // focus backward traversal key if (managingFocusBackwardTraversalKeys==null) { - managingFocusBackwardTraversalKeys = new HashSet(); + managingFocusBackwardTraversalKeys = new HashSet(); managingFocusBackwardTraversalKeys.add( KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK)); } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthStyle.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthStyle.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthStyle.java Wed Jul 05 16:42:37 2017 +0200 @@ -53,7 +53,7 @@ /** * Contains the default values for certain properties. */ - private static Map DEFAULT_VALUES; + private static Map DEFAULT_VALUES; /** * Shared SynthGraphics. @@ -715,7 +715,7 @@ private static Object getDefaultValue(Object key) { synchronized(SynthStyle.class) { if (DEFAULT_VALUES == null) { - DEFAULT_VALUES = new HashMap(); + DEFAULT_VALUES = new HashMap(); populateDefaultValues(); } Object value = DEFAULT_VALUES.get(key); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -66,7 +66,7 @@ protected void installDefaults() { // Installs the text cursor on the component super.installDefaults(); - updateStyle((JTextComponent)getComponent()); + updateStyle(getComponent()); } protected void uninstallDefaults() { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -232,7 +232,7 @@ protected void installDefaults() { // Installs the text cursor on the component super.installDefaults(); - updateStyle((JTextComponent)getComponent()); + updateStyle(getComponent()); getComponent().addFocusListener(this); } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java Wed Jul 05 16:42:37 2017 +0200 @@ -390,7 +390,7 @@ } private Rectangle getDropLineRect(JTree.DropLocation loc) { - Rectangle rect = null; + Rectangle rect; TreePath path = loc.getPath(); int index = loc.getChildIndex(); boolean ltr = tree.getComponentOrientation().isLeftToRight(); @@ -523,7 +523,7 @@ // Don't paint the renderer if editing this row. boolean selected = tree.isRowSelected(row); - JTree.DropLocation dropLocation = (JTree.DropLocation)tree.getDropLocation(); + JTree.DropLocation dropLocation = tree.getDropLocation(); boolean isDrop = dropLocation != null && dropLocation.getChildIndex() == -1 && path == dropLocation.getPath(); diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/table/AbstractTableModel.java --- a/jdk/src/share/classes/javax/swing/table/AbstractTableModel.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/table/AbstractTableModel.java Wed Jul 05 16:42:37 2017 +0200 @@ -176,8 +176,7 @@ * @since 1.4 */ public TableModelListener[] getTableModelListeners() { - return (TableModelListener[])listenerList.getListeners( - TableModelListener.class); + return listenerList.getListeners(TableModelListener.class); } // diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/table/DefaultTableModel.java --- a/jdk/src/share/classes/javax/swing/table/DefaultTableModel.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/table/DefaultTableModel.java Wed Jul 05 16:42:37 2017 +0200 @@ -681,9 +681,9 @@ if (anArray == null) { return null; } - Vector v = new Vector(anArray.length); - for (int i=0; i < anArray.length; i++) { - v.addElement(anArray[i]); + Vector v = new Vector(anArray.length); + for (Object o : anArray) { + v.addElement(o); } return v; } @@ -698,9 +698,9 @@ if (anArray == null) { return null; } - Vector v = new Vector(anArray.length); - for (int i=0; i < anArray.length; i++) { - v.addElement(convertToVector(anArray[i])); + Vector v = new Vector(anArray.length); + for (Object[] o : anArray) { + v.addElement(convertToVector(o)); } return v; } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/text/AbstractDocument.java --- a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java Wed Jul 05 16:42:37 2017 +0200 @@ -123,15 +123,15 @@ if (defaultI18NProperty == null) { // determine default setting for i18n support - Object o = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + String o = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public String run() { return System.getProperty(I18NProperty); } } ); if (o != null) { - defaultI18NProperty = Boolean.valueOf((String)o); + defaultI18NProperty = Boolean.valueOf(o); } else { defaultI18NProperty = Boolean.FALSE; } @@ -163,7 +163,7 @@ */ public Dictionary getDocumentProperties() { if (documentProperties == null) { - documentProperties = new Hashtable(2); + documentProperties = new Hashtable(2); } return documentProperties; } @@ -467,8 +467,7 @@ * @since 1.4 */ public DocumentListener[] getDocumentListeners() { - return (DocumentListener[])listenerList.getListeners( - DocumentListener.class); + return listenerList.getListeners(DocumentListener.class); } /** @@ -508,8 +507,7 @@ * @since 1.4 */ public UndoableEditListener[] getUndoableEditListeners() { - return (UndoableEditListener[])listenerList.getListeners( - UndoableEditListener.class); + return listenerList.getListeners(UndoableEditListener.class); } /** @@ -610,7 +608,7 @@ DefaultDocumentEvent chng = new DefaultDocumentEvent(offs, len, DocumentEvent.EventType.REMOVE); - boolean isComposedTextElement = false; + boolean isComposedTextElement; // Check whether the position of interest is the composed text isComposedTextElement = Utilities.isComposedTextElement(this, offs); @@ -1051,7 +1049,7 @@ byte levels[] = calculateBidiLevels( firstPStart, lastPEnd ); - Vector newElements = new Vector(); + Vector newElements = new Vector(); // Calculate the first span of characters in the affected range with // the same bidi level. If this level is the same as the level of the @@ -1831,7 +1829,6 @@ } out.println("["+contentStr+"]"); } catch (BadLocationException e) { - ; } } else { @@ -2460,7 +2457,7 @@ if(nchildren == 0) return null; - Vector tempVector = new Vector(nchildren); + Vector tempVector = new Vector(nchildren); for(int counter = 0; counter < nchildren; counter++) tempVector.addElement(children[counter]); @@ -2749,7 +2746,7 @@ // if the number of changes gets too great, start using // a hashtable for to locate the change for a given element. if ((changeLookup == null) && (edits.size() > 10)) { - changeLookup = new Hashtable(); + changeLookup = new Hashtable(); int n = edits.size(); for (int i = 0; i < n; i++) { Object o = edits.elementAt(i); @@ -2918,7 +2915,7 @@ */ public DocumentEvent.ElementChange getChange(Element elem) { if (changeLookup != null) { - return (DocumentEvent.ElementChange) changeLookup.get(elem); + return changeLookup.get(elem); } int n = edits.size(); for (int i = 0; i < n; i++) { @@ -2937,7 +2934,7 @@ private int offset; private int length; - private Hashtable changeLookup; + private Hashtable changeLookup; private DocumentEvent.EventType type; } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/text/AsyncBoxView.java --- a/jdk/src/share/classes/javax/swing/text/AsyncBoxView.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/text/AsyncBoxView.java Wed Jul 05 16:42:37 2017 +0200 @@ -25,6 +25,7 @@ package javax.swing.text; import java.util.*; +import java.util.List; import java.awt.*; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; @@ -58,7 +59,7 @@ */ public AsyncBoxView(Element elem, int axis) { super(elem); - stats = new ArrayList(); + stats = new ArrayList(); this.axis = axis; locator = new ChildLocator(); flushTask = new FlushTask(); @@ -197,7 +198,7 @@ protected ChildState getChildState(int index) { synchronized(stats) { if ((index >= 0) && (index < stats.size())) { - return (ChildState) stats.get(index); + return stats.get(index); } return null; } @@ -357,7 +358,7 @@ synchronized(stats) { // remove the replaced state records for (int i = 0; i < length; i++) { - ChildState cs = (ChildState)stats.remove(offset); + ChildState cs = stats.remove(offset); float csSpan = cs.getMajorSpan(); cs.getChildView().setParent(null); @@ -863,7 +864,7 @@ /** * The children and their layout statistics. */ - java.util.List stats; + List stats; /** * Current span along the major axis. This @@ -1110,7 +1111,7 @@ */ int updateChildOffsets(float targetOffset) { int n = getViewCount(); - int targetIndex = n - 1;; + int targetIndex = n - 1; int pos = lastValidOffset.getChildView().getStartOffset(); int startIndex = getViewIndex(pos, Position.Bias.Forward); float start = lastValidOffset.getMajorOffset(); @@ -1394,7 +1395,6 @@ private float min; private float pref; private float max; - private float align; private boolean minorValid; // major axis diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/text/ComponentView.java --- a/jdk/src/share/classes/javax/swing/text/ComponentView.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/text/ComponentView.java Wed Jul 05 16:42:37 2017 +0200 @@ -27,6 +27,7 @@ import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; +import java.util.Set; import javax.swing.SwingUtilities; import javax.swing.event.*; @@ -434,7 +435,7 @@ /** * Shows or hides this component depending on the value of parameter * b. - * @param b If true, shows this component; + * @param b If true, shows this component; * otherwise, hides this component. * @see #isVisible * @since JDK1.1 @@ -480,7 +481,7 @@ return yalign; } - public java.util.Set getFocusTraversalKeys(int id) { + public Set getFocusTraversalKeys(int id) { return KeyboardFocusManager.getCurrentKeyboardFocusManager(). getDefaultFocusTraversalKeys(id); } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/text/DefaultCaret.java --- a/jdk/src/share/classes/javax/swing/text/DefaultCaret.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/text/DefaultCaret.java Wed Jul 05 16:42:37 2017 +0200 @@ -774,8 +774,7 @@ * @since 1.4 */ public ChangeListener[] getChangeListeners() { - return (ChangeListener[])listenerList.getListeners( - ChangeListener.class); + return listenerList.getListeners(ChangeListener.class); } /** @@ -1330,7 +1329,7 @@ if (this.dot != this.mark && component != null) { Clipboard clip = getSystemSelection(); if (clip != null) { - String selectedText = null; + String selectedText; if (component instanceof JPasswordField && component.getClientProperty("JPasswordField.cutCopyAllowed") != Boolean.TRUE) { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/text/DefaultFormatter.java --- a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java Wed Jul 05 16:42:37 2017 +0200 @@ -68,7 +68,7 @@ private boolean commitOnEdit; /** Class used to create new instances. */ - private Class valueClass; + private Class valueClass; /** NavigationFilter that forwards calls back to DefaultFormatter. */ private NavigationFilter navigationFilter; @@ -231,7 +231,7 @@ * @return Object representation of text */ public Object stringToValue(String string) throws ParseException { - Class vc = getValueClass(); + Class vc = getValueClass(); JFormattedTextField ftf = getFormattedTextField(); if (vc == null && ftf != null) { diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/text/DefaultHighlighter.java --- a/jdk/src/share/classes/javax/swing/text/DefaultHighlighter.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/text/DefaultHighlighter.java Wed Jul 05 16:42:37 2017 +0200 @@ -56,7 +56,7 @@ // PENDING(prinz) - should cull ranges not visible int len = highlights.size(); for (int i = 0; i < len; i++) { - HighlightInfo info = (HighlightInfo) highlights.elementAt(i); + HighlightInfo info = highlights.elementAt(i); if (!(info instanceof LayeredHighlightInfo)) { // Avoid allocing unless we need it. Rectangle a = component.getBounds(); @@ -66,7 +66,7 @@ a.width -= insets.left + insets.right; a.height -= insets.top + insets.bottom; for (; i < len; i++) { - info = (HighlightInfo)highlights.elementAt(i); + info = highlights.elementAt(i); if (!(info instanceof LayeredHighlightInfo)) { Highlighter.HighlightPainter p = info.getPainter(); p.paint(g, info.getStartOffset(), info.getEndOffset(), @@ -159,7 +159,7 @@ int p0 = -1; int p1 = -1; for (int i = 0; i < len; i++) { - HighlightInfo hi = (HighlightInfo)highlights.elementAt(i); + HighlightInfo hi = highlights.elementAt(i); if (hi instanceof LayeredHighlightInfo) { LayeredHighlightInfo info = (LayeredHighlightInfo)hi; minX = Math.min(minX, info.x); @@ -195,7 +195,7 @@ int p0 = Integer.MAX_VALUE; int p1 = 0; for (int i = 0; i < len; i++) { - HighlightInfo info = (HighlightInfo) highlights.elementAt(i); + HighlightInfo info = highlights.elementAt(i); p0 = Math.min(p0, info.p0.getOffset()); p1 = Math.max(p1, info.p1.getOffset()); } @@ -282,7 +282,7 @@ Shape viewBounds, JTextComponent editor, View view) { for (int counter = highlights.size() - 1; counter >= 0; counter--) { - Object tag = highlights.elementAt(counter); + HighlightInfo tag = highlights.elementAt(counter); if (tag instanceof LayeredHighlightInfo) { LayeredHighlightInfo lhi = (LayeredHighlightInfo)tag; int start = lhi.getStartOffset(); @@ -333,7 +333,7 @@ private final static Highlighter.Highlight[] noHighlights = new Highlighter.Highlight[0]; - private Vector highlights = new Vector(); // Vector + private Vector highlights = new Vector(); private JTextComponent component; private boolean drawsLayeredHighlights; private SafeDamager safeDamager = new SafeDamager(); @@ -573,8 +573,8 @@ * call. */ class SafeDamager implements Runnable { - private Vector p0 = new Vector(10); - private Vector p1 = new Vector(10); + private Vector p0 = new Vector(10); + private Vector p1 = new Vector(10); private Document lastDoc = null; /** @@ -589,8 +589,8 @@ int len = p0.size(); for (int i = 0; i < len; i++){ mapper.damageRange(component, - ((Position)p0.get(i)).getOffset(), - ((Position)p1.get(i)).getOffset()); + p0.get(i).getOffset(), + p1.get(i).getOffset()); } } } diff -r 62c548002ecb -r 11d2418bf7c1 jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java --- a/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java Fri Oct 10 13:29:11 2008 -0700 +++ b/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java Wed Jul 05 16:42:37 2017 +0200 @@ -84,7 +84,7 @@ */ public DefaultStyledDocument(Content c, StyleContext styles) { super(c, styles); - listeningStyles = new Vector(); + listeningStyles = new Vector