changeset 5811:0d25ad745892 jdk7u12-b04

Merge
author lana
date Sun, 02 Dec 2012 23:39:15 -0800
parents a5dddd960e48 (current diff) e2d212d4211c (diff)
children fdd0d43ba0f9 a5d3d97f79c9
files
diffstat 80 files changed, 3431 insertions(+), 1083 deletions(-) [+]
line wrap: on
line diff
--- a/make/common/Defs-linux.gmk	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/common/Defs-linux.gmk	Sun Dec 02 23:39:15 2012 -0800
@@ -112,21 +112,18 @@
 # since objcopy is optional, we set ZIP_DEBUGINFO_FILES later
 
 ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
-  # Default OBJCOPY comes from GNU Binutils on Linux:
-  DEF_OBJCOPY=/usr/bin/objcopy
-  ifdef CROSS_COMPILE_ARCH
-    # don't try to generate .debuginfo files when cross compiling
-    _JUNK_ := $(shell \
-      echo >&2 "INFO: cross compiling for ARCH $(CROSS_COMPILE_ARCH)," \
-        "skipping .debuginfo generation.")
-    OBJCOPY=
+  ifndef CROSS_COMPILE_ARCH
+    # Default OBJCOPY comes from GNU Binutils on Linux:
+    DEF_OBJCOPY=/usr/bin/objcopy
   else
-    OBJCOPY=$(shell test -x $(DEF_OBJCOPY) && echo $(DEF_OBJCOPY))
-    ifneq ($(ALT_OBJCOPY),)
-      _JUNK_ := $(shell echo >&2 "INFO: ALT_OBJCOPY=$(ALT_OBJCOPY)")
-      # disable .debuginfo support by setting ALT_OBJCOPY to a non-existent path
-      OBJCOPY=$(shell test -x $(ALT_OBJCOPY) && echo $(ALT_OBJCOPY))
-    endif
+    # Assume objcopy is part of the cross-compilation toolkit
+    DEF_OBJCOPY=$(COMPILER_PATH)/objcopy
+  endif
+  OBJCOPY=$(shell test -x $(DEF_OBJCOPY) && echo $(DEF_OBJCOPY))
+  ifneq ($(ALT_OBJCOPY),)
+    _JUNK_ := $(shell echo >&2 "INFO: ALT_OBJCOPY=$(ALT_OBJCOPY)")
+    # disable .debuginfo support by setting ALT_OBJCOPY to a non-existent path
+    OBJCOPY=$(shell test -x $(ALT_OBJCOPY) && echo $(ALT_OBJCOPY))
   endif
 
   # Setting ENABLE_FULL_DEBUG_SYMBOLS=1 (and OBJCOPY) above enables the
@@ -138,7 +135,7 @@
 
   ifeq ($(OBJCOPY),)
     _JUNK_ := $(shell \
-      echo >&2 "INFO: no objcopy cmd found so cannot create .debuginfo files.")
+      echo >&2 "INFO: no objcopy cmd found so cannot create .debuginfo files. You may need to set ALT_OBJCOPY.")
     ENABLE_FULL_DEBUG_SYMBOLS=0
   else
     _JUNK_ := $(shell \
--- a/make/java/java/mapfile-vers	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/java/java/mapfile-vers	Sun Dec 02 23:39:15 2012 -0800
@@ -79,7 +79,7 @@
 		Java_java_io_FileInputStream_close0;
 		Java_java_io_FileInputStream_initIDs;
 		Java_java_io_FileInputStream_open;
-		Java_java_io_FileInputStream_read;
+		Java_java_io_FileInputStream_read0;
 		Java_java_io_FileInputStream_readBytes;
 		Java_java_io_FileInputStream_skip;
 		Java_java_io_FileOutputStream_close0;
@@ -100,12 +100,12 @@
 		Java_java_io_RandomAccessFile_initIDs;
 		Java_java_io_RandomAccessFile_length;
 		Java_java_io_RandomAccessFile_open;
-		Java_java_io_RandomAccessFile_read;
-		Java_java_io_RandomAccessFile_readBytes;
+		Java_java_io_RandomAccessFile_read0;
+		Java_java_io_RandomAccessFile_readBytes0;
 		Java_java_io_RandomAccessFile_seek;
 		Java_java_io_RandomAccessFile_setLength;
-		Java_java_io_RandomAccessFile_write;
-		Java_java_io_RandomAccessFile_writeBytes;
+		Java_java_io_RandomAccessFile_write0;
+		Java_java_io_RandomAccessFile_writeBytes0;
 		Java_java_io_UnixFileSystem_canonicalize0;
 		Java_java_io_UnixFileSystem_checkAccess;
 		Java_java_io_UnixFileSystem_createDirectory;
--- a/make/sun/javazic/tzdata/VERSION	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/VERSION	Sun Dec 02 23:39:15 2012 -0800
@@ -21,4 +21,4 @@
 # or visit www.oracle.com if you need additional information or have any
 # questions.
 #
-tzdata2012c
+tzdata2012i
--- a/make/sun/javazic/tzdata/africa	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/africa	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)africa	8.35
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
@@ -261,7 +260,7 @@
 # I received a mail from an airline which says that the daylight
 # saving time in Egypt will end in the night of 2007-09-06 to 2007-09-07.
 # From Jesper Norgaard Welen (2007-08-15): [The following agree:]
-# http://www.nentjes.info/Bill/bill5.htm 
+# http://www.nentjes.info/Bill/bill5.htm
 # http://www.timeanddate.com/worldclock/city.html?n=53
 # From Steffen Thorsen (2007-09-04): The official information...:
 # http://www.sis.gov.eg/En/EgyptOnline/Miscellaneous/000002/0207000000000000001580.htm
@@ -315,18 +314,18 @@
 # in September.
 
 # From Steffen Thorsen (2009-08-11):
-# We have been able to confirm the August change with the Egyptian Cabinet 
+# We have been able to confirm the August change with the Egyptian Cabinet
 # Information and Decision Support Center:
 # <a href="http://www.timeanddate.com/news/time/egypt-dst-ends-2009.html">
 # http://www.timeanddate.com/news/time/egypt-dst-ends-2009.html
 # </a>
-# 
+#
 # The Middle East News Agency
 # <a href="http://www.mena.org.eg/index.aspx">
 # http://www.mena.org.eg/index.aspx
 # </a>
 # also reports "Egypt starts winter time on August 21"
-# today in article numbered "71, 11/08/2009 12:25 GMT." 
+# today in article numbered "71, 11/08/2009 12:25 GMT."
 # Only the title above is available without a subscription to their service,
 # and can be found by searching for "winter" in their search engine
 # (at least today).
@@ -505,7 +504,7 @@
 # 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 
+# 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
 
@@ -529,12 +528,12 @@
 # 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 
+#
+# 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):
@@ -593,7 +592,7 @@
 # </a>
 
 # From Arthur David Olson (2009-07-11):
-# The "mauritius-dst-will-not-repeat" wrapup includes this: 
+# The "mauritius-dst-will-not-repeat" wrapup includes this:
 # "The trial ended on March 29, 2009, when the clocks moved back by one hour
 # at 2am (or 02:00) local time..."
 
@@ -687,8 +686,8 @@
 # XXX--guess that it is only Morocco for now; guess only 2008 for now.
 
 # From Steffen Thorsen (2008-08-27):
-# Morocco will change the clocks back on the midnight between August 31 
-# and September 1. They originally planned to observe DST to near the end 
+# Morocco will change the clocks back on the midnight between August 31
+# and September 1. They originally planned to observe DST to near the end
 # of September:
 #
 # One article about it (in French):
@@ -822,6 +821,23 @@
 # "...&agrave; partir du dernier dimance d'avril et non fins mars,
 # comme annonc&eacute; pr&eacute;c&eacute;demment."
 
+# From Milamber Space Network (2012-07-17):
+# The official return to GMT is announced by the Moroccan government:
+# <a href="http://www.mmsp.gov.ma/fr/actualites.aspx?id=288">
+# http://www.mmsp.gov.ma/fr/actualites.aspx?id=288 [in French]
+# </a>
+#
+# Google translation, lightly edited:
+# Back to the standard time of the Kingdom (GMT)
+# Pursuant to Decree No. 2-12-126 issued on 26 Jumada (I) 1433 (April 18,
+# 2012) and in accordance with the order of Mr. President of the
+# Government No. 3-47-12 issued on 24 Sha'ban (11 July 2012), the Ministry
+# of Public Service and Administration Modernization announces the return
+# of the legal time of the Kingdom (GMT) from Friday, July 20, 2012 until
+# Monday, August 20, 2012.  So the time will be delayed by 60 minutes from
+# 3:00 am Friday, July 20, 2012 and will again be advanced by 60 minutes
+# August 20, 2012 from 2:00 am.
+
 # RULE	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 
 Rule	Morocco	1939	only	-	Sep	12	 0:00	1:00	S
@@ -849,6 +865,8 @@
 Rule	Morocco	2011	only	-	Jul	 31	 0	0	-
 Rule	Morocco	2012	max	-	Apr	 lastSun 2:00	1:00	S
 Rule	Morocco	2012	max	-	Sep	 lastSun 3:00	0	-
+Rule	Morocco	2012	only	-	Jul	 20	 3:00	0	-
+Rule	Morocco	2012	only	-	Aug	 20	 2:00	1:00	S
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Africa/Casablanca	-0:30:20 -	LMT	1913 Oct 26
@@ -877,7 +895,7 @@
 # Forecasting Riaan van Zyl explained that the far eastern parts of
 # the country are close to 40 minutes earlier in sunrise than the rest
 # of the country.
-# 
+#
 # From Paul Eggert (2007-03-31):
 # Apparently the Caprivi Strip informally observes Botswana time, but
 # we have no details.  In the meantime people there can use Africa/Gaborone.
--- a/make/sun/javazic/tzdata/antarctica	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/antarctica	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)antarctica	8.10
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
--- a/make/sun/javazic/tzdata/asia	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/asia	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)asia	8.73
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
@@ -125,7 +124,7 @@
 # From Alexander Krivenyshev (2012-02-10):
 # According to News Armenia, on Feb 9, 2012,
 # http://newsarmenia.ru/society/20120209/42609695.html
-# 
+#
 # The Armenia National Assembly adopted final reading of Amendments to the
 # Law "On procedure of calculation time on the territory of the Republic of
 # Armenia" according to which Armenia [is] abolishing Daylight Saving Time.
@@ -205,15 +204,15 @@
 # </a>
 
 # From A. N. M. Kamrus Saadat (2009-06-15):
-# Finally we've got the official mail regarding DST start time where DST start 
-# time is mentioned as Jun 19 2009, 23:00 from BTRC (Bangladesh 
-# Telecommunication Regulatory Commission). 
+# Finally we've got the official mail regarding DST start time where DST start
+# time is mentioned as Jun 19 2009, 23:00 from BTRC (Bangladesh
+# Telecommunication Regulatory Commission).
 #
 # No DST end date has been announced yet.
 
 # From Alexander Krivenyshev (2009-09-25):
-# Bangladesh won't go back to Standard Time from October 1, 2009, 
-# instead it will continue DST measure till the cabinet makes a fresh decision. 
+# Bangladesh won't go back to Standard Time from October 1, 2009,
+# instead it will continue DST measure till the cabinet makes a fresh decision.
 #
 # Following report by same newspaper-"The Daily Star Friday":
 # "DST change awaits cabinet decision-Clock won't go back by 1-hr from Oct 1"
@@ -227,8 +226,8 @@
 
 # From Steffen Thorsen (2009-10-13):
 # IANS (Indo-Asian News Service) now reports:
-# Bangladesh has decided that the clock advanced by an hour to make 
-# maximum use of daylight hours as an energy saving measure would 
+# Bangladesh has decided that the clock advanced by an hour to make
+# maximum use of daylight hours as an energy saving measure would
 # "continue for an indefinite period."
 #
 # One of many places where it is published:
@@ -256,7 +255,7 @@
 
 # From Alexander Krivenyshev (2010-03-22):
 # According to Bangladesh newspaper "The Daily Star,"
-# Cabinet cancels Daylight Saving Time 
+# Cabinet cancels Daylight Saving Time
 # <a href="http://www.thedailystar.net/newDesign/latest_news.php?nid=22817">
 # http://www.thedailystar.net/newDesign/latest_news.php?nid=22817
 # </a>
@@ -384,11 +383,11 @@
 # 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 
+# 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):
@@ -525,7 +524,7 @@
 # as of 2009-10-28:
 # Year        Period
 # 1941        1 Apr to 30 Sep
-# 1942        Whole year 
+# 1942        Whole year
 # 1943        Whole year
 # 1944        Whole year
 # 1945        Whole year
@@ -616,16 +615,16 @@
 # From Arthur David Olson (2010-04-07):
 # Here's Google's translation of the table at the bottom of the "summert.htm" page:
 # Decade 	                                                    Name                      Start and end date
-# Republic of China 34 years to 40 years (AD 1945-1951 years) Summer Time               May 1 to September 30 
-# 41 years of the Republic of China (AD 1952)                 Daylight Saving Time      March 1 to October 31 
-# Republic of China 42 years to 43 years (AD 1953-1954 years) Daylight Saving Time      April 1 to October 31 
-# In the 44 years to 45 years (AD 1955-1956 years)            Daylight Saving Time      April 1 to September 30 
-# Republic of China 46 years to 48 years (AD 1957-1959)       Summer Time               April 1 to September 30 
-# Republic of China 49 years to 50 years (AD 1960-1961)       Summer Time               June 1 to September 30 
-# Republic of China 51 years to 62 years (AD 1962-1973 years) Stop Summer Time 
-# Republic of China 63 years to 64 years (1974-1975 AD)       Daylight Saving Time      April 1 to September 30 
-# Republic of China 65 years to 67 years (1976-1978 AD)       Stop Daylight Saving Time 
-# Republic of China 68 years (AD 1979)                        Daylight Saving Time      July 1 to September 30 
+# Republic of China 34 years to 40 years (AD 1945-1951 years) Summer Time               May 1 to September 30
+# 41 years of the Republic of China (AD 1952)                 Daylight Saving Time      March 1 to October 31
+# Republic of China 42 years to 43 years (AD 1953-1954 years) Daylight Saving Time      April 1 to October 31
+# In the 44 years to 45 years (AD 1955-1956 years)            Daylight Saving Time      April 1 to September 30
+# Republic of China 46 years to 48 years (AD 1957-1959)       Summer Time               April 1 to September 30
+# Republic of China 49 years to 50 years (AD 1960-1961)       Summer Time               June 1 to September 30
+# Republic of China 51 years to 62 years (AD 1962-1973 years) Stop Summer Time
+# Republic of China 63 years to 64 years (1974-1975 AD)       Daylight Saving Time      April 1 to September 30
+# Republic of China 65 years to 67 years (1976-1978 AD)       Stop Daylight Saving Time
+# Republic of China 68 years (AD 1979)                        Daylight Saving Time      July 1 to September 30
 # Republic of China since 69 years (AD 1980)                  Stop Daylight Saving Time
 
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
@@ -1194,15 +1193,15 @@
 #
 #	ftp://ftp.cs.huji.ac.il/pub/tz/announcements/2005+beyond.ps
 
-# From Paul Eggert (2005-02-22):
+# From Paul Eggert (2012-10-26):
 # I used Ephraim Silverberg's dst-israel.el program
 # <ftp://ftp.cs.huji.ac.il/pub/tz/software/dst-israel.el> (2005-02-20)
 # along with Ed Reingold's cal-hebrew in GNU Emacs 21.4,
-# to generate the transitions in this list.
+# to generate the transitions from 2005 through 2012.
 # (I replaced "lastFri" with "Fri>=26" by hand.)
-# The spring transitions below all correspond to the following Rule:
+# The spring transitions all correspond to the following Rule:
 #
-# Rule	Zion	2005	max	-	Mar	Fri>=26	2:00	1:00	D
+# Rule	Zion	2005	2012	-	Mar	Fri>=26	2:00	1:00	D
 #
 # but older zic implementations (e.g., Solaris 8) do not support
 # "Fri>=26" to mean April 1 in years like 2005, so for now we list the
@@ -1219,39 +1218,36 @@
 Rule	Zion	2010	only	-	Sep	12	2:00	0	S
 Rule	Zion	2011	only	-	Apr	 1	2:00	1:00	D
 Rule	Zion	2011	only	-	Oct	 2	2:00	0	S
-Rule	Zion	2012	2015	-	Mar	Fri>=26	2:00	1:00	D
+Rule	Zion	2012	only	-	Mar	Fri>=26	2:00	1:00	D
 Rule	Zion	2012	only	-	Sep	23	2:00	0	S
-Rule	Zion	2013	only	-	Sep	 8	2:00	0	S
-Rule	Zion	2014	only	-	Sep	28	2:00	0	S
-Rule	Zion	2015	only	-	Sep	20	2:00	0	S
-Rule	Zion	2016	only	-	Apr	 1	2:00	1:00	D
-Rule	Zion	2016	only	-	Oct	 9	2:00	0	S
-Rule	Zion	2017	2021	-	Mar	Fri>=26	2:00	1:00	D
-Rule	Zion	2017	only	-	Sep	24	2:00	0	S
-Rule	Zion	2018	only	-	Sep	16	2:00	0	S
-Rule	Zion	2019	only	-	Oct	 6	2:00	0	S
-Rule	Zion	2020	only	-	Sep	27	2:00	0	S
-Rule	Zion	2021	only	-	Sep	12	2:00	0	S
-Rule	Zion	2022	only	-	Apr	 1	2:00	1:00	D
-Rule	Zion	2022	only	-	Oct	 2	2:00	0	S
-Rule	Zion	2023	2032	-	Mar	Fri>=26	2:00	1:00	D
-Rule	Zion	2023	only	-	Sep	24	2:00	0	S
-Rule	Zion	2024	only	-	Oct	 6	2:00	0	S
-Rule	Zion	2025	only	-	Sep	28	2:00	0	S
-Rule	Zion	2026	only	-	Sep	20	2:00	0	S
-Rule	Zion	2027	only	-	Oct	10	2:00	0	S
-Rule	Zion	2028	only	-	Sep	24	2:00	0	S
-Rule	Zion	2029	only	-	Sep	16	2:00	0	S
-Rule	Zion	2030	only	-	Oct	 6	2:00	0	S
-Rule	Zion	2031	only	-	Sep	21	2:00	0	S
-Rule	Zion	2032	only	-	Sep	12	2:00	0	S
-Rule	Zion	2033	only	-	Apr	 1	2:00	1:00	D
-Rule	Zion	2033	only	-	Oct	 2	2:00	0	S
-Rule	Zion	2034	2037	-	Mar	Fri>=26	2:00	1:00	D
-Rule	Zion	2034	only	-	Sep	17	2:00	0	S
-Rule	Zion	2035	only	-	Oct	 7	2:00	0	S
-Rule	Zion	2036	only	-	Sep	28	2:00	0	S
-Rule	Zion	2037	only	-	Sep	13	2:00	0	S
+
+# From Ephraim Silverberg (2012-10-18):
+
+# Yesterday, the Interior Ministry Committee, after more than a year
+# past, approved sending the proposed June 2011 changes to the Time
+# Decree Law back to the Knesset for second and third (final) votes
+# before the upcoming elections on Jan. 22, 2013.  Hence, although the
+# changes are not yet law, they are expected to be so before February 2013.
+#
+# As of 2013, DST starts at 02:00 on the Friday before the last Sunday in March.
+# DST ends at 02:00 on the first Sunday after October 1, unless it occurs on the
+# second day of the Jewish Rosh Hashana holiday, in which case DST ends a day
+# later (i.e. at 02:00 the first Monday after October 2).
+# [Rosh Hashana holidays are factored in until 2100.]
+
+# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
+Rule	Zion	2013	max	-	Mar	Fri>=23	2:00	1:00	D
+Rule	Zion	2013	2026	-	Oct	Sun>=2	2:00	0	S
+Rule	Zion	2027	only	-	Oct	Mon>=3	2:00	0	S
+Rule	Zion	2028	max	-	Oct	Sun>=2	2:00	0	S
+# The following rules are commented out for now, as they break older
+# versions of zic that support only signed 32-bit timestamps, i.e.,
+# through 2038-01-19 03:14:07 UTC.
+#Rule	Zion	2028	2053	-	Oct	Sun>=2	2:00	0	S
+#Rule	Zion	2054	only	-	Oct	Mon>=3	2:00	0	S
+#Rule	Zion	2055	2080	-	Oct	Sun>=2	2:00	0	S
+#Rule	Zion	2081	only	-	Oct	Mon>=3	2:00	0	S
+#Rule	Zion	2082	max	-	Oct	Sun>=2	2:00	0	S
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Jerusalem	2:20:56 -	LMT	1880
@@ -1386,6 +1382,16 @@
 # From Arthur David Olson (2009-04-06):
 # We still have Jordan switching to DST on Thursdays in 2000 and 2001.
 
+# From Steffen Thorsen (2012-10-25):
+# Yesterday the government in Jordan announced that they will not
+# switch back to standard time this winter, so the will stay on DST
+# until about the same time next year (at least).
+# http://www.petra.gov.jo/Public_News/Nws_NewsDetails.aspx?NewsID=88950
+#
+# From Paul Eggert (2012-10-25):
+# For now, assume this is just a one-year measure.  If it becomes
+# permanent, we should move Jordan from EET to AST effective tomorrow.
+
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Jordan	1973	only	-	Jun	6	0:00	1:00	S
 Rule	Jordan	1973	1975	-	Oct	1	0:00	0	-
@@ -1414,7 +1420,8 @@
 Rule	Jordan	2003	only	-	Oct	24	0:00s	0	-
 Rule	Jordan	2004	only	-	Oct	15	0:00s	0	-
 Rule	Jordan	2005	only	-	Sep	lastFri	0:00s	0	-
-Rule	Jordan	2006	max	-	Oct	lastFri	0:00s	0	-
+Rule	Jordan	2006	2011	-	Oct	lastFri	0:00s	0	-
+Rule	Jordan	2013	max	-	Oct	lastFri	0:00s	0	-
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Amman	2:23:44 -	LMT	1931
 			2:00	Jordan	EE%sT
@@ -1859,15 +1866,15 @@
 # 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 
+#
+# 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. 
+#
+# "... 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.
 # ...."
-# 
+#
 # <a href="http://www.worldtimezone.net/dst_news/dst_news_pakistan01.html">
 # http://www.worldtimezone.net/dst_news/dst_news_pakistan01.html
 # </a>
@@ -1927,7 +1934,7 @@
 # Government has decided to restore the previous time by moving the
 # clocks backward by one hour from October 1. A formal announcement to
 # this effect will be made after the Prime Minister grants approval in
-# this regard." 
+# this regard."
 # <a href="http://www.thenews.com.pk/updates.asp?id=87168">
 # http://www.thenews.com.pk/updates.asp?id=87168
 # </a>
@@ -2223,7 +2230,7 @@
 # <a href="http://www.maannews.net/eng/ViewDetails.aspx?ID=306795">
 # http://www.maannews.net/eng/ViewDetails.aspx?ID=306795
 # </a>
-# the clocks were set back one hour at 2010-08-11 00:00:00 local time in 
+# the clocks were set back one hour at 2010-08-11 00:00:00 local time in
 # Gaza and the West Bank.
 # Some more background info:
 # <a href="http://www.timeanddate.com/news/time/westbank-gaza-end-dst-2010.html">
@@ -2262,7 +2269,7 @@
 # The rules for Egypt are stolen from the `africa' file.
 
 # From Steffen Thorsen (2011-09-30):
-# West Bank did end Daylight Saving Time this morning/midnight (2011-09-30 
+# West Bank did end Daylight Saving Time this morning/midnight (2011-09-30
 # 00:00).
 # So West Bank and Gaza now have the same time again.
 #
@@ -2317,6 +2324,8 @@
 
 # From Arthur David Olson (2011-09-20):
 # 2011 transitions per http://www.timeanddate.com as of 2011-09-20.
+# From Paul Eggert (2012-10-12):
+# 2012 transitions per http://www.timeanddate.com as of 2012-10-12.
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Gaza	2:17:52	-	LMT	1900 Oct
@@ -2327,7 +2336,7 @@
 			2:00 Palestine	EE%sT	2011 Apr  2 12:01
 			2:00	1:00	EEST	2011 Aug  1
 			2:00	-	EET	2012 Mar 30
-			2:00	1:00	EEST	2012 Sep 28
+			2:00	1:00	EEST	2012 Sep 21 1:00
 			2:00	-	EET
 
 Zone	Asia/Hebron	2:20:23	-	LMT	1900 Oct
@@ -2342,7 +2351,7 @@
 			2:00	-	EET	2011 Aug 30
 			2:00	1:00	EEST	2011 Sep 30 3:00
 			2:00	-	EET	2012 Mar 30
-			2:00	1:00	EEST	2012 Sep 28 3:00
+			2:00	1:00	EEST	2012 Sep 21 1:00
 			2:00	-	EET
 
 # Paracel Is
@@ -2536,19 +2545,19 @@
 # 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 
+# 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	-
 
@@ -2614,8 +2623,8 @@
 # </a>
 
 # From Steffen Thorsen (2009-10-27):
-# The Syrian Arab News Network on 2009-09-29 reported that Syria will 
-# revert back to winter (standard) time on midnight between Thursday 
+# The Syrian Arab News Network on 2009-09-29 reported that Syria will
+# revert back to winter (standard) time on midnight between Thursday
 # 2009-10-29 and Friday 2009-10-30:
 # <a href="http://www.sana.sy/ara/2/2009/09/29/247012.htm">
 # http://www.sana.sy/ara/2/2009/09/29/247012.htm (Arabic)
--- a/make/sun/javazic/tzdata/australasia	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/australasia	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)australasia	8.30
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
@@ -307,9 +306,9 @@
 # </a>
 
 # From Alexander Krivenyshev (2010-10-24):
-# According to Radio Fiji and Fiji Times online, Fiji will end DST 3 
+# According to Radio Fiji and Fiji Times online, Fiji will end DST 3
 # weeks earlier than expected - on March 6, 2011, not March 27, 2011...
-# Here is confirmation from Government of the Republic of the Fiji Islands, 
+# Here is confirmation from Government of the Republic of the Fiji Islands,
 # Ministry of Information (fiji.gov.fj) web site:
 # <a href="http://www.fiji.gov.fj/index.php?option=com_content&view=article&id=2608:daylight-savings&catid=71:press-releases&Itemid=155">
 # http://www.fiji.gov.fj/index.php?option=com_content&view=article&id=2608:daylight-savings&catid=71:press-releases&Itemid=155
@@ -320,15 +319,15 @@
 # </a>
 
 # From Steffen Thorsen (2011-10-03):
-# Now the dates have been confirmed, and at least our start date 
+# Now the dates have been confirmed, and at least our start date
 # assumption was correct (end date was one week wrong).
 #
 # <a href="http://www.fiji.gov.fj/index.php?option=com_content&view=article&id=4966:daylight-saving-starts-in-fiji&catid=71:press-releases&Itemid=155">
 # www.fiji.gov.fj/index.php?option=com_content&view=article&id=4966:daylight-saving-starts-in-fiji&catid=71:press-releases&Itemid=155
 # </a>
 # which says
-# Members of the public are reminded to change their time to one hour in 
-# advance at 2am to 3am on October 23, 2011 and one hour back at 3am to 
+# Members of the public are reminded to change their time to one hour in
+# advance at 2am to 3am on October 23, 2011 and one hour back at 3am to
 # 2am on February 26 next year.
 
 # From Ken Rylander (2011-10-24)
@@ -345,15 +344,23 @@
 # The commencement of daylight saving will remain unchanged and start
 # on the  23rd of October, 2011.
 
+# From the Fiji Government Online Portal (2012-08-21) via Steffen Thorsen:
+# The Minister for Labour, Industrial Relations and Employment Mr Jone Usamate
+# today confirmed that Fiji will start daylight savings at 2 am on Sunday 21st
+# October 2012 and end at 3 am on Sunday 20th January 2013.
+# http://www.fiji.gov.fj/index.php?option=com_content&view=article&id=6702&catid=71&Itemid=155
+#
+# From Paul Eggert (2012-08-31):
+# For now, guess a pattern of the penultimate Sundays in October and January.
+
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Fiji	1998	1999	-	Nov	Sun>=1	2:00	1:00	S
 Rule	Fiji	1999	2000	-	Feb	lastSun	3:00	0	-
 Rule	Fiji	2009	only	-	Nov	29	2:00	1:00	S
 Rule	Fiji	2010	only	-	Mar	lastSun	3:00	0	-
-Rule	Fiji	2010	only	-	Oct	24	2:00	1:00	S
+Rule	Fiji	2010	max	-	Oct	Sun>=18	2:00	1:00	S
 Rule	Fiji	2011	only	-	Mar	Sun>=1	3:00	0	-
-Rule	Fiji	2011	only	-	Oct	23	2:00	1:00	S
-Rule	Fiji	2012	only	-	Jan	22	3:00	0	-
+Rule	Fiji	2012	max	-	Jan	Sun>=18	3:00	0	-
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Pacific/Fiji	11:53:40 -	LMT	1915 Oct 26	# Suva
 			12:00	Fiji	FJ%sT	# Fiji Time
@@ -582,7 +589,7 @@
 
 # From David Zuelke (2011-05-09):
 # Subject: Samoa to move timezone from east to west of international date line
-# 
+#
 # <a href="http://www.morningstar.co.uk/uk/markets/newsfeeditem.aspx?id=138501958347963">
 # http://www.morningstar.co.uk/uk/markets/newsfeeditem.aspx?id=138501958347963
 # </a>
@@ -644,6 +651,23 @@
 # Although Samoa has used Daylight Saving Time in the 2010-2011 and 2011-2012
 # seasons, there is not yet any indication that this trend will continue on
 # a regular basis. For now, we have explicitly listed the transitions below.
+#
+# From Nicky (2012-09-10):
+# Daylight Saving Time commences on Sunday 30th September 2012 and
+# ends on Sunday 7th of April 2013.
+#
+# Please find link below for more information.
+# http://www.mcil.gov.ws/mcil_publications.html
+#
+# That publication also includes dates for Summer of 2013/4 as well
+# which give the impression of a pattern in selecting dates for the
+# future, so for now, we will guess this will continue.
+
+# Western Samoa
+# Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
+Rule	WS	2012	max	-	Sep	lastSun	3:00	1	D
+Rule	WS	2012	max	-	Apr	Sun>=1	4:00	0	-
+# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Pacific/Apia	 12:33:04 -	LMT	1879 Jul  5
 			-11:26:56 -	LMT	1911
 			-11:30	-	SAMT	1950		# Samoa Time
@@ -651,8 +675,8 @@
 			-11:00	1:00	WSDT	2011 Apr 2 4:00
 			-11:00	-	WST	2011 Sep 24 3:00
 			-11:00	1:00	WSDT	2011 Dec 30
-			 13:00	1:00	WSDT	2012 Apr 1 4:00
-			 13:00	-	WST
+			 13:00	1:00	WSDT	2012 Apr Sun>=1 4:00
+			 13:00	WS	WS%sT
 
 # Solomon Is
 # excludes Bougainville, for which see Papua New Guinea
@@ -664,25 +688,25 @@
 #
 # From Gwillim Law (2011-12-29)
 # A correspondent informed me that Tokelau, like Samoa, will be skipping
-# December 31 this year, thereby changing its time zone from UTC-10 to
-# UTC+14. When I tried to verify this statement, I found a confirming
-# article in Time magazine online
-# <a href="http://www.time.com/time/world/article/0,8599,2103243,00.html">
-# (http://www.time.com/time/world/article/0,8599,2103243,00.html).
-# </a>
+# December 31 this year ...
 #
-# From Jonathan Leffler (2011-12-29)
-# Information from the BBC to the same effect:
-# <a href="http://www.bbc.co.uk/news/world-asia-16351377">
-# http://www.bbc.co.uk/news/world-asia-16351377
-# </a>
+# From Steffen Thorsen (2012-07-25)
+# ... we double checked by calling hotels and offices based in Tokelau asking
+# about the time there, and they all told a time that agrees with UTC+13....
+# Shanks says UTC-10 from 1901 [but] ... there is a good chance the change
+# actually was to UTC-11 back then.
 #
-# Patch supplied by Tim Parenti (2011-12-29)
+# From Paul Eggert (2012-07-25)
+# A Google Books snippet of Appendix to the Journals of the House of
+# Representatives of New Zealand, Session 1948,
+# <http://books.google.com/books?id=ZaVCAQAAIAAJ>, page 65, says Tokelau
+# was "11 hours slow on G.M.T."  Go with Thorsen and assume Shanks & Pottenger
+# are off by an hour starting in 1901.
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Pacific/Fakaofo	-11:24:56 -	LMT	1901
-			-10:00	-	TKT 2011 Dec 30	# Tokelau Time
-			14:00	-	TKT
+			-11:00	-	TKT 2011 Dec 30	# Tokelau Time
+			13:00	-	TKT
 
 # Tonga
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
@@ -1363,22 +1387,22 @@
 # See "southeast Australia" above for 2008 and later.
 
 # From Steffen Thorsen (2009-04-28):
-# According to the official press release, South Australia's extended daylight 
-# saving period will continue with the same rules as used during the 2008-2009 
+# According to the official press release, South Australia's extended daylight
+# saving period will continue with the same rules as used during the 2008-2009
 # summer (southern hemisphere).
-# 
+#
 # From
 # <a href="http://www.safework.sa.gov.au/uploaded_files/DaylightDatesSet.pdf">
 # http://www.safework.sa.gov.au/uploaded_files/DaylightDatesSet.pdf
 # </a>
-# The extended daylight saving period that South Australia has been trialling 
+# The extended daylight saving period that South Australia has been trialling
 # for over the last year is now set to be ongoing.
-# Daylight saving will continue to start on the first Sunday in October each 
+# Daylight saving will continue to start on the first Sunday in October each
 # year and finish on the first Sunday in April the following year.
-# Industrial Relations Minister, Paul Caica, says this provides South Australia 
-# with a consistent half hour time difference with NSW, Victoria, Tasmania and 
+# Industrial Relations Minister, Paul Caica, says this provides South Australia
+# with a consistent half hour time difference with NSW, Victoria, Tasmania and
 # the ACT for all 52 weeks of the year...
-# 
+#
 # We have a wrap-up here:
 # <a href="http://www.timeanddate.com/news/time/south-australia-extends-dst.html">
 # http://www.timeanddate.com/news/time/south-australia-extends-dst.html
--- a/make/sun/javazic/tzdata/backward	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/backward	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)backward	8.11
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
--- a/make/sun/javazic/tzdata/etcetera	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/etcetera	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)etcetera	8.3
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
--- a/make/sun/javazic/tzdata/europe	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/europe	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)europe	8.41
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
@@ -598,12 +597,12 @@
 # According to Kremlin press service, Russian President Dmitry Medvedev
 # signed a federal law "On calculation of time" on June 9, 2011.
 # According to the law Russia is abolishing daylight saving time.
-# 
-# Medvedev signed a law "On the Calculation of Time" (in russian): 
+#
+# Medvedev signed a law "On the Calculation of Time" (in russian):
 # <a href="http://bmockbe.ru/events/?ID=7583">
 # http://bmockbe.ru/events/?ID=7583
 # </a>
-# 
+#
 # Medvedev signed a law on the calculation of the time (in russian):
 # <a href="http://www.regnum.ru/news/polit/1413906.html">
 # http://www.regnum.ru/news/polit/1413906.html
@@ -1711,7 +1710,7 @@
 # From Alexander Krivenyshev (2011-10-26)
 # NO need to divide Moldova into two timezones at this point.
 # As of today, Transnistria (Pridnestrovie)- Tiraspol reversed its own
-# decision to abolish DST this winter. 
+# decision to abolish DST this winter.
 # Following Moldova and neighboring Ukraine- Transnistria (Pridnestrovie)-
 # Tiraspol will go back to winter time on October 30, 2011.
 # News from Moldova (in russian):
@@ -2601,11 +2600,11 @@
 # http://www.alomaliye.com/bkk_2002_3769.htm
 
 # From G&ouml;kdeniz Karada&#x011f; (2011-03-10):
-# 
+#
 # According to the articles linked below, Turkey will change into summer
 # time zone (GMT+3) on March 28, 2011 at 3:00 a.m. instead of March 27.
 # This change is due to a nationwide exam on 27th.
-# 
+#
 # <a href="http://www.worldbulletin.net/?aType=haber&ArticleID=70872">
 # http://www.worldbulletin.net/?aType=haber&ArticleID=70872
 # </a>
@@ -2722,7 +2721,7 @@
 # time this year after all.
 #
 # From Udo Schwedt (2011-10-18):
-# As far as I understand, the recent change to the Ukranian time zone 
+# As far as I understand, the recent change to the Ukranian time zone
 # (Europe/Kiev) to introduce permanent daylight saving time (similar
 # to Russia) was reverted today:
 #
--- a/make/sun/javazic/tzdata/factory	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/factory	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)factory	8.2
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
--- a/make/sun/javazic/tzdata/iso3166.tab	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/iso3166.tab	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)iso3166.tab	8.11
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 # ISO 3166 alpha-2 country codes
--- a/make/sun/javazic/tzdata/leapseconds	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/leapseconds	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)leapseconds	8.13
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
@@ -101,8 +100,8 @@
 #
 #
 # A positive leap second will be introduced at the end of June 2012.
-# The sequence of dates of the UTC second markers will be:		
-# 		
+# The sequence of dates of the UTC second markers will be:
+#
 #                          2012 June 30,     23h 59m 59s
 #                          2012 June 30,     23h 59m 60s
 #                          2012 July  1,      0h  0m  0s
@@ -119,6 +118,6 @@
 #
 #
 # Daniel GAMBIS
-# Head		
+# Head
 # Earth Orientation Center of IERS
 # Observatoire de Paris, France
--- a/make/sun/javazic/tzdata/northamerica	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/northamerica	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)northamerica	8.54
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
@@ -502,7 +501,7 @@
 			 -8:00	US	P%sT	1946
 			 -8:00	-	PST	1969
 			 -8:00	US	P%sT	1980 Apr 27 2:00
-			 -9:00	US	Y%sT	1980 Oct 26 2:00	
+			 -9:00	US	Y%sT	1980 Oct 26 2:00
 			 -8:00	US	P%sT	1983 Oct 30 2:00
 			 -9:00	US	Y%sT	1983 Nov 30
 			 -9:00	US	AK%sT
@@ -1867,7 +1866,7 @@
 # Here is a summary of the three clock change events in Creston's history:
 # 1. 1884 or 1885: adoption of Mountain Standard Time (GMT-7)
 # Exact date unknown
-# 2. Oct 1916: switch to Pacific Standard Time (GMT-8) 
+# 2. Oct 1916: switch to Pacific Standard Time (GMT-8)
 # Exact date in October unknown;  Sunday October 1 is a reasonable guess.
 # 3. June 1918: switch to Pacific Daylight Time (GMT-7)
 # Exact date in June unknown; Sunday June 2 is a reasonable guess.
@@ -2697,20 +2696,20 @@
 # 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 
+# 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):
@@ -2794,7 +2793,7 @@
 # </a>
 #
 # From Steffen Thorsen (2011-10-30)
-# Cuba will end DST two weeks later this year. Instead of going back 
+# Cuba will end DST two weeks later this year. Instead of going back
 # tonight, it has been delayed to 2011-11-13 at 01:00.
 #
 # One source (Spanish)
@@ -2806,11 +2805,11 @@
 # <a href="http://www.timeanddate.com/news/time/cuba-time-changes-2011.html">
 # http://www.timeanddate.com/news/time/cuba-time-changes-2011.html
 # </a>
-# 
+#
 # From Steffen Thorsen (2012-03-01)
-# According to Radio Reloj, Cuba will start DST on Midnight between March 
+# According to Radio Reloj, Cuba will start DST on Midnight between March
 # 31 and April 1.
-# 
+#
 # Radio Reloj has the following info (Spanish):
 # <a href="http://www.radioreloj.cu/index.php/noticias-radio-reloj/71-miscelaneas/7529-cuba-aplicara-el-horario-de-verano-desde-el-1-de-abril">
 # http://www.radioreloj.cu/index.php/noticias-radio-reloj/71-miscelaneas/7529-cuba-aplicara-el-horario-de-verano-desde-el-1-de-abril
@@ -2821,6 +2820,13 @@
 # http://www.timeanddate.com/news/time/cuba-starts-dst-2012.html
 # </a>
 
+# From Steffen Thorsen (2012-11-03):
+# Radio Reloj and many other sources report that Cuba is changing back
+# to standard time on 2012-11-04:
+# http://www.radioreloj.cu/index.php/noticias-radio-reloj/36-nacionales/9961-regira-horario-normal-en-cuba-desde-el-domingo-cuatro-de-noviembre
+# From Paul Eggert (2012-11-03):
+# For now, assume the future rule is first Sunday in November.
+
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Cuba	1928	only	-	Jun	10	0:00	1:00	D
 Rule	Cuba	1928	only	-	Oct	10	0:00	0	S
@@ -2858,7 +2864,7 @@
 Rule	Cuba	2011	only	-	Mar	Sun>=15	0:00s	1:00	D
 Rule	Cuba	2011	only	-	Nov	13	0:00s	0	S
 Rule	Cuba	2012	only	-	Apr	1	0:00s	1:00	D
-Rule	Cuba	2012	max	-	Oct	lastSun	0:00s	0	S
+Rule	Cuba	2012	max	-	Nov	Sun>=1	0:00s	0	S
 Rule	Cuba	2013	max	-	Mar	Sun>=8	0:00s	1:00	D
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
--- a/make/sun/javazic/tzdata/pacificnew	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/pacificnew	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)pacificnew	8.2
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
--- a/make/sun/javazic/tzdata/solar87	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/solar87	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)solar87	8.2
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
--- a/make/sun/javazic/tzdata/solar88	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/solar88	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)solar88	8.2
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
--- a/make/sun/javazic/tzdata/solar89	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/solar89	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)solar89	8.2
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
--- a/make/sun/javazic/tzdata/southamerica	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/southamerica	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)southamerica	8.53
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
@@ -255,7 +254,7 @@
 Rule	Arg	2007	only	-	Dec	30	0:00	1:00	S
 Rule	Arg	2008	2009	-	Mar	Sun>=15	0:00	0	-
 Rule	Arg	2008	only	-	Oct	Sun>=15	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....
@@ -345,9 +344,9 @@
 # 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. 
-# 
+# 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
@@ -409,7 +408,7 @@
 # <a href="http://www.lanacion.com.ar/nota.asp?nota_id=1107912">
 # http://www.lanacion.com.ar/nota.asp?nota_id=1107912
 # </a>
-# 
+#
 # The press release says:
 #  (...) anunció que el próximo domingo a las 00:00 los puntanos deberán
 # atrasar una hora sus relojes.
@@ -823,8 +822,8 @@
 #
 # From Alexander Krivenyshev (2011-10-04):
 # State Bahia will return to Daylight savings time this year after 8 years off.
-# The announcement was made by Governor Jaques Wagner in an interview to a 
-# television station in Salvador. 
+# The announcement was made by Governor Jaques Wagner in an interview to a
+# television station in Salvador.
 
 # In Portuguese:
 # <a href="http://g1.globo.com/bahia/noticia/2011/10/governador-jaques-wagner-confirma-horario-de-verao-na-bahia.html">
@@ -853,6 +852,15 @@
 # http://www.in.gov.br/visualiza/index.jsp?data=13/10/2011&jornal=1000&pagina=6&totalArquivos=6
 # </a>
 
+# From Kelley Cook (2012-10-16):
+# The governor of state of Bahia in Brazil announced on Thursday that
+# due to public pressure, he is reversing the DST policy they implemented
+# last year and will not be going to Summer Time on October 21st....
+# http://www.correio24horas.com.br/r/artigo/apos-pressoes-wagner-suspende-horario-de-verao-na-bahia
+
+# From Rodrigo Severo (2012-10-16):
+# Tocantins state will have DST.
+# http://noticias.terra.com.br/brasil/noticias/0,,OI6232536-EI306.html
 
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 # Decree <a href="http://pcdsh01.on.br/HV20466.htm">20,466</a> (1931-10-01)
@@ -1072,7 +1080,8 @@
 			-3:00	Brazil	BR%sT	1990 Sep 17
 			-3:00	-	BRT	1995 Sep 14
 			-3:00	Brazil	BR%sT	2003 Sep 24
-			-3:00	-	BRT
+			-3:00	-	BRT	2012 Oct 21
+			-3:00	Brazil	BR%sT
 #
 # Alagoas (AL), Sergipe (SE)
 Zone America/Maceio	-2:22:52 -	LMT	1914
@@ -1091,7 +1100,8 @@
 Zone America/Bahia	-2:34:04 -	LMT	1914
 			-3:00	Brazil	BR%sT	2003 Sep 24
 			-3:00	-	BRT	2011 Oct 16
-			-3:00	Brazil	BR%sT
+			-3:00	Brazil	BR%sT	2012 Oct 21
+			-3:00	-	BRT
 #
 # Goias (GO), Distrito Federal (DF), Minas Gerais (MG),
 # Espirito Santo (ES), Rio de Janeiro (RJ), Sao Paulo (SP), Parana (PR),
@@ -1183,7 +1193,7 @@
 # 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 
+# The Supreme Decree is located at
 # <a href="http://www.shoa.cl/servicios/supremo316.pdf">
 # http://www.shoa.cl/servicios/supremo316.pdf
 # </a>
@@ -1194,7 +1204,7 @@
 
 # From Jose Miguel Garrido (2008-03-05):
 # ...
-# You could see the announces of the change on 
+# You could see the announces of the change on
 # <a href="http://www.shoa.cl/noticias/2008/04hora/hora.htm">
 # http://www.shoa.cl/noticias/2008/04hora/hora.htm
 # </a>.
--- a/make/sun/javazic/tzdata/systemv	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/systemv	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)systemv	8.2
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
--- a/make/sun/javazic/tzdata/zone.tab	Thu Nov 29 19:42:30 2012 -0800
+++ b/make/sun/javazic/tzdata/zone.tab	Sun Dec 02 23:39:15 2012 -0800
@@ -22,7 +22,6 @@
 # questions.
 #
 # <pre>
-# @(#)zone.tab	8.55
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 #
--- a/src/share/classes/java/io/FileInputStream.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/share/classes/java/io/FileInputStream.java	Sun Dec 02 23:39:15 2012 -0800
@@ -27,6 +27,7 @@
 
 import java.nio.channels.FileChannel;
 import sun.nio.ch.FileChannelImpl;
+import sun.misc.IoTrace;
 
 
 /**
@@ -51,6 +52,9 @@
     /* File Descriptor - handle to the open file */
     private final FileDescriptor fd;
 
+    /* The path of the referenced file (null if the stream is created with a file descriptor) */
+    private final String path;
+
     private FileChannel channel = null;
 
     private final Object closeLock = new Object();
@@ -135,6 +139,7 @@
         }
         fd = new FileDescriptor();
         fd.incrementAndGetUseCount();
+        this.path = name;
         open(name);
     }
 
@@ -171,6 +176,7 @@
             security.checkRead(fdObj);
         }
         fd = fdObj;
+        path = null;
 
         /*
          * FileDescriptor is being shared by streams.
@@ -194,7 +200,18 @@
      *             file is reached.
      * @exception  IOException  if an I/O error occurs.
      */
-    public native int read() throws IOException;
+    public int read() throws IOException {
+        Object traceContext = IoTrace.fileReadBegin(path);
+        int b = 0;
+        try {
+            b = read0();
+        } finally {
+            IoTrace.fileReadEnd(traceContext, b == -1 ? 0 : 1);
+        }
+        return b;
+    }
+
+    private native int read0() throws IOException;
 
     /**
      * Reads a subarray as a sequence of bytes.
@@ -217,7 +234,14 @@
      * @exception  IOException  if an I/O error occurs.
      */
     public int read(byte b[]) throws IOException {
-        return readBytes(b, 0, b.length);
+        Object traceContext = IoTrace.fileReadBegin(path);
+        int bytesRead = 0;
+        try {
+            bytesRead = readBytes(b, 0, b.length);
+        } finally {
+            IoTrace.fileReadEnd(traceContext, bytesRead == -1 ? 0 : bytesRead);
+        }
+        return bytesRead;
     }
 
     /**
@@ -239,7 +263,14 @@
      * @exception  IOException  if an I/O error occurs.
      */
     public int read(byte b[], int off, int len) throws IOException {
-        return readBytes(b, off, len);
+        Object traceContext = IoTrace.fileReadBegin(path);
+        int bytesRead = 0;
+        try {
+            bytesRead = readBytes(b, off, len);
+        } finally {
+            IoTrace.fileReadEnd(traceContext, bytesRead == -1 ? 0 : bytesRead);
+        }
+        return bytesRead;
     }
 
     /**
@@ -361,7 +392,7 @@
     public FileChannel getChannel() {
         synchronized (this) {
             if (channel == null) {
-                channel = FileChannelImpl.open(fd, true, false, this);
+                channel = FileChannelImpl.open(fd, path, true, false, this);
 
                 /*
                  * Increment fd's use count. Invoking the channel's close()
--- a/src/share/classes/java/io/FileOutputStream.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/share/classes/java/io/FileOutputStream.java	Sun Dec 02 23:39:15 2012 -0800
@@ -27,6 +27,7 @@
 
 import java.nio.channels.FileChannel;
 import sun.nio.ch.FileChannelImpl;
+import sun.misc.IoTrace;
 
 
 /**
@@ -58,6 +59,11 @@
     private final FileDescriptor fd;
 
     /**
+     * The path of the referenced file (null if the stream is created with a file descriptor)
+     */
+    private final String path;
+
+    /**
      * True if the file is opened for append.
      */
     private final boolean append;
@@ -207,7 +213,7 @@
         }
         this.fd = new FileDescriptor();
         this.append = append;
-
+        this.path = name;
         fd.incrementAndGetUseCount();
         open(name, append);
     }
@@ -244,6 +250,7 @@
             security.checkWrite(fdObj);
         }
         this.fd = fdObj;
+        this.path = null;
         this.append = false;
 
         /*
@@ -279,7 +286,14 @@
      * @exception  IOException  if an I/O error occurs.
      */
     public void write(int b) throws IOException {
-        write(b, append);
+        Object traceContext = IoTrace.fileWriteBegin(path);
+        int bytesWritten = 0;
+        try {
+            write(b, append);
+            bytesWritten = 1;
+        } finally {
+            IoTrace.fileWriteEnd(traceContext, bytesWritten);
+        }
     }
 
     /**
@@ -302,7 +316,14 @@
      * @exception  IOException  if an I/O error occurs.
      */
     public void write(byte b[]) throws IOException {
-        writeBytes(b, 0, b.length, append);
+        Object traceContext = IoTrace.fileWriteBegin(path);
+        int bytesWritten = 0;
+        try {
+            writeBytes(b, 0, b.length, append);
+            bytesWritten = b.length;
+        } finally {
+            IoTrace.fileWriteEnd(traceContext, bytesWritten);
+        }
     }
 
     /**
@@ -315,7 +336,14 @@
      * @exception  IOException  if an I/O error occurs.
      */
     public void write(byte b[], int off, int len) throws IOException {
-        writeBytes(b, off, len, append);
+        Object traceContext = IoTrace.fileWriteBegin(path);
+        int bytesWritten = 0;
+        try {
+            writeBytes(b, off, len, append);
+            bytesWritten = len;
+        } finally {
+            IoTrace.fileWriteEnd(traceContext, bytesWritten);
+        }
     }
 
     /**
@@ -398,7 +426,7 @@
     public FileChannel getChannel() {
         synchronized (this) {
             if (channel == null) {
-                channel = FileChannelImpl.open(fd, false, true, append, this);
+                channel = FileChannelImpl.open(fd, path, false, true, append, this);
 
                 /*
                  * Increment fd's use count. Invoking the channel's close()
--- a/src/share/classes/java/io/RandomAccessFile.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/share/classes/java/io/RandomAccessFile.java	Sun Dec 02 23:39:15 2012 -0800
@@ -27,6 +27,7 @@
 
 import java.nio.channels.FileChannel;
 import sun.nio.ch.FileChannelImpl;
+import sun.misc.IoTrace;
 
 
 /**
@@ -62,6 +63,9 @@
     private FileChannel channel = null;
     private boolean rw;
 
+    /* The path of the referenced file */
+    private final String path;
+
     private Object closeLock = new Object();
     private volatile boolean closed = false;
 
@@ -230,6 +234,7 @@
         }
         fd = new FileDescriptor();
         fd.incrementAndGetUseCount();
+        this.path = name;
         open(name, imode);
     }
 
@@ -267,7 +272,7 @@
     public final FileChannel getChannel() {
         synchronized (this) {
             if (channel == null) {
-                channel = FileChannelImpl.open(fd, true, rw, this);
+                channel = FileChannelImpl.open(fd, path, true, rw, this);
 
                 /*
                  * FileDescriptor could be shared by FileInputStream or
@@ -315,7 +320,18 @@
      * @exception  IOException  if an I/O error occurs. Not thrown if
      *                          end-of-file has been reached.
      */
-    public native int read() throws IOException;
+    public int read() throws IOException {
+        Object traceContext = IoTrace.fileReadBegin(path);
+        int b = 0;
+        try {
+            b = read0();
+        } finally {
+            IoTrace.fileReadEnd(traceContext, b == -1 ? 0 : 1);
+        }
+        return b;
+    }
+
+    private native int read0() throws IOException;
 
     /**
      * Reads a sub array as a sequence of bytes.
@@ -324,7 +340,18 @@
      * @param len the number of bytes to read.
      * @exception IOException If an I/O error has occurred.
      */
-    private native int readBytes(byte b[], int off, int len) throws IOException;
+    private int readBytes(byte b[], int off, int len) throws IOException {
+        Object traceContext = IoTrace.fileReadBegin(path);
+        int bytesRead = 0;
+        try {
+            bytesRead = readBytes0(b, off, len);
+        } finally {
+            IoTrace.fileReadEnd(traceContext, bytesRead == -1 ? 0 : bytesRead);
+        }
+        return bytesRead;
+    }
+
+    private native int readBytes0(byte b[], int off, int len) throws IOException;
 
     /**
      * Reads up to <code>len</code> bytes of data from this file into an
@@ -463,17 +490,38 @@
      * @param      b   the <code>byte</code> to be written.
      * @exception  IOException  if an I/O error occurs.
      */
-    public native void write(int b) throws IOException;
+    public void write(int b) throws IOException {
+        Object traceContext = IoTrace.fileWriteBegin(path);
+        int bytesWritten = 0;
+        try {
+            write0(b);
+            bytesWritten = 1;
+        } finally {
+            IoTrace.fileWriteEnd(traceContext, bytesWritten);
+        }
+    }
+
+    private native void write0(int b) throws IOException;
 
     /**
      * Writes a sub array as a sequence of bytes.
      * @param b the data to be written
-
      * @param off the start offset in the data
      * @param len the number of bytes that are written
      * @exception IOException If an I/O error has occurred.
      */
-    private native void writeBytes(byte b[], int off, int len) throws IOException;
+    private void writeBytes(byte b[], int off, int len) throws IOException {
+        Object traceContext = IoTrace.fileWriteBegin(path);
+        int bytesWritten = 0;
+        try {
+            writeBytes0(b, off, len);
+            bytesWritten = len;
+        } finally {
+            IoTrace.fileWriteEnd(traceContext, bytesWritten);
+        }
+    }
+
+    private native void writeBytes0(byte b[], int off, int len) throws IOException;
 
     /**
      * Writes <code>b.length</code> bytes from the specified byte array
--- a/src/share/classes/java/net/SocketInputStream.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/share/classes/java/net/SocketInputStream.java	Sun Dec 02 23:39:15 2012 -0800
@@ -30,6 +30,7 @@
 import java.io.IOException;
 import java.nio.channels.FileChannel;
 
+import sun.misc.IoTrace;
 import sun.net.ConnectionResetException;
 
 /**
@@ -122,7 +123,7 @@
     }
 
     int read(byte b[], int off, int length, int timeout) throws IOException {
-        int n;
+        int n = 0;
 
         // EOF already encountered
         if (eof) {
@@ -144,6 +145,7 @@
 
         boolean gotReset = false;
 
+        Object traceContext = IoTrace.socketReadBegin(impl.address, impl.port, timeout);
         // acquire file descriptor and do the read
         FileDescriptor fd = impl.acquireFD();
         try {
@@ -155,6 +157,7 @@
             gotReset = true;
         } finally {
             impl.releaseFD();
+            IoTrace.socketReadEnd(traceContext, n > 0 ? n : 0);
         }
 
         /*
@@ -162,6 +165,7 @@
          * buffered on the socket
          */
         if (gotReset) {
+            traceContext = IoTrace.socketReadBegin(impl.address, impl.port, timeout);
             impl.setConnectionResetPending();
             impl.acquireFD();
             try {
@@ -172,6 +176,7 @@
             } catch (ConnectionResetException rstExc) {
             } finally {
                 impl.releaseFD();
+                IoTrace.socketReadEnd(traceContext, n > 0 ? n : 0);
             }
         }
 
--- a/src/share/classes/java/net/SocketOutputStream.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/share/classes/java/net/SocketOutputStream.java	Sun Dec 02 23:39:15 2012 -0800
@@ -30,6 +30,8 @@
 import java.io.IOException;
 import java.nio.channels.FileChannel;
 
+import sun.misc.IoTrace;
+
 /**
  * This stream extends FileOutputStream to implement a
  * SocketOutputStream. Note that this class should <b>NOT</b> be
@@ -104,9 +106,12 @@
             throw new ArrayIndexOutOfBoundsException();
         }
 
+        Object traceContext = IoTrace.socketWriteBegin(impl.address, impl.port);
+        int bytesWritten = 0;
         FileDescriptor fd = impl.acquireFD();
         try {
             socketWrite0(fd, b, off, len);
+            bytesWritten = len;
         } catch (SocketException se) {
             if (se instanceof sun.net.ConnectionResetException) {
                 impl.setConnectionResetPending();
@@ -119,6 +124,7 @@
             }
         } finally {
             impl.releaseFD();
+            IoTrace.socketWriteEnd(traceContext, bytesWritten);
         }
     }
 
--- a/src/share/classes/sun/awt/im/InputContext.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/share/classes/sun/awt/im/InputContext.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -785,7 +785,7 @@
     public void disableNativeIM() {
         InputMethod inputMethod = getInputMethod();
         if (inputMethod != null && inputMethod instanceof InputMethodAdapter) {
-            ((InputMethodAdapter)inputMethod).disableInputMethod();
+            ((InputMethodAdapter)inputMethod).stopListening();
         }
     }
 
--- a/src/share/classes/sun/awt/im/InputMethodAdapter.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/share/classes/sun/awt/im/InputMethodAdapter.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -79,7 +79,6 @@
 
     /**
      * Informs the input method adapter not to listen to the native events.
-     * This method is called when a Java input method is active.
      */
     protected void stopListening() {
         // ignore - adapters can override if needed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/misc/IoTrace.java	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.misc;
+
+import java.net.InetAddress;
+
+/**
+ * Utility class used to identify trace points for I/O calls.
+ * <p>
+ * To use this class, a diagnostic tool must redefine this class with a version
+ * that contains calls to the the diagnostic tool. This implementation will then
+ * receive callbacks when file and socket operations are performed. The reason
+ * for requiring a redefine of the class is to avoid any overhead caused by the
+ * instrumentation.
+ * <p>
+ * The xxBegin() methods return a "context". This can be any Object. This
+ * context will be passed to the corresponding xxEnd() method. This way, an
+ * implementation can correlate the beginning of an operation with the end.
+ * <p>
+ * It is possible for a xxEnd() method to be called with a null handle. This
+ * happens if tracing was started between the call to xxBegin() and xxEnd(), in
+ * which case xxBegin() would not have been called. It is the implementation's
+ * responsibility to not throw an exception in this case.
+ * <p>
+ * Only blocking I/O operations are identified with this facility.
+ * <p>
+ * <b>Warning</b>
+ * <p>
+ * These methods are called from sensitive points in the I/O subsystem. Great
+ * care must be taken to not interfere with ongoing operations or cause
+ * deadlocks. In particular:
+ * <ul>
+ * <li>Implementations must not throw exceptions since this will cause
+ * disruptions to the I/O operations.
+ * <li>Implementations must not do I/O operations since this will lead to an
+ * endless loop.
+ * <li>Since the hooks may be called while holding low-level locks in the I/O
+ * subsystem, implementations must be careful with synchronization or
+ * interaction with other threads to avoid deadlocks in the VM.
+ * </ul>
+ */
+public final class IoTrace {
+    private IoTrace() {
+    }
+
+    /**
+     * Called before data is read from a socket.
+     *
+     * @param address
+     *            the remote address the socket is bound to
+     * @param port
+     *            the remote port the socket is bound to
+     * @param timeout
+     *            the SO_TIMEOUT value of the socket (in milliseconds) or 0 if
+     *            there is no timeout set
+     * @return a context object
+     */
+    public static Object socketReadBegin(InetAddress address, int port,
+            int timeout) {
+        return null;
+    }
+
+    /**
+     * Called after data is read from the socket.
+     *
+     * @param context
+     *            the context returned by the previous call to socketReadBegin()
+     * @param bytesRead
+     *            the number of bytes read from the socket, 0 if there was an
+     *            error reading from the socket
+     */
+    public static void socketReadEnd(Object context, long bytesRead) {
+    }
+
+    /**
+     * Called before data is written to a socket.
+     *
+     * @param address
+     *            the remote address the socket is bound to
+     * @param port
+     *            the remote port the socket is bound to
+     * @return a context object
+     */
+    public static Object socketWriteBegin(InetAddress address, int port) {
+        return null;
+    }
+
+    /**
+     * Called after data is written to a socket.
+     *
+     * @param context
+     *            the context returned by the previous call to
+     *            socketWriteBegin()
+     * @param bytesWritten
+     *            the number of bytes written to the socket, 0 if there was an
+     *            error writing to the socket
+     */
+    public static void socketWriteEnd(Object context, long bytesWritten) {
+    }
+
+    /**
+     * Called before data is read from a file.
+     *
+     * @param path
+     *            the path of the file
+     * @return a context object
+     */
+    public static Object fileReadBegin(String path) {
+        return null;
+    }
+
+    /**
+     * Called after data is read from a file.
+     *
+     * @param context
+     *            the context returned by the previous call to fileReadBegin()
+     * @param bytesRead
+     *            the number of bytes written to the file, 0 if there was an
+     *            error writing to the file
+     */
+    public static void fileReadEnd(Object context, long bytesRead) {
+    }
+
+    /**
+     * Called before data is written to a file.
+     *
+     * @param path
+     *            the path of the file
+     * @return a context object
+     */
+    public static Object fileWriteBegin(String path) {
+        return null;
+    }
+
+    /**
+     * Called after data is written to a file.
+     *
+     * @param context
+     *            the context returned by the previous call to fileReadBegin()
+     * @param bytesWritten
+     *            the number of bytes written to the file, 0 if there was an
+     *            error writing to the file
+     */
+    public static void fileWriteEnd(Object context, long bytesWritten) {
+    }
+}
--- a/src/share/classes/sun/nio/ch/FileChannelImpl.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/share/classes/sun/nio/ch/FileChannelImpl.java	Sun Dec 02 23:39:15 2012 -0800
@@ -34,6 +34,7 @@
 import java.util.List;
 import java.security.AccessController;
 import sun.misc.Cleaner;
+import sun.misc.IoTrace;
 import sun.security.action.GetPropertyAction;
 
 public class FileChannelImpl
@@ -56,13 +57,16 @@
     // Required to prevent finalization of creating stream (immutable)
     private final Object parent;
 
+    // The path of the referenced file (null if the parent stream is created with a file descriptor)
+    private final String path;
+
     // Thread-safe set of IDs of native threads, for signalling
     private final NativeThreadSet threads = new NativeThreadSet(2);
 
     // Lock for operations involving position and size
     private final Object positionLock = new Object();
 
-    private FileChannelImpl(FileDescriptor fd, boolean readable,
+    private FileChannelImpl(FileDescriptor fd, String path, boolean readable,
                             boolean writable, boolean append, Object parent)
     {
         this.fd = fd;
@@ -70,23 +74,24 @@
         this.writable = writable;
         this.append = append;
         this.parent = parent;
+        this.path = path;
         this.nd = new FileDispatcherImpl(append);
     }
 
     // Used by FileInputStream.getChannel() and RandomAccessFile.getChannel()
-    public static FileChannel open(FileDescriptor fd,
+    public static FileChannel open(FileDescriptor fd, String path,
                                    boolean readable, boolean writable,
                                    Object parent)
     {
-        return new FileChannelImpl(fd, readable, writable, false, parent);
+        return new FileChannelImpl(fd, path, readable, writable, false, parent);
     }
 
     // Used by FileOutputStream.getChannel
-    public static FileChannel open(FileDescriptor fd,
+    public static FileChannel open(FileDescriptor fd, String path,
                                    boolean readable, boolean writable,
                                    boolean append, Object parent)
     {
-        return new FileChannelImpl(fd, readable, writable, append, parent);
+        return new FileChannelImpl(fd, path, readable, writable, append, parent);
     }
 
     private void ensureOpen() throws IOException {
@@ -134,6 +139,7 @@
         synchronized (positionLock) {
             int n = 0;
             int ti = -1;
+            Object traceContext = IoTrace.fileReadBegin(path);
             try {
                 begin();
                 ti = threads.add();
@@ -145,6 +151,7 @@
                 return IOStatus.normalize(n);
             } finally {
                 threads.remove(ti);
+                IoTrace.fileReadEnd(traceContext, n > 0 ? n : 0);
                 end(n > 0);
                 assert IOStatus.check(n);
             }
@@ -162,6 +169,7 @@
         synchronized (positionLock) {
             long n = 0;
             int ti = -1;
+            Object traceContext = IoTrace.fileReadBegin(path);
             try {
                 begin();
                 ti = threads.add();
@@ -173,6 +181,7 @@
                 return IOStatus.normalize(n);
             } finally {
                 threads.remove(ti);
+                IoTrace.fileReadEnd(traceContext, n > 0 ? n : 0);
                 end(n > 0);
                 assert IOStatus.check(n);
             }
@@ -186,6 +195,7 @@
         synchronized (positionLock) {
             int n = 0;
             int ti = -1;
+            Object traceContext = IoTrace.fileWriteBegin(path);
             try {
                 begin();
                 ti = threads.add();
@@ -198,6 +208,7 @@
             } finally {
                 threads.remove(ti);
                 end(n > 0);
+                IoTrace.fileWriteEnd(traceContext, n > 0 ? n : 0);
                 assert IOStatus.check(n);
             }
         }
@@ -214,6 +225,7 @@
         synchronized (positionLock) {
             long n = 0;
             int ti = -1;
+            Object traceContext = IoTrace.fileWriteBegin(path);
             try {
                 begin();
                 ti = threads.add();
@@ -225,6 +237,7 @@
                 return IOStatus.normalize(n);
             } finally {
                 threads.remove(ti);
+                IoTrace.fileWriteEnd(traceContext, n > 0 ? n : 0);
                 end(n > 0);
                 assert IOStatus.check(n);
             }
@@ -665,6 +678,7 @@
         ensureOpen();
         int n = 0;
         int ti = -1;
+        Object traceContext = IoTrace.fileReadBegin(path);
         try {
             begin();
             ti = threads.add();
@@ -676,6 +690,7 @@
             return IOStatus.normalize(n);
         } finally {
             threads.remove(ti);
+            IoTrace.fileReadEnd(traceContext, n > 0 ? n : 0);
             end(n > 0);
             assert IOStatus.check(n);
         }
@@ -691,6 +706,7 @@
         ensureOpen();
         int n = 0;
         int ti = -1;
+        Object traceContext = IoTrace.fileWriteBegin(path);
         try {
             begin();
             ti = threads.add();
@@ -703,6 +719,7 @@
         } finally {
             threads.remove(ti);
             end(n > 0);
+            IoTrace.fileWriteEnd(traceContext, n > 0 ? n : 0);
             assert IOStatus.check(n);
         }
     }
--- a/src/share/classes/sun/nio/ch/SocketAdaptor.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/share/classes/sun/nio/ch/SocketAdaptor.java	Sun Dec 02 23:39:15 2012 -0800
@@ -34,6 +34,8 @@
 import java.security.PrivilegedExceptionAction;
 import java.util.*;
 
+import sun.misc.IoTrace;
+
 
 // Make a socket channel look like a socket.
 //
@@ -204,8 +206,9 @@
                 SelectionKey sk = null;
                 Selector sel = null;
                 sc.configureBlocking(false);
+                int n = 0;
+                Object traceContext = IoTrace.socketReadBegin(getInetAddress(), getPort(), timeout);
                 try {
-                    int n;
                     if ((n = sc.read(bb)) != 0)
                         return n;
                     sel = Util.getTemporarySelector(sc);
@@ -226,6 +229,7 @@
                             throw new SocketTimeoutException();
                     }
                 } finally {
+                    IoTrace.socketReadEnd(traceContext, n > 0 ? n : 0);
                     if (sk != null)
                         sk.cancel();
                     if (sc.isOpen())
--- a/src/share/classes/sun/nio/ch/SocketChannelImpl.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/share/classes/sun/nio/ch/SocketChannelImpl.java	Sun Dec 02 23:39:15 2012 -0800
@@ -33,7 +33,7 @@
 import java.nio.channels.spi.*;
 import java.util.*;
 import sun.net.NetHooks;
-
+import sun.misc.IoTrace;
 
 /**
  * An implementation of SocketChannels
@@ -80,8 +80,8 @@
     private int state = ST_UNINITIALIZED;
 
     // Binding
-    private SocketAddress localAddress;
-    private SocketAddress remoteAddress;
+    private InetSocketAddress localAddress;
+    private InetSocketAddress remoteAddress;
 
     // Input/Output open
     private boolean isInputOpen = true;
@@ -278,6 +278,11 @@
         synchronized (readLock) {
             if (!ensureReadOpen())
                 return -1;
+            Object traceContext = null;
+            if (isBlocking()) {
+                traceContext = IoTrace.socketReadBegin(remoteAddress.getAddress(),
+                                                      remoteAddress.getPort(), 0);
+            }
             int n = 0;
             try {
 
@@ -367,6 +372,11 @@
 
             } finally {
                 readerCleanup();        // Clear reader thread
+
+                if (isBlocking()) {
+                    IoTrace.socketReadEnd(traceContext, n > 0 ? n : 0);
+                }
+
                 // The end method, which is defined in our superclass
                 // AbstractInterruptibleChannel, resets the interruption
                 // machinery.  If its argument is true then it returns
@@ -407,6 +417,11 @@
             if (!ensureReadOpen())
                 return -1;
             long n = 0;
+            Object traceContext = null;
+            if (isBlocking()) {
+                traceContext = IoTrace.socketReadBegin(remoteAddress.getAddress(),
+                                                      remoteAddress.getPort(), 0);
+            }
             try {
                 begin();
                 synchronized (stateLock) {
@@ -423,6 +438,9 @@
                 }
             } finally {
                 readerCleanup();
+                if (isBlocking()) {
+                    IoTrace.socketReadEnd(traceContext, n > 0 ? n : 0);
+                }
                 end(n > 0 || (n == IOStatus.UNAVAILABLE));
                 synchronized (stateLock) {
                     if ((n <= 0) && (!isInputOpen))
@@ -439,6 +457,10 @@
         synchronized (writeLock) {
             ensureWriteOpen();
             int n = 0;
+            Object traceContext =
+                IoTrace.socketWriteBegin(remoteAddress.getAddress(),
+                                         remoteAddress.getPort());
+
             try {
                 begin();
                 synchronized (stateLock) {
@@ -454,6 +476,7 @@
                 }
             } finally {
                 writerCleanup();
+                IoTrace.socketWriteEnd(traceContext, n > 0 ? n : 0);
                 end(n > 0 || (n == IOStatus.UNAVAILABLE));
                 synchronized (stateLock) {
                     if ((n <= 0) && (!isOutputOpen))
@@ -472,6 +495,9 @@
         synchronized (writeLock) {
             ensureWriteOpen();
             long n = 0;
+            Object traceContext =
+                IoTrace.socketWriteBegin(remoteAddress.getAddress(),
+                                         remoteAddress.getPort());
             try {
                 begin();
                 synchronized (stateLock) {
@@ -487,6 +513,7 @@
                 }
             } finally {
                 writerCleanup();
+                IoTrace.socketWriteEnd(traceContext, n > 0 ? n : 0);
                 end((n > 0) || (n == IOStatus.UNAVAILABLE));
                 synchronized (stateLock) {
                     if ((n <= 0) && (!isOutputOpen))
--- a/src/share/classes/sun/security/krb5/Config.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/share/classes/sun/security/krb5/Config.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1314,7 +1314,7 @@
      */
     private String getKDCFromDNS(String realm) throws KrbException {
         // use DNS to locate KDC
-        String kdcs = null;
+        String kdcs = "";
         String[] srvs = null;
         // locate DNS SRV record using UDP
         if (DEBUG) {
@@ -1324,7 +1324,7 @@
         if (srvs == null) {
             // locate DNS SRV record using TCP
             if (DEBUG) {
-                System.out.println("getKDCFromDNS using UDP");
+                System.out.println("getKDCFromDNS using TCP");
             }
             srvs = KrbServiceLocator.getKerberosService(realm, "_tcp");
         }
@@ -1333,14 +1333,15 @@
             throw new KrbException(Krb5.KRB_ERR_GENERIC,
                 "Unable to locate KDC for realm " + realm);
         }
+        if (srvs.length == 0) {
+            return null;
+        }
         for (int i = 0; i < srvs.length; i++) {
-            String value = srvs[i];
-            for (int j = 0; j < srvs[i].length(); j++) {
-                // filter the KDC name
-                if (value.charAt(j) == ':') {
-                    kdcs = (value.substring(0, j)).trim();
-                }
-            }
+            kdcs += srvs[i].trim() + " ";
+        }
+        kdcs = kdcs.trim();
+        if (kdcs.equals("")) {
+            return null;
         }
         return kdcs;
     }
--- a/src/share/native/java/io/FileInputStream.c	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/share/native/java/io/FileInputStream.c	Sun Dec 02 23:39:15 2012 -0800
@@ -62,7 +62,7 @@
 }
 
 JNIEXPORT jint JNICALL
-Java_java_io_FileInputStream_read(JNIEnv *env, jobject this) {
+Java_java_io_FileInputStream_read0(JNIEnv *env, jobject this) {
     return readSingle(env, this, fis_fd);
 }
 
--- a/src/share/native/java/io/RandomAccessFile.c	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/share/native/java/io/RandomAccessFile.c	Sun Dec 02 23:39:15 2012 -0800
@@ -64,23 +64,23 @@
 }
 
 JNIEXPORT jint JNICALL
-Java_java_io_RandomAccessFile_read(JNIEnv *env, jobject this) {
+Java_java_io_RandomAccessFile_read0(JNIEnv *env, jobject this) {
     return readSingle(env, this, raf_fd);
 }
 
 JNIEXPORT jint JNICALL
-Java_java_io_RandomAccessFile_readBytes(JNIEnv *env,
+Java_java_io_RandomAccessFile_readBytes0(JNIEnv *env,
     jobject this, jbyteArray bytes, jint off, jint len) {
     return readBytes(env, this, bytes, off, len, raf_fd);
 }
 
 JNIEXPORT void JNICALL
-Java_java_io_RandomAccessFile_write(JNIEnv *env, jobject this, jint byte) {
+Java_java_io_RandomAccessFile_write0(JNIEnv *env, jobject this, jint byte) {
     writeSingle(env, this, byte, JNI_FALSE, raf_fd);
 }
 
 JNIEXPORT void JNICALL
-Java_java_io_RandomAccessFile_writeBytes(JNIEnv *env,
+Java_java_io_RandomAccessFile_writeBytes0(JNIEnv *env,
     jobject this, jbyteArray bytes, jint off, jint len) {
     writeBytes(env, this, bytes, off, len, JNI_FALSE, raf_fd);
 }
--- a/src/solaris/classes/sun/awt/X11InputMethod.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/solaris/classes/sun/awt/X11InputMethod.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -415,6 +415,10 @@
             setXICFocus(getPeer(lastXICFocussedComponent), false, isLastXICActive);
             lastXICFocussedComponent = null;
             isLastXICActive = false;
+
+            resetXIC();
+            needResetXICClient = null;
+            needResetXIC = false;
         }
     }
 
--- a/src/solaris/classes/sun/nio/fs/SolarisUserDefinedFileAttributeView.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/solaris/classes/sun/nio/fs/SolarisUserDefinedFileAttributeView.java	Sun Dec 02 23:39:15 2012 -0800
@@ -147,7 +147,7 @@
                 int afd = openat(fd, nameAsBytes(file,name), (O_RDONLY|O_XATTR), 0);
 
                 // wrap with channel
-                FileChannel fc = UnixChannelFactory.newFileChannel(afd, true, false);
+                FileChannel fc = UnixChannelFactory.newFileChannel(afd, file.toString(), true, false);
 
                 // read to EOF (nothing we can do if I/O error occurs)
                 try {
@@ -188,7 +188,7 @@
                                  UnixFileModeAttribute.ALL_PERMISSIONS);
 
                 // wrap with channel
-                FileChannel fc = UnixChannelFactory.newFileChannel(afd, false, true);
+                FileChannel fc = UnixChannelFactory.newFileChannel(afd, file.toString(), false, true);
 
                 // write value (nothing we can do if I/O error occurs)
                 try {
--- a/src/solaris/classes/sun/nio/fs/UnixChannelFactory.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/solaris/classes/sun/nio/fs/UnixChannelFactory.java	Sun Dec 02 23:39:15 2012 -0800
@@ -100,10 +100,10 @@
     /**
      * Constructs a file channel from an existing (open) file descriptor
      */
-    static FileChannel newFileChannel(int fd, boolean reading, boolean writing) {
+    static FileChannel newFileChannel(int fd, String path, boolean reading, boolean writing) {
         FileDescriptor fdObj = new FileDescriptor();
         fdAccess.set(fdObj, fd);
-        return FileChannelImpl.open(fdObj, reading, writing, null);
+        return FileChannelImpl.open(fdObj, path, reading, writing, null);
     }
 
     /**
@@ -134,7 +134,8 @@
             throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
 
         FileDescriptor fdObj = open(dfd, path, pathForPermissionCheck, flags, mode);
-        return FileChannelImpl.open(fdObj, flags.read, flags.write, flags.append, null);
+        return FileChannelImpl.open(fdObj, path.toString(),
+            flags.read, flags.write, flags.append, null);
     }
 
     /**
--- a/src/windows/classes/sun/nio/fs/WindowsChannelFactory.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/src/windows/classes/sun/nio/fs/WindowsChannelFactory.java	Sun Dec 02 23:39:15 2012 -0800
@@ -157,7 +157,7 @@
             throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
 
         FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor);
-        return FileChannelImpl.open(fdObj, flags.read, flags.write, flags.append, null);
+        return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write, flags.append, null);
     }
 
     /**
--- a/test/java/beans/EventHandler/Test6277266.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/beans/EventHandler/Test6277266.java	Sun Dec 02 23:39:15 2012 -0800
@@ -51,9 +51,11 @@
                     )
             );
             throw new Error("SecurityException expected");
+        } catch (SecurityException exception) {
+            return; // expected security exception in JDK 7
         } catch (InvocationTargetException exception) {
             if (exception.getCause() instanceof SecurityException){
-                return; // expected security exception
+                return; // expected security exception in JDK 8
             }
             throw new Error("unexpected exception", exception);
         } catch (InterruptedException exception) {
--- a/test/java/nio/channels/AsynchronousSocketChannel/Basic.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/AsynchronousSocketChannel/Basic.java	Sun Dec 02 23:39:15 2012 -0800
@@ -24,7 +24,7 @@
 /* @test
  * @bug 4607272 6842687 6878369 6944810 7023403
  * @summary Unit test for AsynchronousSocketChannel
- * @run main/timeout=600 Basic
+ * @run main Basic -skipSlowConnectTest
  */
 
 import java.nio.ByteBuffer;
@@ -34,12 +34,25 @@
 import java.util.Random;
 import java.util.concurrent.*;
 import java.util.concurrent.atomic.*;
+import java.io.Closeable;
 import java.io.IOException;
 
 public class Basic {
     static final Random rand = new Random();
 
+    static boolean skipSlowConnectTest = false;
+
     public static void main(String[] args) throws Exception {
+        for (String arg: args) {
+            switch (arg) {
+            case "-skipSlowConnectTest" :
+                skipSlowConnectTest = true;
+                break;
+            default:
+                throw new RuntimeException("Unrecognized argument: " + arg);
+            }
+        }
+
         testBind();
         testSocketOptions();
         testConnect();
@@ -54,7 +67,7 @@
         testShutdown();
     }
 
-    static class Server {
+    static class Server implements Closeable {
         private final ServerSocketChannel ssc;
         private final InetSocketAddress address;
 
@@ -74,10 +87,8 @@
             return ssc.accept();
         }
 
-        void close() {
-            try {
-                ssc.close();
-            } catch (IOException ignore) { }
+        public void close() throws IOException {
+            ssc.close();
         }
 
     }
@@ -85,28 +96,28 @@
     static void testBind() throws Exception {
         System.out.println("-- bind --");
 
-        AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
-        if (ch.getLocalAddress() != null)
-            throw new RuntimeException("Local address should be 'null'");
-        ch.bind(new InetSocketAddress(0));
+        try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {
+            if (ch.getLocalAddress() != null)
+                throw new RuntimeException("Local address should be 'null'");
+            ch.bind(new InetSocketAddress(0));
 
-        // check local address after binding
-        InetSocketAddress local = (InetSocketAddress)ch.getLocalAddress();
-        if (local.getPort() == 0)
-            throw new RuntimeException("Unexpected port");
-        if (!local.getAddress().isAnyLocalAddress())
-            throw new RuntimeException("Not bound to a wildcard address");
+            // check local address after binding
+            InetSocketAddress local = (InetSocketAddress)ch.getLocalAddress();
+            if (local.getPort() == 0)
+                throw new RuntimeException("Unexpected port");
+            if (!local.getAddress().isAnyLocalAddress())
+                throw new RuntimeException("Not bound to a wildcard address");
 
-        // try to re-bind
-        try {
-            ch.bind(new InetSocketAddress(0));
-            throw new RuntimeException("AlreadyBoundException expected");
-        } catch (AlreadyBoundException x) {
+            // try to re-bind
+            try {
+                ch.bind(new InetSocketAddress(0));
+                throw new RuntimeException("AlreadyBoundException expected");
+            } catch (AlreadyBoundException x) {
+            }
         }
-        ch.close();
 
         // check ClosedChannelException
-        ch = AsynchronousSocketChannel.open();
+        AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
         ch.close();
         try {
             ch.bind(new InetSocketAddress(0));
@@ -118,109 +129,124 @@
     static void testSocketOptions() throws Exception {
         System.out.println("-- socket options --");
 
-        AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()
-            .setOption(SO_RCVBUF, 128*1024)
-            .setOption(SO_SNDBUF, 128*1024)
-            .setOption(SO_REUSEADDR, true);
+        try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {
+            ch.setOption(SO_RCVBUF, 128*1024)
+              .setOption(SO_SNDBUF, 128*1024)
+              .setOption(SO_REUSEADDR, true);
 
-        // check SO_SNDBUF/SO_RCVBUF limits
-        int before, after;
-        before = ch.getOption(SO_SNDBUF);
-        after = ch.setOption(SO_SNDBUF, Integer.MAX_VALUE).getOption(SO_SNDBUF);
-        if (after < before)
-            throw new RuntimeException("setOption caused SO_SNDBUF to decrease");
-        before = ch.getOption(SO_RCVBUF);
-        after = ch.setOption(SO_RCVBUF, Integer.MAX_VALUE).getOption(SO_RCVBUF);
-        if (after < before)
-            throw new RuntimeException("setOption caused SO_RCVBUF to decrease");
-
-        ch.bind(new InetSocketAddress(0));
+            // check SO_SNDBUF/SO_RCVBUF limits
+            int before, after;
+            before = ch.getOption(SO_SNDBUF);
+            after = ch.setOption(SO_SNDBUF, Integer.MAX_VALUE).getOption(SO_SNDBUF);
+            if (after < before)
+                throw new RuntimeException("setOption caused SO_SNDBUF to decrease");
+            before = ch.getOption(SO_RCVBUF);
+            after = ch.setOption(SO_RCVBUF, Integer.MAX_VALUE).getOption(SO_RCVBUF);
+            if (after < before)
+                throw new RuntimeException("setOption caused SO_RCVBUF to decrease");
 
-        // default values
-        if ((Boolean)ch.getOption(SO_KEEPALIVE))
-            throw new RuntimeException("Default of SO_KEEPALIVE should be 'false'");
-        if ((Boolean)ch.getOption(TCP_NODELAY))
-            throw new RuntimeException("Default of TCP_NODELAY should be 'false'");
+            ch.bind(new InetSocketAddress(0));
+
+            // default values
+            if (ch.getOption(SO_KEEPALIVE))
+                throw new RuntimeException("Default of SO_KEEPALIVE should be 'false'");
+            if (ch.getOption(TCP_NODELAY))
+                throw new RuntimeException("Default of TCP_NODELAY should be 'false'");
 
-        // set and check
-        if (!(Boolean)ch.setOption(SO_KEEPALIVE, true).getOption(SO_KEEPALIVE))
-            throw new RuntimeException("SO_KEEPALIVE did not change");
-        if (!(Boolean)ch.setOption(TCP_NODELAY, true).getOption(TCP_NODELAY))
-            throw new RuntimeException("SO_KEEPALIVE did not change");
+            // set and check
+            if (!ch.setOption(SO_KEEPALIVE, true).getOption(SO_KEEPALIVE))
+                throw new RuntimeException("SO_KEEPALIVE did not change");
+            if (!ch.setOption(TCP_NODELAY, true).getOption(TCP_NODELAY))
+                throw new RuntimeException("SO_KEEPALIVE did not change");
 
-        // read others (can't check as actual value is implementation dependent)
-        ch.getOption(SO_RCVBUF);
-        ch.getOption(SO_SNDBUF);
-
-        ch.close();
+            // read others (can't check as actual value is implementation dependent)
+            ch.getOption(SO_RCVBUF);
+            ch.getOption(SO_SNDBUF);
+        }
     }
 
     static void testConnect() throws Exception {
         System.out.println("-- connect --");
 
-        Server server = new Server();
-        AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
-        ch.connect(server.address()).get();
+        SocketAddress address;
+
+        try (Server server = new Server()) {
+            address = server.address();
 
-        // check local address
-        if (ch.getLocalAddress() == null)
-            throw new RuntimeException("Not bound to local address");
+            // connect to server and check local/remote addresses
+            try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {
+                ch.connect(address).get();
+                // check local address
+                if (ch.getLocalAddress() == null)
+                    throw new RuntimeException("Not bound to local address");
 
-        // check remote address
-        InetSocketAddress remote = (InetSocketAddress)ch.getRemoteAddress();
-        if (remote.getPort() != server.address().getPort())
-            throw new RuntimeException("Connected to unexpected port");
-        if (!remote.getAddress().equals(server.address().getAddress()))
-            throw new RuntimeException("Connected to unexpected address");
+                // check remote address
+                InetSocketAddress remote = (InetSocketAddress)ch.getRemoteAddress();
+                if (remote.getPort() != server.address().getPort())
+                    throw new RuntimeException("Connected to unexpected port");
+                if (!remote.getAddress().equals(server.address().getAddress()))
+                    throw new RuntimeException("Connected to unexpected address");
 
-        // try to connect again
-        try {
-            ch.connect(server.address()).get();
-            throw new RuntimeException("AlreadyConnectedException expected");
-        } catch (AlreadyConnectedException x) {
-        }
-        ch.close();
+                // try to connect again
+                try {
+                    ch.connect(server.address()).get();
+                    throw new RuntimeException("AlreadyConnectedException expected");
+                } catch (AlreadyConnectedException x) {
+                }
 
-        // check that connect fails with ClosedChannelException)
-        ch = AsynchronousSocketChannel.open();
-        ch.close();
-        try {
-            ch.connect(server.address()).get();
-            throw new RuntimeException("ExecutionException expected");
-        } catch (ExecutionException x) {
-            if (!(x.getCause() instanceof ClosedChannelException))
-                throw new RuntimeException("Cause of ClosedChannelException expected");
+                // clean-up
+                server.accept().close();
+            }
+
+            // check that connect fails with ClosedChannelException
+            AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
+            ch.close();
+            try {
+                ch.connect(server.address()).get();
+                throw new RuntimeException("ExecutionException expected");
+            } catch (ExecutionException x) {
+                if (!(x.getCause() instanceof ClosedChannelException))
+                    throw new RuntimeException("Cause of ClosedChannelException expected");
+            }
+            final AtomicReference<Throwable> connectException = new AtomicReference<>();
+            ch.connect(server.address(), (Void)null, new CompletionHandler<Void,Void>() {
+                public void completed(Void result, Void att) {
+                }
+                public void failed(Throwable exc, Void att) {
+                    connectException.set(exc);
+                }
+            });
+            while (connectException.get() == null) {
+                Thread.sleep(100);
+            }
+            if (!(connectException.get() instanceof ClosedChannelException))
+                throw new RuntimeException("ClosedChannelException expected");
         }
-        final AtomicReference<Throwable> connectException =
-            new AtomicReference<Throwable>();
-        ch.connect(server.address(), (Void)null, new CompletionHandler<Void,Void>() {
-            public void completed(Void result, Void att) {
-            }
-            public void failed(Throwable exc, Void att) {
-                connectException.set(exc);
-            }
-        });
-        while (connectException.get() == null) {
-            Thread.sleep(100);
-        }
-        if (!(connectException.get() instanceof ClosedChannelException))
-            throw new RuntimeException("ClosedChannelException expected");
-
-        System.out.println("-- connect to non-existent host --");
 
         // test that failure to connect closes the channel
-        ch = AsynchronousSocketChannel.open();
-        try {
-            ch.connect(genSocketAddress()).get();
-        } catch (ExecutionException x) {
-            // failed to establish connection
-            if (ch.isOpen())
-                throw new RuntimeException("Channel should be closed");
-        } finally {
-            ch.close();
+        try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {
+            try {
+                ch.connect(address).get();
+            } catch (ExecutionException x) {
+                // failed to establish connection
+                if (ch.isOpen())
+                    throw new RuntimeException("Channel should be closed");
+            }
         }
 
-        server.close();
+        // repeat test by connecting to a (probably) non-existent host. This
+        // improves the chance that the connect will not fail immediately.
+        if (!skipSlowConnectTest) {
+            try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {
+                try {
+                    ch.connect(genSocketAddress()).get();
+                } catch (ExecutionException x) {
+                    // failed to establish connection
+                    if (ch.isOpen())
+                        throw new RuntimeException("Channel should be closed");
+                }
+            }
+        }
     }
 
     static void testCloseWhenPending() throws Exception {
@@ -249,466 +275,460 @@
 
         System.out.println("-- asynchronous close when reading --");
 
-        Server server = new Server();
-        ch = AsynchronousSocketChannel.open();
-        ch.connect(server.address()).get();
+        try (Server server = new Server()) {
+            ch = AsynchronousSocketChannel.open();
+            ch.connect(server.address()).get();
 
-        ByteBuffer dst = ByteBuffer.allocateDirect(100);
-        Future<Integer> result = ch.read(dst);
+            ByteBuffer dst = ByteBuffer.allocateDirect(100);
+            Future<Integer> result = ch.read(dst);
 
-        // attempt a second read - should fail with ReadPendingException
-        ByteBuffer buf = ByteBuffer.allocateDirect(100);
-        try {
-            ch.read(buf);
-            throw new RuntimeException("ReadPendingException expected");
-        } catch (ReadPendingException x) {
-        }
+            // attempt a second read - should fail with ReadPendingException
+            ByteBuffer buf = ByteBuffer.allocateDirect(100);
+            try {
+                ch.read(buf);
+                throw new RuntimeException("ReadPendingException expected");
+            } catch (ReadPendingException x) {
+            }
 
-        // close channel (should cause initial read to complete)
-        ch.close();
+            // close channel (should cause initial read to complete)
+            ch.close();
+            server.accept().close();
 
-        // check that AsynchronousCloseException is thrown
-        try {
-            result.get();
-            throw new RuntimeException("Should not read");
-        } catch (ExecutionException x) {
-            if (!(x.getCause() instanceof AsynchronousCloseException))
-                throw new RuntimeException(x);
-        }
+            // check that AsynchronousCloseException is thrown
+            try {
+                result.get();
+                throw new RuntimeException("Should not read");
+            } catch (ExecutionException x) {
+                if (!(x.getCause() instanceof AsynchronousCloseException))
+                    throw new RuntimeException(x);
+            }
 
-        System.out.println("-- asynchronous close when writing --");
+            System.out.println("-- asynchronous close when writing --");
 
-        ch = AsynchronousSocketChannel.open();
-        ch.connect(server.address()).get();
+            ch = AsynchronousSocketChannel.open();
+            ch.connect(server.address()).get();
 
-        final AtomicReference<Throwable> writeException =
-            new AtomicReference<Throwable>();
+            final AtomicReference<Throwable> writeException =
+                new AtomicReference<Throwable>();
 
-        // write bytes to fill socket buffer
-        ch.write(genBuffer(), ch, new CompletionHandler<Integer,AsynchronousSocketChannel>() {
-            public void completed(Integer result, AsynchronousSocketChannel ch) {
-                ch.write(genBuffer(), ch, this);
-            }
-            public void failed(Throwable x, AsynchronousSocketChannel ch) {
-                writeException.set(x);
-            }
-        });
+            // write bytes to fill socket buffer
+            ch.write(genBuffer(), ch, new CompletionHandler<Integer,AsynchronousSocketChannel>() {
+                public void completed(Integer result, AsynchronousSocketChannel ch) {
+                    ch.write(genBuffer(), ch, this);
+                }
+                public void failed(Throwable x, AsynchronousSocketChannel ch) {
+                    writeException.set(x);
+                }
+            });
 
-        // give time for socket buffer to fill up.
-        Thread.sleep(5*1000);
+            // give time for socket buffer to fill up.
+            Thread.sleep(5*1000);
 
-        //  attempt a concurrent write - should fail with WritePendingException
-        try {
-            ch.write(genBuffer());
-            throw new RuntimeException("WritePendingException expected");
-        } catch (WritePendingException x) {
-        }
+            //  attempt a concurrent write - should fail with WritePendingException
+            try {
+                ch.write(genBuffer());
+                throw new RuntimeException("WritePendingException expected");
+            } catch (WritePendingException x) {
+            }
 
-        // close channel - should cause initial write to complete
-        ch.close();
+            // close channel - should cause initial write to complete
+            ch.close();
+            server.accept().close();
 
-        // wait for exception
-        while (writeException.get() == null) {
-            Thread.sleep(100);
+            // wait for exception
+            while (writeException.get() == null) {
+                Thread.sleep(100);
+            }
+            if (!(writeException.get() instanceof AsynchronousCloseException))
+                throw new RuntimeException("AsynchronousCloseException expected");
         }
-        if (!(writeException.get() instanceof AsynchronousCloseException))
-            throw new RuntimeException("AsynchronousCloseException expected");
-
-        server.close();
     }
 
     static void testCancel() throws Exception {
         System.out.println("-- cancel --");
 
-        Server server = new Server();
-
-        for (int i=0; i<2; i++) {
-            boolean mayInterruptIfRunning = (i == 0) ? false : true;
+        try (Server server = new Server()) {
+            for (int i=0; i<2; i++) {
+                boolean mayInterruptIfRunning = (i == 0) ? false : true;
 
-            // establish loopback connection
-            AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
-            ch.connect(server.address()).get();
-            SocketChannel peer = server.accept();
+                // establish loopback connection
+                AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
+                ch.connect(server.address()).get();
+                SocketChannel peer = server.accept();
 
-            // start read operation
-            ByteBuffer buf = ByteBuffer.allocate(1);
-            Future<Integer> res = ch.read(buf);
+                // start read operation
+                ByteBuffer buf = ByteBuffer.allocate(1);
+                Future<Integer> res = ch.read(buf);
 
-            // cancel operation
-            boolean cancelled = res.cancel(mayInterruptIfRunning);
+                // cancel operation
+                boolean cancelled = res.cancel(mayInterruptIfRunning);
 
-            // check post-conditions
-            if (!res.isDone())
-                throw new RuntimeException("isDone should return true");
-            if (res.isCancelled() != cancelled)
-                throw new RuntimeException("isCancelled not consistent");
-            try {
-                res.get();
-                throw new RuntimeException("CancellationException expected");
-            } catch (CancellationException x) {
+                // check post-conditions
+                if (!res.isDone())
+                    throw new RuntimeException("isDone should return true");
+                if (res.isCancelled() != cancelled)
+                    throw new RuntimeException("isCancelled not consistent");
+                try {
+                    res.get();
+                    throw new RuntimeException("CancellationException expected");
+                } catch (CancellationException x) {
+                }
+                try {
+                    res.get(1, TimeUnit.SECONDS);
+                    throw new RuntimeException("CancellationException expected");
+                } catch (CancellationException x) {
+                }
+
+                // check that the cancel doesn't impact writing to the channel
+                if (!mayInterruptIfRunning) {
+                    buf = ByteBuffer.wrap("a".getBytes());
+                    ch.write(buf).get();
+                }
+
+                ch.close();
+                peer.close();
             }
-            try {
-                res.get(1, TimeUnit.SECONDS);
-                throw new RuntimeException("CancellationException expected");
-            } catch (CancellationException x) {
-            }
-
-            // check that the cancel doesn't impact writing to the channel
-            if (!mayInterruptIfRunning) {
-                buf = ByteBuffer.wrap("a".getBytes());
-                ch.write(buf).get();
-            }
-
-            ch.close();
-            peer.close();
         }
-
-        server.close();
     }
 
     static void testRead1() throws Exception {
         System.out.println("-- read (1) --");
 
-        Server server = new Server();
-        final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
-        ch.connect(server.address()).get();
+        try (Server server = new Server()) {
+            final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
+            ch.connect(server.address()).get();
 
-        // read with 0 bytes remaining should complete immediately
-        ByteBuffer buf = ByteBuffer.allocate(1);
-        buf.put((byte)0);
-        int n = ch.read(buf).get();
-        if (n != 0)
-            throw new RuntimeException("0 expected");
+            // read with 0 bytes remaining should complete immediately
+            ByteBuffer buf = ByteBuffer.allocate(1);
+            buf.put((byte)0);
+            int n = ch.read(buf).get();
+            if (n != 0)
+                throw new RuntimeException("0 expected");
 
-        // write bytes and close connection
-        SocketChannel sc = server.accept();
-        ByteBuffer src = genBuffer();
-        sc.setOption(StandardSocketOptions.SO_SNDBUF, src.remaining());
-        while (src.hasRemaining())
-            sc.write(src);
-        sc.close();
+            // write bytes and close connection
+            ByteBuffer src = genBuffer();
+            try (SocketChannel sc = server.accept()) {
+                sc.setOption(SO_SNDBUF, src.remaining());
+                while (src.hasRemaining())
+                    sc.write(src);
+            }
 
-        // reads should complete immediately
-        final ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity() + 100);
-        final CountDownLatch latch = new CountDownLatch(1);
-        ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() {
-            public void completed(Integer result, Void att) {
-                int n = result;
-                if (n > 0) {
-                    ch.read(dst, (Void)null, this);
-                } else {
-                    latch.countDown();
+            // reads should complete immediately
+            final ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity() + 100);
+            final CountDownLatch latch = new CountDownLatch(1);
+            ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() {
+                public void completed(Integer result, Void att) {
+                    int n = result;
+                    if (n > 0) {
+                        ch.read(dst, (Void)null, this);
+                    } else {
+                        latch.countDown();
+                    }
                 }
-            }
-            public void failed(Throwable exc, Void att) {
-            }
-        });
+                public void failed(Throwable exc, Void att) {
+                }
+            });
 
-        latch.await();
+            latch.await();
 
-        // check buffers
-        src.flip();
-        dst.flip();
-        if (!src.equals(dst)) {
-            throw new RuntimeException("Contents differ");
-        }
+            // check buffers
+            src.flip();
+            dst.flip();
+            if (!src.equals(dst)) {
+                throw new RuntimeException("Contents differ");
+            }
 
-        // close channel
-        ch.close();
+            // close channel
+            ch.close();
 
-        // check read fails with ClosedChannelException
-        try {
-            ch.read(dst).get();
-            throw new RuntimeException("ExecutionException expected");
-        } catch (ExecutionException x) {
-            if (!(x.getCause() instanceof ClosedChannelException))
-                throw new RuntimeException("Cause of ClosedChannelException expected");
+            // check read fails with ClosedChannelException
+            try {
+                ch.read(dst).get();
+                throw new RuntimeException("ExecutionException expected");
+            } catch (ExecutionException x) {
+                if (!(x.getCause() instanceof ClosedChannelException))
+                    throw new RuntimeException("Cause of ClosedChannelException expected");
+            }
         }
-
-        server.close();
     }
 
     static void testRead2() throws Exception {
         System.out.println("-- read (2) --");
 
-        Server server = new Server();
+        try (Server server = new Server()) {
+            final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
+            ch.connect(server.address()).get();
+            SocketChannel sc = server.accept();
 
-        final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
-        ch.connect(server.address()).get();
-        SocketChannel sc = server.accept();
-
-        ByteBuffer src = genBuffer();
+            ByteBuffer src = genBuffer();
 
-        // read until the buffer is full
-        final ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity());
-        final CountDownLatch latch = new CountDownLatch(1);
-        ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() {
-            public void completed(Integer result, Void att) {
-                if (dst.hasRemaining()) {
-                    ch.read(dst, (Void)null, this);
-                } else {
-                    latch.countDown();
+            // read until the buffer is full
+            final ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity());
+            final CountDownLatch latch = new CountDownLatch(1);
+            ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() {
+                public void completed(Integer result, Void att) {
+                    if (dst.hasRemaining()) {
+                        ch.read(dst, (Void)null, this);
+                    } else {
+                        latch.countDown();
+                    }
                 }
-            }
-            public void failed(Throwable exc, Void att) {
-            }
-        });
+                public void failed(Throwable exc, Void att) {
+                }
+            });
 
-        // trickle the writing
-        do {
-            int rem = src.remaining();
-            int size = (rem <= 100) ? rem : 50 + rand.nextInt(rem - 100);
-            ByteBuffer buf = ByteBuffer.allocate(size);
-            for (int i=0; i<size; i++)
-                buf.put(src.get());
-            buf.flip();
-            Thread.sleep(50 + rand.nextInt(1500));
-            while (buf.hasRemaining())
-                sc.write(buf);
-        } while (src.hasRemaining());
+            // trickle the writing
+            do {
+                int rem = src.remaining();
+                int size = (rem <= 100) ? rem : 50 + rand.nextInt(rem - 100);
+                ByteBuffer buf = ByteBuffer.allocate(size);
+                for (int i=0; i<size; i++)
+                    buf.put(src.get());
+                buf.flip();
+                Thread.sleep(50 + rand.nextInt(1500));
+                while (buf.hasRemaining())
+                    sc.write(buf);
+            } while (src.hasRemaining());
 
-        // wait until ascynrhonous reading has completed
-        latch.await();
+            // wait until ascynrhonous reading has completed
+            latch.await();
 
-        // check buffers
-        src.flip();
-        dst.flip();
-        if (!src.equals(dst)) {
-           throw new RuntimeException("Contents differ");
+            // check buffers
+            src.flip();
+            dst.flip();
+            if (!src.equals(dst)) {
+               throw new RuntimeException("Contents differ");
+            }
+
+            sc.close();
+            ch.close();
         }
-
-        sc.close();
-        ch.close();
-        server.close();
     }
 
     // exercise scattering read
     static void testRead3() throws Exception {
         System.out.println("-- read (3) --");
 
-        Server server = new Server();
-        final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
-        ch.connect(server.address()).get();
-        SocketChannel sc = server.accept();
+        try (Server server = new Server()) {
+            final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
+            ch.connect(server.address()).get();
+            SocketChannel sc = server.accept();
 
-        ByteBuffer[] dsts = new ByteBuffer[3];
-        for (int i=0; i<dsts.length; i++) {
-            dsts[i] = ByteBuffer.allocateDirect(100);
-        }
+            ByteBuffer[] dsts = new ByteBuffer[3];
+            for (int i=0; i<dsts.length; i++) {
+                dsts[i] = ByteBuffer.allocateDirect(100);
+            }
 
-        // scattering read that completes ascynhronously
-        final CountDownLatch l1 = new CountDownLatch(1);
-        ch.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, (Void)null,
-            new CompletionHandler<Long,Void>() {
-                public void completed(Long result, Void att) {
-                    long n = result;
-                    if (n <= 0)
-                        throw new RuntimeException("No bytes read");
-                    l1.countDown();
-                }
-                public void failed(Throwable exc, Void att) {
-                }
-        });
+            // scattering read that completes ascynhronously
+            final CountDownLatch l1 = new CountDownLatch(1);
+            ch.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, (Void)null,
+                new CompletionHandler<Long,Void>() {
+                    public void completed(Long result, Void att) {
+                        long n = result;
+                        if (n <= 0)
+                            throw new RuntimeException("No bytes read");
+                        l1.countDown();
+                    }
+                    public void failed(Throwable exc, Void att) {
+                    }
+            });
 
-        // write some bytes
-        sc.write(genBuffer());
+            // write some bytes
+            sc.write(genBuffer());
 
-        // read should now complete
-        l1.await();
+            // read should now complete
+            l1.await();
 
-        // write more bytes
-        sc.write(genBuffer());
+            // write more bytes
+            sc.write(genBuffer());
 
-        // read should complete immediately
-        for (int i=0; i<dsts.length; i++) {
-            dsts[i].rewind();
-        }
+            // read should complete immediately
+            for (int i=0; i<dsts.length; i++) {
+                dsts[i].rewind();
+            }
 
-        final CountDownLatch l2 = new CountDownLatch(1);
-        ch.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, (Void)null,
-            new CompletionHandler<Long,Void>() {
-                public void completed(Long result, Void att) {
-                    long n = result;
-                    if (n <= 0)
-                        throw new RuntimeException("No bytes read");
-                    l2.countDown();
-                }
-                public void failed(Throwable exc, Void att) {
-                }
-        });
-        l2.await();
+            final CountDownLatch l2 = new CountDownLatch(1);
+            ch.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, (Void)null,
+                new CompletionHandler<Long,Void>() {
+                    public void completed(Long result, Void att) {
+                        long n = result;
+                        if (n <= 0)
+                            throw new RuntimeException("No bytes read");
+                        l2.countDown();
+                    }
+                    public void failed(Throwable exc, Void att) {
+                    }
+            });
+            l2.await();
 
-        ch.close();
-        sc.close();
-        server.close();
+            ch.close();
+            sc.close();
+        }
     }
 
     static void testWrite1() throws Exception {
         System.out.println("-- write (1) --");
 
-        Server server = new Server();
-        final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
-        ch.connect(server.address()).get();
-        SocketChannel sc = server.accept();
+        try (Server server = new Server()) {
+            final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
+            ch.connect(server.address()).get();
+            SocketChannel sc = server.accept();
 
-        // write with 0 bytes remaining should complete immediately
-        ByteBuffer buf = ByteBuffer.allocate(1);
-        buf.put((byte)0);
-        int n = ch.write(buf).get();
-        if (n != 0)
-            throw new RuntimeException("0 expected");
+            // write with 0 bytes remaining should complete immediately
+            ByteBuffer buf = ByteBuffer.allocate(1);
+            buf.put((byte)0);
+            int n = ch.write(buf).get();
+            if (n != 0)
+                throw new RuntimeException("0 expected");
 
-        // write all bytes and close connection when done
-        final ByteBuffer src = genBuffer();
-        ch.write(src, (Void)null, new CompletionHandler<Integer,Void>() {
-            public void completed(Integer result, Void att) {
-                if (src.hasRemaining()) {
-                    ch.write(src, (Void)null, this);
-                } else {
-                    try {
-                        ch.close();
-                    } catch (IOException ignore) { }
+            // write all bytes and close connection when done
+            final ByteBuffer src = genBuffer();
+            ch.write(src, (Void)null, new CompletionHandler<Integer,Void>() {
+                public void completed(Integer result, Void att) {
+                    if (src.hasRemaining()) {
+                        ch.write(src, (Void)null, this);
+                    } else {
+                        try {
+                            ch.close();
+                        } catch (IOException ignore) { }
+                    }
+                }
+                public void failed(Throwable exc, Void att) {
                 }
-            }
-            public void failed(Throwable exc, Void att) {
+            });
+
+            // read to EOF or buffer full
+            ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity() + 100);
+            do {
+                n = sc.read(dst);
+            } while (n > 0);
+            sc.close();
+
+            // check buffers
+            src.flip();
+            dst.flip();
+            if (!src.equals(dst)) {
+                throw new RuntimeException("Contents differ");
             }
-        });
 
-        // read to EOF or buffer full
-        ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity() + 100);
-        do {
-            n = sc.read(dst);
-        } while (n > 0);
-        sc.close();
-
-        // check buffers
-        src.flip();
-        dst.flip();
-        if (!src.equals(dst)) {
-            throw new RuntimeException("Contents differ");
+            // check write fails with ClosedChannelException
+            try {
+                ch.read(dst).get();
+                throw new RuntimeException("ExecutionException expected");
+            } catch (ExecutionException x) {
+                if (!(x.getCause() instanceof ClosedChannelException))
+                    throw new RuntimeException("Cause of ClosedChannelException expected");
+            }
         }
-
-        // check write fails with ClosedChannelException
-        try {
-            ch.read(dst).get();
-            throw new RuntimeException("ExecutionException expected");
-        } catch (ExecutionException x) {
-            if (!(x.getCause() instanceof ClosedChannelException))
-                throw new RuntimeException("Cause of ClosedChannelException expected");
-        }
-
-        server.close();
     }
 
     // exercise gathering write
     static void testWrite2() throws Exception {
         System.out.println("-- write (2) --");
 
-        Server server = new Server();
-        final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
-        ch.connect(server.address()).get();
-        SocketChannel sc = server.accept();
+        try (Server server = new Server()) {
+            final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
+            ch.connect(server.address()).get();
+            SocketChannel sc = server.accept();
 
-        // number of bytes written
-        final AtomicLong bytesWritten = new AtomicLong(0);
+            // number of bytes written
+            final AtomicLong bytesWritten = new AtomicLong(0);
 
-        // write buffers (should complete immediately)
-        ByteBuffer[] srcs = genBuffers(1);
-        final CountDownLatch l1 = new CountDownLatch(1);
-        ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, (Void)null,
-            new CompletionHandler<Long,Void>() {
-                public void completed(Long result, Void att) {
-                    long n = result;
-                    if (n <= 0)
-                        throw new RuntimeException("No bytes read");
-                    bytesWritten.addAndGet(n);
-                    l1.countDown();
-                }
-                public void failed(Throwable exc, Void att) {
-                }
-        });
-        l1.await();
+            // write buffers (should complete immediately)
+            ByteBuffer[] srcs = genBuffers(1);
+            final CountDownLatch l1 = new CountDownLatch(1);
+            ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, (Void)null,
+                new CompletionHandler<Long,Void>() {
+                    public void completed(Long result, Void att) {
+                        long n = result;
+                        if (n <= 0)
+                            throw new RuntimeException("No bytes read");
+                        bytesWritten.addAndGet(n);
+                        l1.countDown();
+                    }
+                    public void failed(Throwable exc, Void att) {
+                    }
+            });
+            l1.await();
 
-        // set to true to signal that no more buffers should be written
-        final AtomicBoolean continueWriting = new AtomicBoolean(true);
+            // set to true to signal that no more buffers should be written
+            final AtomicBoolean continueWriting = new AtomicBoolean(true);
 
-        // write until socket buffer is full so as to create the conditions
-        // for when a write does not complete immediately
-        srcs = genBuffers(1);
-        ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, (Void)null,
-            new CompletionHandler<Long,Void>() {
-                public void completed(Long result, Void att) {
-                    long n = result;
-                    if (n <= 0)
-                        throw new RuntimeException("No bytes written");
-                    bytesWritten.addAndGet(n);
-                    if (continueWriting.get()) {
-                        ByteBuffer[] srcs = genBuffers(8);
-                        ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS,
-                            (Void)null, this);
+            // write until socket buffer is full so as to create the conditions
+            // for when a write does not complete immediately
+            srcs = genBuffers(1);
+            ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, (Void)null,
+                new CompletionHandler<Long,Void>() {
+                    public void completed(Long result, Void att) {
+                        long n = result;
+                        if (n <= 0)
+                            throw new RuntimeException("No bytes written");
+                        bytesWritten.addAndGet(n);
+                        if (continueWriting.get()) {
+                            ByteBuffer[] srcs = genBuffers(8);
+                            ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS,
+                                (Void)null, this);
+                        }
                     }
-                }
-                public void failed(Throwable exc, Void att) {
-                }
-        });
+                    public void failed(Throwable exc, Void att) {
+                    }
+            });
 
-        // give time for socket buffer to fill up.
-        Thread.sleep(5*1000);
+            // give time for socket buffer to fill up.
+            Thread.sleep(5*1000);
 
-        // signal handler to stop further writing
-        continueWriting.set(false);
+            // signal handler to stop further writing
+            continueWriting.set(false);
 
-        // read until done
-        ByteBuffer buf = ByteBuffer.allocateDirect(4096);
-        long total = 0L;
-        do {
-            int n = sc.read(buf);
-            if (n <= 0)
-                throw new RuntimeException("No bytes read");
-            buf.rewind();
-            total += n;
-        } while (total < bytesWritten.get());
+            // read until done
+            ByteBuffer buf = ByteBuffer.allocateDirect(4096);
+            long total = 0L;
+            do {
+                int n = sc.read(buf);
+                if (n <= 0)
+                    throw new RuntimeException("No bytes read");
+                buf.rewind();
+                total += n;
+            } while (total < bytesWritten.get());
 
-        ch.close();
-        sc.close();
-        server.close();
+            ch.close();
+            sc.close();
+        }
     }
 
     static void testShutdown() throws Exception {
         System.out.println("-- shutdown--");
 
-        Server server = new Server();
-        AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
-        ch.connect(server.address()).get();
-        SocketChannel sc = server.accept();
-
-        ByteBuffer buf = ByteBuffer.allocateDirect(1000);
-        int n;
+        try (Server server = new Server();
+             AsynchronousSocketChannel ch = AsynchronousSocketChannel.open())
+        {
+            ch.connect(server.address()).get();
+            try (SocketChannel peer = server.accept()) {
+                ByteBuffer buf = ByteBuffer.allocateDirect(1000);
+                int n;
 
-        // check read
-        ch.shutdownInput();
-        n = ch.read(buf).get();
-        if (n != -1)
-            throw new RuntimeException("-1 expected");
-        // check full with full buffer
-        buf.put(new byte[100]);
-        n = ch.read(buf).get();
-        if (n != -1)
-            throw new RuntimeException("-1 expected");
+                // check read
+                ch.shutdownInput();
+                n = ch.read(buf).get();
+                if (n != -1)
+                    throw new RuntimeException("-1 expected");
+                // check full with full buffer
+                buf.put(new byte[100]);
+                n = ch.read(buf).get();
+                if (n != -1)
+                    throw new RuntimeException("-1 expected");
 
-        // check write
-        ch.shutdownOutput();
-        try {
-            ch.write(buf).get();
-            throw new RuntimeException("ClosedChannelException expected");
-        } catch (ExecutionException x) {
-            if (!(x.getCause() instanceof ClosedChannelException))
-                throw new RuntimeException("ClosedChannelException expected");
+                // check write
+                ch.shutdownOutput();
+                try {
+                    ch.write(buf).get();
+                    throw new RuntimeException("ClosedChannelException expected");
+                } catch (ExecutionException x) {
+                    if (!(x.getCause() instanceof ClosedChannelException))
+                        throw new RuntimeException("ClosedChannelException expected");
+                }
+            }
         }
-
-        sc.close();
-        ch.close();
-        server.close();
     }
 
     static void testTimeout() throws Exception {
@@ -720,88 +740,88 @@
     }
 
     static void testTimeout(final long timeout, final TimeUnit unit) throws Exception {
-        Server server = new Server();
-        AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
-        ch.connect(server.address()).get();
+        try (Server server = new Server()) {
+            AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
+            ch.connect(server.address()).get();
 
-        ByteBuffer dst = ByteBuffer.allocate(512);
+            ByteBuffer dst = ByteBuffer.allocate(512);
 
-        final AtomicReference<Throwable> readException = new AtomicReference<Throwable>();
+            final AtomicReference<Throwable> readException = new AtomicReference<Throwable>();
 
-        // this read should timeout if value is > 0
-        ch.read(dst, timeout, unit, null, new CompletionHandler<Integer,Void>() {
-            public void completed(Integer result, Void att) {
-                readException.set(new RuntimeException("Should not complete"));
-            }
-            public void failed(Throwable exc, Void att) {
-                readException.set(exc);
+            // this read should timeout if value is > 0
+            ch.read(dst, timeout, unit, null, new CompletionHandler<Integer,Void>() {
+                public void completed(Integer result, Void att) {
+                    readException.set(new RuntimeException("Should not complete"));
+                }
+                public void failed(Throwable exc, Void att) {
+                    readException.set(exc);
+                }
+            });
+            if (timeout > 0L) {
+                // wait for exception
+                while (readException.get() == null) {
+                    Thread.sleep(100);
+                }
+                if (!(readException.get() instanceof InterruptedByTimeoutException))
+                    throw new RuntimeException("InterruptedByTimeoutException expected");
+
+                // after a timeout then further reading should throw unspecified runtime exception
+                boolean exceptionThrown = false;
+                try {
+                    ch.read(dst);
+                } catch (RuntimeException x) {
+                    exceptionThrown = true;
+                }
+                if (!exceptionThrown)
+                    throw new RuntimeException("RuntimeException expected after timeout.");
+            } else {
+                Thread.sleep(1000);
+                Throwable exc = readException.get();
+                if (exc != null)
+                    throw new RuntimeException(exc);
             }
-        });
-        if (timeout > 0L) {
-            // wait for exception
-            while (readException.get() == null) {
-                Thread.sleep(100);
-            }
-            if (!(readException.get() instanceof InterruptedByTimeoutException))
-                throw new RuntimeException("InterruptedByTimeoutException expected");
-
-            // after a timeout then further reading should throw unspecified runtime exception
-            boolean exceptionThrown = false;
-            try {
-                ch.read(dst);
-            } catch (RuntimeException x) {
-                exceptionThrown = true;
-            }
-            if (!exceptionThrown)
-                throw new RuntimeException("RuntimeException expected after timeout.");
-        } else {
-            Thread.sleep(1000);
-            Throwable exc = readException.get();
-            if (exc != null)
-                throw new RuntimeException(exc);
-        }
 
-        final AtomicReference<Throwable> writeException = new AtomicReference<Throwable>();
+            final AtomicReference<Throwable> writeException = new AtomicReference<Throwable>();
 
-        // write bytes to fill socket buffer
-        ch.write(genBuffer(), timeout, unit, ch,
-            new CompletionHandler<Integer,AsynchronousSocketChannel>()
-        {
-            public void completed(Integer result, AsynchronousSocketChannel ch) {
-                ch.write(genBuffer(), timeout, unit, ch, this);
-            }
-            public void failed(Throwable exc, AsynchronousSocketChannel ch) {
-                writeException.set(exc);
-            }
-        });
-        if (timeout > 0) {
-            // wait for exception
-            while (writeException.get() == null) {
-                Thread.sleep(100);
-            }
-            if (!(writeException.get() instanceof InterruptedByTimeoutException))
-                throw new RuntimeException("InterruptedByTimeoutException expected");
+            // write bytes to fill socket buffer
+            ch.write(genBuffer(), timeout, unit, ch,
+                new CompletionHandler<Integer,AsynchronousSocketChannel>()
+            {
+                public void completed(Integer result, AsynchronousSocketChannel ch) {
+                    ch.write(genBuffer(), timeout, unit, ch, this);
+                }
+                public void failed(Throwable exc, AsynchronousSocketChannel ch) {
+                    writeException.set(exc);
+                }
+            });
+            if (timeout > 0) {
+                // wait for exception
+                while (writeException.get() == null) {
+                    Thread.sleep(100);
+                }
+                if (!(writeException.get() instanceof InterruptedByTimeoutException))
+                    throw new RuntimeException("InterruptedByTimeoutException expected");
 
-            // after a timeout then further writing should throw unspecified runtime exception
-            boolean exceptionThrown = false;
-            try {
-                ch.write(genBuffer());
-            } catch (RuntimeException x) {
-                exceptionThrown = true;
+                // after a timeout then further writing should throw unspecified runtime exception
+                boolean exceptionThrown = false;
+                try {
+                    ch.write(genBuffer());
+                } catch (RuntimeException x) {
+                    exceptionThrown = true;
+                }
+                if (!exceptionThrown)
+                    throw new RuntimeException("RuntimeException expected after timeout.");
+            } else {
+                Thread.sleep(1000);
+                Throwable exc = writeException.get();
+                if (exc != null)
+                    throw new RuntimeException(exc);
             }
-            if (!exceptionThrown)
-                throw new RuntimeException("RuntimeException expected after timeout.");
-        } else {
-            Thread.sleep(1000);
-            Throwable exc = writeException.get();
-            if (exc != null)
-                throw new RuntimeException(exc);
+
+            // clean-up
+            server.accept().close();
+            ch.close();
         }
-
-        // clean-up
-        server.accept().close();
-        ch.close();
-        server.close();
     }
 
     // returns ByteBuffer with random bytes
--- a/test/java/nio/channels/AsynchronousSocketChannel/Leaky.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/AsynchronousSocketChannel/Leaky.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,9 +22,9 @@
  */
 
 /* @test
- * @bug 4607272 6999915
+ * @bug 4607272 6999915 7185340
  * @summary Unit test for AsynchronousSocketChannel
- * @run main/othervm -XX:+DisableExplicitGC -XX:MaxDirectMemorySize=64m Leaky
+ * @run main/othervm -XX:+DisableExplicitGC -XX:MaxDirectMemorySize=75m Leaky
  */
 
 import java.nio.ByteBuffer;
--- a/test/java/nio/channels/DatagramChannel/AdaptDatagramSocket.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/DatagramChannel/AdaptDatagramSocket.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,29 +27,16 @@
  * @library ..
  */
 
-import java.io.*;
 import java.net.*;
-import java.nio.*;
 import java.nio.channels.*;
-import java.nio.charset.*;
 import java.util.*;
 
 
 public class AdaptDatagramSocket {
 
     static java.io.PrintStream out = System.out;
-
     static Random rand = new Random();
 
-    static final int ECHO_PORT = 7;
-    static final int DISCARD_PORT = 9;
-    static final String REMOTE_HOST = TestUtil.HOST;
-
-    static final InetSocketAddress echoAddress
-        = new InetSocketAddress(REMOTE_HOST, ECHO_PORT);
-    static final InetSocketAddress discardAddress
-        = new InetSocketAddress(REMOTE_HOST, DISCARD_PORT);
-
     static String toString(DatagramPacket dp) {
         return ("DatagramPacket[off=" + dp.getOffset()
                 + ", len=" + dp.getLength()
@@ -88,10 +75,11 @@
         out.println("rtt: " + (System.currentTimeMillis() - start));
         out.println("post op: " + toString(op) + "  ip: " + toString(ip));
 
-        for (int i = 0; i < ip.getLength(); i++)
+        for (int i = 0; i < ip.getLength(); i++) {
             if (ip.getData()[ip.getOffset() + i]
                 != op.getData()[op.getOffset() + i])
                 throw new Exception("Incorrect data received");
+        }
 
         if (!(ip.getSocketAddress().equals(dst))) {
             throw new Exception("Incorrect sender address, expected: " + dst
@@ -130,8 +118,9 @@
             ds.setSoTimeout(timeout);
         out.println("timeout: " + ds.getSoTimeout());
 
-        for (int i = 0; i < 5; i++)
+        for (int i = 0; i < 5; i++) {
             test(ds, dst, shouldTimeout);
+        }
 
         // Leave the socket open so that we don't reuse the old src address
         //ds.close();
@@ -139,10 +128,23 @@
     }
 
     public static void main(String[] args) throws Exception {
-        test(echoAddress, 0, false, false);
-        test(echoAddress, 0, false, true);
-        test(echoAddress, 5000, false, false);
-        test(discardAddress, 10, true, false);
+        // need an UDP echo server
+        try (TestServers.UdpEchoServer echoServer
+                = TestServers.UdpEchoServer.startNewServer(100)) {
+            final InetSocketAddress address
+                = new InetSocketAddress(echoServer.getAddress(),
+                                        echoServer.getPort());
+            test(address, 0, false, false);
+            test(address, 0, false, true);
+            test(address, 5000, false, false);
+        }
+        try (TestServers.UdpDiscardServer discardServer
+                = TestServers.UdpDiscardServer.startNewServer()) {
+            final InetSocketAddress address
+                = new InetSocketAddress(discardServer.getAddress(),
+                                        discardServer.getPort());
+            test(address, 10, true, false);
+        }
     }
 
 }
--- a/test/java/nio/channels/DatagramChannel/IsBound.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/DatagramChannel/IsBound.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,21 +34,25 @@
 
 public class IsBound {
     public static void main(String argv[]) throws Exception {
-        InetSocketAddress isa = new InetSocketAddress(
-            InetAddress.getByName(TestUtil.HOST), 13);
-        ByteBuffer bb = ByteBuffer.allocateDirect(256);
-        bb.put("hello".getBytes());
-        bb.flip();
+        try (TestServers.UdpDayTimeServer daytimeServer
+                = TestServers.UdpDayTimeServer.startNewServer(100)) {
+            InetSocketAddress isa = new InetSocketAddress(
+                daytimeServer.getAddress(),
+                daytimeServer.getPort());
+            ByteBuffer bb = ByteBuffer.allocateDirect(256);
+            bb.put("hello".getBytes());
+            bb.flip();
 
-        DatagramChannel dc = DatagramChannel.open();
-        dc.send(bb, isa);
-        if(!dc.socket().isBound())
-            throw new Exception("Test failed");
-        dc.close();
+            DatagramChannel dc = DatagramChannel.open();
+            dc.send(bb, isa);
+            if(!dc.socket().isBound())
+                throw new Exception("Test failed");
+            dc.close();
 
-        dc = DatagramChannel.open();
-        if(dc.socket().isBound())
-            throw new Exception("Test failed");
-        dc.close();
+            dc = DatagramChannel.open();
+            if(dc.socket().isBound())
+                throw new Exception("Test failed");
+            dc.close();
+        }
     }
 }
--- a/test/java/nio/channels/DatagramChannel/IsConnected.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/DatagramChannel/IsConnected.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,21 +28,23 @@
  */
 
 import java.net.*;
-import java.nio.*;
 import java.nio.channels.*;
 
 
 public class IsConnected {
     public static void main(String argv[]) throws Exception {
-        InetSocketAddress isa = new InetSocketAddress(
-            InetAddress.getByName(TestUtil.HOST), 13);
-        DatagramChannel dc = DatagramChannel.open();
-        dc.configureBlocking(true);
-        dc.connect(isa);
-        if  (!dc.isConnected())
-            throw new RuntimeException("channel.isConnected inconsistent");
-        if (!dc.socket().isConnected())
-            throw new RuntimeException("socket.isConnected inconsistent");
-        dc.close();
+        try (TestServers.UdpDayTimeServer daytimeServer
+                = TestServers.UdpDayTimeServer.startNewServer(100)) {
+            InetSocketAddress isa = new InetSocketAddress(
+                daytimeServer.getAddress(), daytimeServer.getPort());
+            DatagramChannel dc = DatagramChannel.open();
+            dc.configureBlocking(true);
+            dc.connect(isa);
+            if  (!dc.isConnected())
+                throw new RuntimeException("channel.isConnected inconsistent");
+            if (!dc.socket().isConnected())
+                throw new RuntimeException("socket.isConnected inconsistent");
+            dc.close();
+        }
     }
 }
--- a/test/java/nio/channels/Selector/Alias.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/Selector/Alias.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,12 +27,11 @@
  * @library ..
  */
 
-import java.io.*;
 import java.net.*;
 import java.nio.*;
 import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
 import java.util.*;
-import java.nio.channels.spi.SelectorProvider;
 
 public class Alias {
 
@@ -40,18 +39,26 @@
     static int LIMIT = 20; // Hangs after just 1 if problem is present
 
     public static void main(String[] args) throws Exception {
-        test1();
+        try (TestServers.DayTimeServer daytimeServer
+                = TestServers.DayTimeServer.startNewServer(100)) {
+            test1(daytimeServer);
+        }
     }
 
-    public static void test1() throws Exception {
+    static void test1(TestServers.DayTimeServer daytimeServer) throws Exception {
         Selector selector = SelectorProvider.provider().openSelector();
-        InetAddress myAddress=InetAddress.getByName(TestUtil.HOST);
-        InetSocketAddress isa = new InetSocketAddress(myAddress,13);
+        InetAddress myAddress = daytimeServer.getAddress();
+        InetSocketAddress isa
+            = new InetSocketAddress(myAddress,
+                                    daytimeServer.getPort());
 
         for (int j=0; j<LIMIT; j++) {
             SocketChannel sc = SocketChannel.open();
             sc.configureBlocking(false);
             boolean result = sc.connect(isa);
+
+            // On some platforms - given that we're using a local server,
+            // we may not enter into the if () { } statement below...
             if (!result) {
                 SelectionKey key = sc.register(selector,
                                                SelectionKey.OP_CONNECT);
--- a/test/java/nio/channels/Selector/BasicConnect.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/Selector/BasicConnect.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,12 +27,10 @@
  * @library ..
  */
 
-import java.io.*;
 import java.net.*;
 import java.nio.*;
 import java.nio.channels.*;
 import java.nio.channels.spi.SelectorProvider;
-import java.nio.charset.*;
 import java.util.*;
 
 
@@ -44,52 +42,57 @@
 
 public class BasicConnect {
 
-    static final int PORT = 7;          // echo
-    static final String HOST = TestUtil.HOST;
-
     public static void main(String[] args) throws Exception {
         Selector connectSelector =
             SelectorProvider.provider().openSelector();
-        InetSocketAddress isa
-            = new InetSocketAddress(InetAddress.getByName(HOST), PORT);
-        SocketChannel sc = SocketChannel.open();
-        sc.configureBlocking(false);
-        boolean result = sc.connect(isa);
-        while (!result) {
-            SelectionKey connectKey = sc.register(connectSelector,
-                                                  SelectionKey.OP_CONNECT);
-            int keysAdded = connectSelector.select();
-            if (keysAdded > 0) {
-                Set readyKeys = connectSelector.selectedKeys();
-                Iterator i = readyKeys.iterator();
-                while (i.hasNext()) {
-                    SelectionKey sk = (SelectionKey)i.next();
-                    i.remove();
-                    SocketChannel nextReady = (SocketChannel)sk.channel();
-                    result = nextReady.finishConnect();
-                    if (result)
-                        sk.cancel();
+        try (TestServers.EchoServer echoServer
+                = TestServers.EchoServer.startNewServer(100)) {
+            InetSocketAddress isa
+                = new InetSocketAddress(echoServer.getAddress(),
+                                        echoServer.getPort());
+            SocketChannel sc = SocketChannel.open();
+            sc.configureBlocking(false);
+            boolean result = sc.connect(isa);
+            if (result) {
+                System.out.println("Socket immediately connected on "
+                        + System.getProperty("os.name")
+                        + ": " + sc);
+            }
+            while (!result) {
+                SelectionKey connectKey = sc.register(connectSelector,
+                                                      SelectionKey.OP_CONNECT);
+                int keysAdded = connectSelector.select();
+                if (keysAdded > 0) {
+                    Set readyKeys = connectSelector.selectedKeys();
+                    Iterator i = readyKeys.iterator();
+                    while (i.hasNext()) {
+                        SelectionKey sk = (SelectionKey)i.next();
+                        i.remove();
+                        SocketChannel nextReady = (SocketChannel)sk.channel();
+                        result = nextReady.finishConnect();
+                        if (result)
+                            sk.cancel();
+                    }
                 }
             }
-        }
 
-        byte[] bs = new byte[] { (byte)0xca, (byte)0xfe,
-                                 (byte)0xba, (byte)0xbe };
-        ByteBuffer bb = ByteBuffer.wrap(bs);
-        sc.configureBlocking(true);
-        sc.write(bb);
-        bb.rewind();
+            byte[] bs = new byte[] { (byte)0xca, (byte)0xfe,
+                                     (byte)0xba, (byte)0xbe };
+            ByteBuffer bb = ByteBuffer.wrap(bs);
+            sc.configureBlocking(true);
+            sc.write(bb);
+            bb.rewind();
 
-        ByteBuffer bb2 = ByteBuffer.allocateDirect(100);
-        int n = sc.read(bb2);
-        bb2.flip();
+            ByteBuffer bb2 = ByteBuffer.allocateDirect(100);
+            int n = sc.read(bb2);
+            bb2.flip();
 
-        sc.close();
-        connectSelector.close();
+            sc.close();
+            connectSelector.close();
 
-        if (!bb.equals(bb2))
-            throw new Exception("Echoed bytes incorrect: Sent "
-                                + bb + ", got " + bb2);
+            if (!bb.equals(bb2))
+                throw new Exception("Echoed bytes incorrect: Sent "
+                                    + bb + ", got " + bb2);
+        }
     }
-
 }
--- a/test/java/nio/channels/Selector/Connect.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/Selector/Connect.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,12 +27,11 @@
  * @library ..
  */
 
-import java.io.*;
 import java.net.*;
 import java.nio.*;
 import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
 import java.util.*;
-import java.nio.channels.spi.SelectorProvider;
 
 public class Connect {
 
@@ -40,12 +39,18 @@
     static int LIMIT = 100;
 
     public static void main(String[] args) throws Exception {
-        scaleTest();
+        try (TestServers.DayTimeServer daytimeServer
+                = TestServers.DayTimeServer.startNewServer(50)) {
+            scaleTest(daytimeServer);
+        }
     }
 
-    public static void scaleTest() throws Exception {
-        InetAddress myAddress=InetAddress.getByName(TestUtil.HOST);
-        InetSocketAddress isa = new InetSocketAddress(myAddress,13);
+    static void scaleTest(TestServers.DayTimeServer daytimeServer)
+        throws Exception
+    {
+        InetAddress myAddress = daytimeServer.getAddress();
+        InetSocketAddress isa
+            = new InetSocketAddress(myAddress, daytimeServer.getPort());
 
         for (int j=0; j<LIMIT; j++) {
             SocketChannel sc = SocketChannel.open();
--- a/test/java/nio/channels/Selector/ConnectWrite.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/Selector/ConnectWrite.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,23 +27,25 @@
  * @library ..
  */
 
-import java.io.*;
 import java.net.*;
-import java.nio.*;
 import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
 import java.util.*;
-import java.nio.channels.spi.SelectorProvider;
 
 public class ConnectWrite {
 
     public static void main(String[] args) throws Exception {
-        test1(13);
+        try (TestServers.DayTimeServer daytimeServer
+                = TestServers.DayTimeServer.startNewServer(25)) {
+            test1(daytimeServer);
+        }
     }
 
-    public static void test1(int port) throws Exception {
+    static void test1(TestServers.DayTimeServer daytimeServer) throws Exception {
         Selector selector = SelectorProvider.provider().openSelector();
-        InetAddress myAddress=InetAddress.getByName(TestUtil.HOST);
-        InetSocketAddress isa = new InetSocketAddress(myAddress, port);
+        InetAddress myAddress = daytimeServer.getAddress();
+        InetSocketAddress isa
+            = new InetSocketAddress(myAddress, daytimeServer.getPort());
         SocketChannel sc = SocketChannel.open();
         try {
             sc.configureBlocking(false);
--- a/test/java/nio/channels/Selector/KeysReady.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/Selector/KeysReady.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,21 +28,15 @@
  */
 
 import java.net.*;
-import java.io.*;
-import java.nio.*;
 import java.nio.channels.*;
-import java.nio.charset.*;
 import java.nio.channels.spi.SelectorProvider;
 
 public class KeysReady {
 
-    static final int DAYTIME_PORT = 13;
-    static final String DAYTIME_HOST = TestUtil.HOST;
-
-    static void test() throws Exception {
+    static void test(TestServers.DayTimeServer dayTimeServer) throws Exception {
         InetSocketAddress isa
-            = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
-                                    DAYTIME_PORT);
+            = new InetSocketAddress(dayTimeServer.getAddress(),
+                                    dayTimeServer.getPort());
         SocketChannel sc = SocketChannel.open();
         sc.configureBlocking(false);
         sc.connect(isa);
@@ -64,7 +58,10 @@
     }
 
     public static void main(String[] args) throws Exception {
-        test();
+        try (TestServers.DayTimeServer daytimeServer
+                = TestServers.DayTimeServer.startNewServer(50)) {
+            test(daytimeServer);
+        }
     }
 
 }
--- a/test/java/nio/channels/SocketChannel/AdaptSocket.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/SocketChannel/AdaptSocket.java	Sun Dec 02 23:39:15 2012 -0800
@@ -35,19 +35,16 @@
 
     static java.io.PrintStream out = System.out;
 
-    static final int ECHO_PORT = 7;
-    static final int DAYTIME_PORT = 13;
-    static final String REMOTE_HOST = TestUtil.HOST;
-    static final String VERY_REMOTE_HOST = TestUtil.FAR_HOST;
-
-    static void test(String hn, int timeout, boolean shouldTimeout)
+    static void test(TestServers.DayTimeServer dayTimeServer,
+                     int timeout,
+                     boolean shouldTimeout)
         throws Exception
     {
         out.println();
 
         InetSocketAddress isa
-            = new InetSocketAddress(InetAddress.getByName(hn),
-                                    DAYTIME_PORT);
+            = new InetSocketAddress(dayTimeServer.getAddress(),
+                                    dayTimeServer.getPort());
         SocketChannel sc = SocketChannel.open();
         Socket so = sc.socket();
         out.println("opened: " + so);
@@ -116,13 +113,16 @@
         }
     }
 
-    static void testRead(String hn, int timeout, boolean shouldTimeout)
+    static void testRead(TestServers.EchoServer echoServer,
+                         int timeout,
+                         boolean shouldTimeout)
         throws Exception
     {
         out.println();
 
         InetSocketAddress isa
-            = new InetSocketAddress(InetAddress.getByName(hn), ECHO_PORT);
+            = new InetSocketAddress(echoServer.getAddress(),
+                                    echoServer.getPort());
         SocketChannel sc = SocketChannel.open();
         sc.connect(isa);
         Socket so = sc.socket();
@@ -134,22 +134,38 @@
         out.println("timeout: " + so.getSoTimeout());
 
         testRead(so, shouldTimeout);
-        for (int i = 0; i < 4; i++)
+        for (int i = 0; i < 4; i++) {
             testRead(so, shouldTimeout);
+        }
 
         sc.close();
     }
 
     public static void main(String[] args) throws Exception {
 
-        test(REMOTE_HOST, 0, false);
-        test(REMOTE_HOST, 1000, false);
-        test(VERY_REMOTE_HOST, 10, true);
+        try (TestServers.DayTimeServer dayTimeServer
+                = TestServers.DayTimeServer.startNewServer()) {
+            test(dayTimeServer, 0, false);
+            test(dayTimeServer, 1000, false);
+        }
 
-        testRead(REMOTE_HOST, 0, false);
-        testRead(REMOTE_HOST, 8000, false);
-        testRead(VERY_REMOTE_HOST, 10, true);
+        try (TestServers.DayTimeServer lingerDayTimeServer
+                = TestServers.DayTimeServer.startNewServer(100)) {
+            // this test no longer really test the connection timeout
+            // since there is no way to prevent the server from eagerly
+            // accepting connection...
+            test(lingerDayTimeServer, 10, true);
+        }
 
-    }
+        try (TestServers.EchoServer echoServer
+                = TestServers.EchoServer.startNewServer()) {
+            testRead(echoServer, 0, false);
+            testRead(echoServer, 8000, false);
+        }
 
+        try (TestServers.EchoServer lingerEchoServer
+                = TestServers.EchoServer.startNewServer(100)) {
+            testRead(lingerEchoServer, 10, true);
+        }
+    }
 }
--- a/test/java/nio/channels/SocketChannel/Basic.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/SocketChannel/Basic.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,13 +36,10 @@
 
     static java.io.PrintStream out = System.out;
 
-    static final int DAYTIME_PORT = 13;
-    static final String DAYTIME_HOST = TestUtil.HOST;
-
-    static void test() throws Exception {
+    static void test(TestServers.DayTimeServer daytimeServer) throws Exception {
         InetSocketAddress isa
-            = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
-                                    DAYTIME_PORT);
+            = new InetSocketAddress(daytimeServer.getAddress(),
+                                    daytimeServer.getPort());
         SocketChannel sc = SocketChannel.open(isa);
         out.println("opened: " + sc);
         /*
@@ -76,7 +73,10 @@
     }
 
     public static void main(String[] args) throws Exception {
-        test();
+        try (TestServers.DayTimeServer dayTimeServer
+                = TestServers.DayTimeServer.startNewServer(100)) {
+            test(dayTimeServer);
+        }
     }
 
 }
--- a/test/java/nio/channels/SocketChannel/BufferSize.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/SocketChannel/BufferSize.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,17 +28,10 @@
  */
 
 import java.nio.channels.*;
-import java.net.*;
 
 public class BufferSize {
 
-    static final int DAYTIME_PORT = 13;
-    static final String DAYTIME_HOST = TestUtil.HOST;
-
     public static void main(String[] args) throws Exception {
-        InetSocketAddress isa
-            = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
-                                    DAYTIME_PORT);
         ServerSocketChannel sc = ServerSocketChannel.open();
         try {
             sc.socket().setReceiveBufferSize(-1);
--- a/test/java/nio/channels/SocketChannel/Connect.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/SocketChannel/Connect.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,9 +27,9 @@
  * @library ..
  */
 
+import java.net.*;
 import java.nio.*;
 import java.nio.channels.*;
-import java.net.*;
 import java.util.*;
 
 public class Connect {
@@ -37,21 +37,26 @@
     private static final long INCREMENTAL_DELAY = 30L * 1000L;
 
     public static void main(String args[]) throws Exception {
-        test1(TestUtil.HOST);
+        try (TestServers.EchoServer echoServer
+                = TestServers.EchoServer.startNewServer(1000)) {
+            test1(echoServer);
+        }
         try {
-            test1(TestUtil.REFUSING_HOST);
+            TestServers.RefusingServer refusingServer
+                = TestServers.RefusingServer.startNewServer();
+            test1(refusingServer);
             throw new Exception("Refused connection throws no exception");
         } catch (ConnectException ce) {
             // Correct result
         }
     }
 
-    static void test1(String hostname) throws Exception {
+    static void test1(TestServers.AbstractServer server) throws Exception {
         Selector selector;
         SocketChannel sc;
         SelectionKey sk;
         InetSocketAddress isa = new InetSocketAddress(
-            InetAddress.getByName (hostname), 80);
+            server.getAddress(), server.getPort());
         sc = SocketChannel.open();
         sc.configureBlocking(false);
 
--- a/test/java/nio/channels/SocketChannel/ConnectState.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/SocketChannel/ConnectState.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,20 +30,39 @@
 import java.net.*;
 import java.nio.*;
 import java.nio.channels.*;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
 
 
 public class ConnectState {
 
     static PrintStream log = System.err;
 
-    static String REMOTE_HOST = TestUtil.HOST;
-    static int REMOTE_PORT = 7;                         // echo
     static InetSocketAddress remote;
 
     final static int ST_UNCONNECTED = 0;
     final static int ST_PENDING = 1;
     final static int ST_CONNECTED = 2;
     final static int ST_CLOSED = 3;
+    final static int ST_PENDING_OR_CONNECTED = 4;
+    // NO exceptions expected
+    final static Collection<Class<?>> NONE = Collections.emptySet();
+
+    // make a set of expected exception.
+    static Collection<Class<?>> expectedExceptions(Class<?>... expected) {
+        final Collection<Class<?>> exceptions;
+        if (expected.length == 0) {
+            exceptions = NONE;
+        } else if (expected.length == 1) {
+            assert expected[0] != null;
+            exceptions = Collections.<Class<?>>singleton(expected[0]);
+        } else {
+            exceptions = new HashSet<>(Arrays.asList(expected));
+        }
+        return exceptions;
+    }
 
     static abstract class Test {
 
@@ -76,37 +95,65 @@
                 check(!sc.isConnectionPending(), "!isConnectionPending");
                 check(sc.isOpen(), "isOpen");
                 break;
+            case ST_PENDING_OR_CONNECTED:
+                check(sc.isConnected() || sc.isConnectionPending(),
+                        "isConnected || isConnectionPending");
+                check(sc.isOpen(), "isOpen");
+                break;
             }
         }
 
-        Test(String name, Class exception, int state) throws Exception {
+        Test(String name, Class<?> exception, int state) throws Exception {
+            this(name, expectedExceptions(exception), state);
+        }
+
+        // On some architecture we may need to accept several exceptions.
+        // For instance on Solaris, when using a server colocated on the
+        // machine we cannot guarantee that we will get a
+        // ConnectionPendingException when connecting twice on the same
+        // non-blocking socket. We may instead get a an
+        // AlreadyConnectedException, which is also valid: it simply means
+        // that the first connection has been immediately accepted.
+        Test(String name, Collection<Class<?>> exceptions, int state)
+                throws Exception {
             SocketChannel sc = SocketChannel.open();
-            String note = null;
+            String note;
             try {
                 try {
                     note = go(sc);
                 } catch (Exception x) {
-                    if (exception != null) {
+                    Class<?> expectedExceptionClass = null;
+                    for (Class<?> exception : exceptions) {
                         if (exception.isInstance(x)) {
                             log.println(name + ": As expected: "
                                         + x);
+                            expectedExceptionClass = exception;
                             check(sc, state);
-                            return;
-                        } else {
-                            throw new Exception(name
+                            break;
+                        }
+                    }
+                    if (expectedExceptionClass == null
+                            && !exceptions.isEmpty()) {
+                        // we had an exception, but it's not of the set of
+                        // exceptions we expected.
+                        throw new Exception(name
                                                 + ": Incorrect exception",
                                                 x);
-                        }
-                    } else {
+                    } else if (exceptions.isEmpty()) {
+                        // we didn't expect any exception
                         throw new Exception(name
                                             + ": Unexpected exception",
                                             x);
                     }
+                    // if we reach here, we have our expected exception
+                    assert expectedExceptionClass != null;
+                    return;
                 }
-                if (exception != null)
+                if (!exceptions.isEmpty()) {
                     throw new Exception(name
                                         + ": Expected exception not thrown: "
-                                        + exception);
+                                        + exceptions.iterator().next());
+                }
                 check(sc, state);
                 log.println(name + ": Returned normally"
                             + ((note != null) ? ": " + note : ""));
@@ -123,6 +170,7 @@
 
         new Test("Read unconnected", NotYetConnectedException.class,
                  ST_UNCONNECTED) {
+                @Override
                 String go(SocketChannel sc) throws Exception {
                     ByteBuffer b = ByteBuffer.allocateDirect(1024);
                     sc.read(b);
@@ -131,19 +179,22 @@
 
         new Test("Write unconnected", NotYetConnectedException.class,
                  ST_UNCONNECTED) {
+                @Override
                 String go(SocketChannel sc) throws Exception {
                     ByteBuffer b = ByteBuffer.allocateDirect(1024);
                     sc.write(b);
                     return null;
                 }};
 
-        new Test("Simple connect", null, ST_CONNECTED) {
+        new Test("Simple connect", NONE, ST_CONNECTED) {
+                @Override
                 String go(SocketChannel sc) throws Exception {
                     sc.connect(remote);
                     return null;
                 }};
 
-        new Test("Simple connect & finish", null, ST_CONNECTED) {
+        new Test("Simple connect & finish", NONE, ST_CONNECTED) {
+                @Override
                 String go(SocketChannel sc) throws Exception {
                     sc.connect(remote);
                     if (!sc.finishConnect())
@@ -153,6 +204,7 @@
 
         new Test("Double connect",
                  AlreadyConnectedException.class, ST_CONNECTED) {
+                @Override
                 String go(SocketChannel sc) throws Exception {
                     sc.connect(remote);
                     sc.connect(remote);
@@ -161,12 +213,16 @@
 
         new Test("Finish w/o start",
                  NoConnectionPendingException.class, ST_UNCONNECTED) {
+                @Override
                 String go(SocketChannel sc) throws Exception {
                     sc.finishConnect();
                     return null;
                 }};
 
-        new Test("NB simple connect", null, ST_CONNECTED) {
+        // Note: using our local EchoServer rather than echo on a distant
+        //       host - we see that Tries to finish = 0 (instead of ~ 18).
+        new Test("NB simple connect", NONE, ST_CONNECTED) {
+                @Override
                 String go(SocketChannel sc) throws Exception {
                     sc.configureBlocking(false);
                     sc.connect(remote);
@@ -179,8 +235,15 @@
                     return ("Tries to finish = " + n);
                 }};
 
+        // Note: using our local EchoServer rather than echo on a distant
+        //       host - we cannot guarantee that this test will get a
+        //       a ConnectionPendingException: it may get an
+        //       AlreadyConnectedException, so we should allow for both.
         new Test("NB double connect",
-                 ConnectionPendingException.class, ST_PENDING) {
+                 expectedExceptions(ConnectionPendingException.class,
+                                    AlreadyConnectedException.class),
+                 ST_PENDING_OR_CONNECTED) {
+                @Override
                 String go(SocketChannel sc) throws Exception {
                     sc.configureBlocking(false);
                     sc.connect(remote);
@@ -190,13 +253,15 @@
 
         new Test("NB finish w/o start",
                  NoConnectionPendingException.class, ST_UNCONNECTED) {
+                @Override
                 String go(SocketChannel sc) throws Exception {
                     sc.configureBlocking(false);
                     sc.finishConnect();
                     return null;
                 }};
 
-        new Test("NB connect, B finish", null, ST_CONNECTED) {
+        new Test("NB connect, B finish", NONE, ST_CONNECTED) {
+                @Override
                 String go(SocketChannel sc) throws Exception {
                     sc.configureBlocking(false);
                     sc.connect(remote);
@@ -208,9 +273,12 @@
     }
 
     public static void main(String[] args) throws Exception {
-        remote = new InetSocketAddress(InetAddress.getByName(REMOTE_HOST),
-                                       REMOTE_PORT);
-        tests();
+        try (TestServers.EchoServer echoServer
+                = TestServers.EchoServer.startNewServer(500)) {
+            remote = new InetSocketAddress(echoServer.getAddress(),
+                                           echoServer.getPort());
+            tests();
+        }
     }
 
 }
--- a/test/java/nio/channels/SocketChannel/FinishConnect.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/SocketChannel/FinishConnect.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,21 +36,25 @@
 
 public class FinishConnect {
 
-    static final int DAYTIME_PORT = 13;
-    static final String DAYTIME_HOST = TestUtil.HOST;
-
     public static void main(String[] args) throws Exception {
-        test1(true, true);
-        test1(true, false);
-        test1(false, true);
-        test1(false, false);
-        test2();
+        try (TestServers.DayTimeServer dayTimeServer
+                = TestServers.DayTimeServer.startNewServer(100)) {
+            test1(dayTimeServer, true, true);
+            test1(dayTimeServer, true, false);
+            test1(dayTimeServer, false, true);
+            test1(dayTimeServer, false, false);
+            test2(dayTimeServer);
+        }
     }
 
-    static void test1(boolean select, boolean setBlocking) throws Exception {
+    static void test1(TestServers.DayTimeServer daytimeServer,
+                      boolean select,
+                      boolean setBlocking)
+        throws Exception
+    {
         InetSocketAddress isa
-            = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
-                                    DAYTIME_PORT);
+            = new InetSocketAddress(daytimeServer.getAddress(),
+                                    daytimeServer.getPort());
         SocketChannel sc = SocketChannel.open();
         sc.configureBlocking(false);
         boolean connected = sc.connect(isa);
@@ -109,15 +113,27 @@
         sc.close();
     }
 
-    static void test2() throws Exception {
+    static void test2(TestServers.DayTimeServer daytimeServer) throws Exception {
         InetSocketAddress isa
-            = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
-                                    DAYTIME_PORT);
+            = new InetSocketAddress(daytimeServer.getAddress(),
+                                    daytimeServer.getPort());
         boolean done = false;
         int globalAttempts = 0;
+        int connectSuccess = 0;
         while (!done) {
-            if (globalAttempts++ > 50)
+            // When using a local daytime server it is not always possible
+            // to get a pending connection, as sc.connect(isa) may always
+            // return true.
+            // So we're going to throw the exception only if there was
+            // at least 1 case where we did not manage to connect.
+            if (globalAttempts++ > 50) {
+                if (globalAttempts == connectSuccess + 1) {
+                    System.out.println("Can't fully test on "
+                            + System.getProperty("os.name"));
+                    break;
+                }
                 throw new RuntimeException("Failed to connect");
+            }
             SocketChannel sc = SocketChannel.open();
             sc.configureBlocking(false);
             boolean connected = sc.connect(isa);
@@ -132,6 +148,9 @@
                 }
                 Thread.sleep(10);
             }
+            if (connected) {
+                connectSuccess++;
+            }
             sc.close();
         }
     }
--- a/test/java/nio/channels/SocketChannel/IsConnectable.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/SocketChannel/IsConnectable.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,24 +28,19 @@
  */
 
 import java.net.*;
-import java.io.*;
-import java.nio.*;
 import java.nio.channels.*;
 import java.nio.channels.spi.SelectorProvider;
 import java.util.*;
 
 public class IsConnectable {
 
-    static final int DAYTIME_PORT = 13;
-    static final String DAYTIME_HOST = TestUtil.HOST;
-
-    static void test() throws Exception {
+    static void test(TestServers.DayTimeServer daytimeServer) throws Exception {
         InetSocketAddress isa
-            = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
-                                    DAYTIME_PORT);
+            = new InetSocketAddress(daytimeServer.getAddress(),
+                                    daytimeServer.getPort());
         SocketChannel sc = SocketChannel.open();
         sc.configureBlocking(false);
-        sc.connect(isa);
+        final boolean immediatelyConnected = sc.connect(isa);
 
         Selector selector = SelectorProvider.provider().openSelector();
         try {
@@ -67,7 +62,12 @@
                         throw new Exception("Test failed: 4737146 detected");
                 }
             } else {
-                throw new Exception("Select failed");
+                if (!immediatelyConnected) {
+                    throw new Exception("Select failed");
+                } else {
+                    System.out.println("IsConnectable couldn't be fully tested for "
+                            + System.getProperty("os.name"));
+                }
             }
         } finally {
             sc.close();
@@ -76,7 +76,10 @@
     }
 
     public static void main(String[] args) throws Exception {
-        test();
+        try (TestServers.DayTimeServer daytimeServer
+                = TestServers.DayTimeServer.startNewServer(100)) {
+            test(daytimeServer);
+        }
     }
 
 }
--- a/test/java/nio/channels/SocketChannel/LocalAddress.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/SocketChannel/LocalAddress.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,18 +28,20 @@
  */
 
 import java.net.*;
-import java.nio.*;
 import java.nio.channels.*;
 
 public class LocalAddress {
     public static void main(String[] args) throws Exception {
-        test1();
+        try (TestServers.EchoServer echoServer
+                = TestServers.EchoServer.startNewServer()) {
+            test1(echoServer);
+        }
     }
 
-    static void test1() throws Exception {
+    static void test1(TestServers.AbstractServer server) throws Exception {
         InetAddress bogus = InetAddress.getByName("0.0.0.0");
         InetSocketAddress saddr = new InetSocketAddress(
-            InetAddress.getByName(TestUtil.HOST), 23);
+            server.getAddress(), server.getPort());
 
         //Test1: connect only
         SocketChannel sc = SocketChannel.open();
--- a/test/java/nio/channels/SocketChannel/Stream.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/SocketChannel/Stream.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,22 +27,17 @@
  * @library ..
  */
 
+import java.io.*;
 import java.net.*;
-import java.io.*;
-import java.nio.*;
 import java.nio.channels.*;
-import java.nio.charset.*;
 
 
 public class Stream {
 
-    static final int DAYTIME_PORT = 13;
-    static final String DAYTIME_HOST = TestUtil.HOST;
-
-    static void test() throws Exception {
+    static void test(TestServers.DayTimeServer daytimeServer) throws Exception {
         InetSocketAddress isa
-            = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
-                                    DAYTIME_PORT);
+            = new InetSocketAddress(daytimeServer.getAddress(),
+                                    daytimeServer.getPort());
         SocketChannel sc = SocketChannel.open();
         sc.connect(isa);
         sc.configureBlocking(false);
@@ -58,7 +53,9 @@
     }
 
     public static void main(String[] args) throws Exception {
-        test();
+        try (TestServers.DayTimeServer dayTimeServer
+                = TestServers.DayTimeServer.startNewServer(100)) {
+            test(dayTimeServer);
+        }
     }
-
 }
--- a/test/java/nio/channels/SocketChannel/VectorParams.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/SocketChannel/VectorParams.java	Sun Dec 02 23:39:15 2012 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,31 +27,31 @@
  * @library ..
  */
 
+import java.io.*;
 import java.net.*;
-import java.io.*;
 import java.nio.*;
 import java.nio.channels.*;
-import java.nio.charset.*;
 
 public class VectorParams {
 
     static java.io.PrintStream out = System.out;
 
-    static final int DAYTIME_PORT = 13;
-    static final String DAYTIME_HOST = TestUtil.HOST;
     static final int testSize = 10;
     static ByteBuffer[] bufs = null;
     static InetSocketAddress isa = null;
 
     public static void main(String[] args) throws Exception {
-        initBufs();
-        testSocketChannelVectorParams();
-        testDatagramChannelVectorParams();
-        testPipeVectorParams();
-        testFileVectorParams();
+        try (TestServers.DayTimeServer daytimeServer
+                = TestServers.DayTimeServer.startNewServer(100)) {
+            initBufs(daytimeServer);
+            testSocketChannelVectorParams();
+            testDatagramChannelVectorParams();
+            testPipeVectorParams();
+            testFileVectorParams();
+        }
     }
 
-    static void initBufs() throws Exception {
+    static void initBufs(TestServers.DayTimeServer daytimeServer) throws Exception {
         bufs = new ByteBuffer[testSize];
         for(int i=0; i<testSize; i++) {
             String source = "buffer" + i;
@@ -59,8 +59,8 @@
             bufs[i].put(source.getBytes("8859_1"));
             bufs[i].flip();
         }
-        isa =  new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
-                                    DAYTIME_PORT);
+        isa = new InetSocketAddress(daytimeServer.getAddress(),
+                                    daytimeServer.getPort());
     }
 
     static void testSocketChannelVectorParams() throws Exception {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/nio/channels/TestServers.java	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,849 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* Test utility classes
+ *
+ */
+
+import java.io.*;
+import java.net.*;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+
+public class TestServers {
+
+    private TestServers() { }
+
+    /**
+     * An abstract server identifies a server which listens on a port on on a
+     * given machine.
+     */
+    static abstract class AbstractServer {
+
+        private AbstractServer() {
+        }
+
+        public abstract int getPort();
+
+        public abstract InetAddress getAddress();
+    }
+
+    /**
+     * A downgraded type of AbstractServer which will refuse connections. Note:
+     * use it once and throw it away - this implementation opens an anonymous
+     * socket and closes it, returning the address of the closed socket. If
+     * other servers are started afterwards, the address/port might get reused
+     * and become connectable again - so it's not a good idea to assume that
+     * connections using this address/port will always be refused. Connections
+     * will be refused as long as the address/port of the refusing server has
+     * not been reused.
+     */
+    static class RefusingServer extends AbstractServer {
+
+        final InetAddress address;
+        final int port;
+
+        private RefusingServer(InetAddress address, int port) {
+            this.address = address;
+            this.port = port;
+        }
+
+        @Override
+        public int getPort() {
+            return port;
+        }
+
+        @Override
+        public InetAddress getAddress() {
+            return address;
+        }
+
+        public static RefusingServer startNewServer() throws IOException {
+            ServerSocket socket = new ServerSocket(0, 100,
+                    InetAddress.getLocalHost());
+            RefusingServer server = new RefusingServer(socket.getInetAddress(),
+                    socket.getLocalPort());
+            socket.close();
+            return server;
+        }
+    }
+
+    /**
+     * An abstract class for implementing small TCP servers for the nio tests
+     * purposes. Disclaimer: This is a naive implementation that uses the old
+     * networking APIs (not those from {@code java.nio.*}) and shamelessly
+     * extends/creates Threads instead of using an executor service.
+     */
+    static abstract class AbstractTcpServer extends AbstractServer
+            implements Runnable, Closeable {
+
+        protected final long linger; // #of ms to wait before responding
+        private Thread acceptThread; // thread waiting for accept
+        // list of opened connections that should be closed on close.
+        private List<TcpConnectionThread> connections = new ArrayList<>();
+        private ServerSocket serverSocket; // the server socket
+        private boolean started = false; // whether the server is started
+        Throwable error = null;
+
+        /**
+         * Creates a new abstract TCP server.
+         *
+         * @param linger the amount of time the server should wait before
+         * responding to requests.
+         */
+        protected AbstractTcpServer(long linger) {
+            this.linger = linger;
+        }
+
+        /**
+         * The local port to which the server is bound.
+         *
+         * @return The local port to which the server is bound.
+         * @exception IllegalStateException is thrown if the server is not
+         * started.
+         */
+        @Override
+        public final synchronized int getPort() {
+            if (!started) {
+                throw new IllegalStateException("Not started");
+            }
+            return serverSocket.getLocalPort();
+        }
+
+        /**
+         * The local address to which the server is bound.
+         *
+         * @return The local address to which the server is bound.
+         * @exception IllegalStateException is thrown if the server is not
+         * started.
+         */
+        @Override
+        public final synchronized InetAddress getAddress() {
+            if (!started) {
+                throw new IllegalStateException("Not started");
+            }
+            return serverSocket.getInetAddress();
+        }
+
+        /**
+         * Tells whether the server is started.
+         *
+         * @return true if the server is started.
+         */
+        public final synchronized boolean isStarted() {
+            return started;
+        }
+
+        /**
+         * Creates a new server socket.
+         *
+         * @param port local port to bind to.
+         * @param backlog requested maximum length of the queue of incoming
+         * connections.
+         * @param address local address to bind to.
+         * @return a new bound server socket ready to accept connections.
+         * @throws IOException if the socket cannot be created or bound.
+         */
+        protected ServerSocket newServerSocket(int port, int backlog,
+                InetAddress address)
+                throws IOException {
+            return new ServerSocket(port, backlog, address);
+        }
+
+        /**
+         * Starts listening for connections.
+         *
+         * @throws IOException if the server socket cannot be created or bound.
+         */
+        public final synchronized void start() throws IOException {
+            if (started) {
+                return;
+            }
+            final ServerSocket socket =
+                    newServerSocket(0, 100, InetAddress.getLocalHost());
+            serverSocket = socket;
+            acceptThread = new Thread(this);
+            acceptThread.setDaemon(true);
+            acceptThread.start();
+            started = true;
+        }
+
+        /**
+         * Calls {@code Thread.sleep(linger);}
+         */
+        protected final void lingerIfRequired() {
+            if (linger > 0) {
+                try {
+                    Thread.sleep(linger);
+                } catch (InterruptedException x) {
+                    Thread.interrupted();
+                    final ServerSocket socket = serverSocket();
+                    if (socket != null && !socket.isClosed()) {
+                        System.err.println("Thread interrupted...");
+                    }
+                }
+            }
+        }
+
+        final synchronized ServerSocket serverSocket() {
+            return this.serverSocket;
+        }
+
+        /**
+         * The main accept loop.
+         */
+        @Override
+        public final void run() {
+            final ServerSocket sSocket = serverSocket();
+            try {
+                Socket s;
+                while (isStarted() && !Thread.interrupted()
+                        && (s = sSocket.accept()) != null) {
+                    lingerIfRequired();
+                    listen(s);
+                }
+            } catch (Exception x) {
+                error = x;
+            } finally {
+                synchronized (this) {
+                    if (!sSocket.isClosed()) {
+                        try {
+                            sSocket.close();
+                        } catch (IOException x) {
+                            System.err.println("Failed to close server socket");
+                        }
+                    }
+                    if (started && this.serverSocket == sSocket) {
+                        started = false;
+                        this.serverSocket = null;
+                        this.acceptThread = null;
+                    }
+                }
+            }
+        }
+
+        /**
+         * Represents a connection accepted by the server.
+         */
+        protected abstract class TcpConnectionThread extends Thread {
+
+            protected final Socket socket;
+
+            protected TcpConnectionThread(Socket socket) {
+                this.socket = socket;
+                this.setDaemon(true);
+            }
+
+            public void close() throws IOException {
+                socket.close();
+                interrupt();
+            }
+        }
+
+        /**
+         * Creates a new TcpConnnectionThread to handle the connection through
+         * an accepted socket.
+         *
+         * @param s the socket returned by {@code serverSocket.accept()}.
+         * @return a new TcpConnnectionThread to handle the connection through
+         * an accepted socket.
+         */
+        protected abstract TcpConnectionThread createConnection(Socket s);
+
+        /**
+         * Creates and starts a new TcpConnectionThread to handle the accepted
+         * socket.
+         *
+         * @param s the socket returned by {@code serverSocket.accept()}.
+         */
+        private synchronized void listen(Socket s) {
+            TcpConnectionThread c = createConnection(s);
+            c.start();
+            addConnection(c);
+        }
+
+        /**
+         * Add the connection to the list of accepted connections.
+         *
+         * @param connection an accepted connection.
+         */
+        protected synchronized void addConnection(
+                TcpConnectionThread connection) {
+            connections.add(connection);
+        }
+
+        /**
+         * Remove the connection from the list of accepted connections.
+         *
+         * @param connection an accepted connection.
+         */
+        protected synchronized void removeConnection(
+                TcpConnectionThread connection) {
+            connections.remove(connection);
+        }
+
+        /**
+         * Close the server socket and all the connections present in the list
+         * of accepted connections.
+         *
+         * @throws IOException
+         */
+        @Override
+        public synchronized void close() throws IOException {
+            if (serverSocket != null && !serverSocket.isClosed()) {
+                serverSocket.close();
+            }
+            if (acceptThread != null) {
+                acceptThread.interrupt();
+            }
+            int failed = 0;
+            for (TcpConnectionThread c : connections) {
+                try {
+                    c.close();
+                } catch (IOException x) {
+                    // no matter - we're closing.
+                    failed++;
+                }
+            }
+            connections.clear();
+            if (failed > 0) {
+                throw new IOException("Failed to close some connections");
+            }
+        }
+    }
+
+    /**
+     * A small TCP Server that emulates the echo service for tests purposes. See
+     * http://en.wikipedia.org/wiki/Echo_Protocol This server uses an anonymous
+     * port - NOT the standard port 7. We don't guarantee that its behavior
+     * exactly matches the RFC - the only purpose of this server is to have
+     * something that responds to nio tests...
+     */
+    static final class EchoServer extends AbstractTcpServer {
+
+        public EchoServer() {
+            this(0L);
+        }
+
+        public EchoServer(long linger) {
+            super(linger);
+        }
+
+        @Override
+        protected TcpConnectionThread createConnection(Socket s) {
+            return new EchoConnection(s);
+        }
+
+        private final class EchoConnection extends TcpConnectionThread {
+
+            public EchoConnection(Socket socket) {
+                super(socket);
+            }
+
+            @Override
+            public void run() {
+                try {
+                    final InputStream is = socket.getInputStream();
+                    final OutputStream out = socket.getOutputStream();
+                    byte[] b = new byte[255];
+                    int n;
+                    while ((n = is.read(b)) > 0) {
+                        lingerIfRequired();
+                        out.write(b, 0, n);
+                    }
+                } catch (IOException io) {
+                    // fall through to finally
+                } finally {
+                    if (!socket.isClosed()) {
+                        try {
+                            socket.close();
+                        } catch (IOException x) {
+                            System.err.println(
+                                    "Failed to close echo connection socket");
+                        }
+                    }
+                    removeConnection(this);
+                }
+            }
+        }
+
+        public static EchoServer startNewServer() throws IOException {
+            return startNewServer(0);
+        }
+
+        public static EchoServer startNewServer(long linger) throws IOException {
+            final EchoServer echoServer = new EchoServer(linger);
+            echoServer.start();
+            return echoServer;
+        }
+    }
+
+    /**
+     * A small TCP server that emulates the Day & Time service for tests
+     * purposes. See http://en.wikipedia.org/wiki/Daytime_Protocol This server
+     * uses an anonymous port - NOT the standard port 13. We don't guarantee
+     * that its behavior exactly matches the RFC - the only purpose of this
+     * server is to have something that responds to nio tests...
+     */
+    static final class DayTimeServer extends AbstractTcpServer {
+
+        public DayTimeServer() {
+            this(0L);
+        }
+
+        public DayTimeServer(long linger) {
+            super(linger);
+        }
+
+        @Override
+        protected TcpConnectionThread createConnection(Socket s) {
+            return new DayTimeServerConnection(s);
+        }
+
+        @Override
+        protected void addConnection(TcpConnectionThread connection) {
+            // do nothing - the connection just write the date and terminates.
+        }
+
+        @Override
+        protected void removeConnection(TcpConnectionThread connection) {
+            // do nothing - we're not adding connections to the list...
+        }
+
+        private final class DayTimeServerConnection extends TcpConnectionThread {
+
+            public DayTimeServerConnection(Socket socket) {
+                super(socket);
+            }
+
+            @Override
+            public void run() {
+                try {
+                    final OutputStream out = socket.getOutputStream();
+                    lingerIfRequired();
+                    out.write(new Date(System.currentTimeMillis())
+                            .toString().getBytes("US-ASCII"));
+                    out.flush();
+                } catch (IOException io) {
+                    // fall through to finally
+                } finally {
+                    if (!socket.isClosed()) {
+                        try {
+                            socket.close();
+                        } catch (IOException x) {
+                            System.err.println(
+                                    "Failed to close echo connection socket");
+                        }
+                    }
+                }
+            }
+        }
+
+        public static DayTimeServer startNewServer()
+                throws IOException {
+            return startNewServer(0);
+        }
+
+        public static DayTimeServer startNewServer(long linger)
+                throws IOException {
+            final DayTimeServer daytimeServer = new DayTimeServer(linger);
+            daytimeServer.start();
+            return daytimeServer;
+        }
+    }
+
+    /**
+     * An abstract class for implementing small UDP Servers for the nio tests
+     * purposes. Disclaimer: This is a naive implementation that uses the old
+     * networking APIs (not those from {@code java.nio.*}) and shamelessly
+     * extends/creates Threads instead of using an executor service.
+     */
+    static abstract class AbstractUdpServer extends AbstractServer
+            implements Runnable, Closeable {
+
+        protected final long linger; // #of ms to wait before responding
+        private Thread acceptThread; // thread waiting for packets
+        private DatagramSocket serverSocket; // the server socket
+        private boolean started = false; // whether the server is started
+        Throwable error = null;
+
+        /**
+         * Creates a new abstract UDP server.
+         *
+         * @param linger the amount of time the server should wait before
+         * responding to requests.
+         */
+        protected AbstractUdpServer(long linger) {
+            this.linger = linger;
+        }
+
+        /**
+         * The local port to which the server is bound.
+         *
+         * @return The local port to which the server is bound.
+         * @exception IllegalStateException is thrown if the server is not
+         * started.
+         */
+        @Override
+        public final synchronized int getPort() {
+            if (!started) {
+                throw new IllegalStateException("Not started");
+            }
+            return serverSocket.getLocalPort();
+        }
+
+        /**
+         * The local address to which the server is bound.
+         *
+         * @return The local address to which the server is bound.
+         * @exception IllegalStateException is thrown if the server is not
+         * started.
+         */
+        @Override
+        public final synchronized InetAddress getAddress() {
+            if (!started) {
+                throw new IllegalStateException("Not started");
+            }
+            return serverSocket.getLocalAddress();
+        }
+
+        /**
+         * Tells whether the server is started.
+         *
+         * @return true if the server is started.
+         */
+        public final synchronized boolean isStarted() {
+            return started;
+        }
+
+        /**
+         * Creates a new datagram socket.
+         *
+         * @param port local port to bind to.
+         * @param address local address to bind to.
+         * @return a new bound server socket ready to listen for packets.
+         * @throws IOException if the socket cannot be created or bound.
+         */
+        protected DatagramSocket newDatagramSocket(int port,
+                InetAddress address)
+                throws IOException {
+            return new DatagramSocket(port, address);
+        }
+
+        /**
+         * Starts listening for connections.
+         *
+         * @throws IOException if the server socket cannot be created or bound.
+         */
+        public final synchronized void start() throws IOException {
+            if (started) {
+                return;
+            }
+            final DatagramSocket socket =
+                    newDatagramSocket(0, InetAddress.getLocalHost());
+            serverSocket = socket;
+            acceptThread = new Thread(this);
+            acceptThread.setDaemon(true);
+            acceptThread.start();
+            started = true;
+        }
+
+        /**
+         * Calls {@code Thread.sleep(linger);}
+         */
+        protected final void lingerIfRequired() {
+            if (linger > 0) {
+                try {
+                    Thread.sleep(linger);
+                } catch (InterruptedException x) {
+                    Thread.interrupted();
+                    final DatagramSocket socket = serverSocket();
+                    if (socket != null && !socket.isClosed()) {
+                        System.err.println("Thread interrupted...");
+                    }
+                }
+            }
+        }
+
+        final synchronized DatagramSocket serverSocket() {
+            return this.serverSocket;
+        }
+
+        final synchronized boolean send(DatagramSocket socket,
+                DatagramPacket response) throws IOException {
+            if (!socket.isClosed()) {
+                socket.send(response);
+                return true;
+            } else {
+                return false;
+            }
+        }
+
+        /**
+         * The main receive loop.
+         */
+        @Override
+        public final void run() {
+            final DatagramSocket sSocket = serverSocket();
+            try {
+                final int size = Math.max(1024, sSocket.getReceiveBufferSize());
+                if (size > sSocket.getReceiveBufferSize()) {
+                    sSocket.setReceiveBufferSize(size);
+                }
+                while (isStarted() && !Thread.interrupted() && !sSocket.isClosed()) {
+                    final byte[] buf = new byte[size];
+                    final DatagramPacket packet =
+                            new DatagramPacket(buf, buf.length);
+                    lingerIfRequired();
+                    sSocket.receive(packet);
+                    //System.out.println("Received packet from: "
+                    //        + packet.getAddress()+":"+packet.getPort());
+                    handle(sSocket, packet);
+                }
+            } catch (Exception x) {
+                error = x;
+            } finally {
+                synchronized (this) {
+                    if (!sSocket.isClosed()) {
+                        sSocket.close();
+                    }
+                    if (started && this.serverSocket == sSocket) {
+                        started = false;
+                        this.serverSocket = null;
+                        this.acceptThread = null;
+                    }
+                }
+            }
+        }
+
+        /**
+         * Represents an UDP request received by the server.
+         */
+        protected abstract class UdpRequestThread extends Thread {
+
+            protected final DatagramPacket request;
+            protected final DatagramSocket socket;
+
+            protected UdpRequestThread(DatagramSocket socket, DatagramPacket request) {
+                this.socket = socket;
+                this.request = request;
+                this.setDaemon(true);
+            }
+        }
+
+        /**
+         * Creates a new UdpRequestThread to handle a DatagramPacket received
+         * through a DatagramSocket.
+         *
+         * @param socket the socket through which the request was received.
+         * @param request the datagram packet received through the socket.
+         * @return a new UdpRequestThread to handle the request received through
+         * a DatagramSocket.
+         */
+        protected abstract UdpRequestThread createConnection(DatagramSocket socket,
+                DatagramPacket request);
+
+        /**
+         * Creates and starts a new UdpRequestThread to handle the received
+         * datagram packet.
+         *
+         * @param socket the socket through which the request was received.
+         * @param request the datagram packet received through the socket.
+         */
+        private synchronized void handle(DatagramSocket socket,
+                DatagramPacket request) {
+            UdpRequestThread c = createConnection(socket, request);
+            // c can be null if the request requires no response.
+            if (c != null) {
+                c.start();
+            }
+        }
+
+        /**
+         * Close the server socket.
+         *
+         * @throws IOException
+         */
+        @Override
+        public synchronized void close() throws IOException {
+            if (serverSocket != null && !serverSocket.isClosed()) {
+                serverSocket.close();
+            }
+            if (acceptThread != null) {
+                acceptThread.interrupt();
+            }
+        }
+    }
+
+    /**
+     * A small UDP Server that emulates the discard service for tests purposes.
+     * See http://en.wikipedia.org/wiki/Discard_Protocol This server uses an
+     * anonymous port - NOT the standard port 9. We don't guarantee that its
+     * behavior exactly matches the RFC - the only purpose of this server is to
+     * have something that responds to nio tests...
+     */
+    static final class UdpDiscardServer extends AbstractUdpServer {
+
+        public UdpDiscardServer() {
+            this(0L);
+        }
+
+        public UdpDiscardServer(long linger) {
+            super(linger);
+        }
+
+        @Override
+        protected UdpRequestThread createConnection(DatagramSocket socket,
+                DatagramPacket request) {
+            // no response required
+            return null;
+        }
+
+        public static UdpDiscardServer startNewServer() throws IOException {
+            return startNewServer(0);
+        }
+
+        public static UdpDiscardServer startNewServer(long linger) throws IOException {
+            final UdpDiscardServer discardServer = new UdpDiscardServer(linger);
+            discardServer.start();
+            return discardServer;
+        }
+    }
+
+    /**
+     * A small UDP Server that emulates the echo service for tests purposes. See
+     * http://en.wikipedia.org/wiki/Echo_Protocol This server uses an anonymous
+     * port - NOT the standard port 7. We don't guarantee that its behavior
+     * exactly matches the RFC - the only purpose of this server is to have
+     * something that responds to nio tests...
+     */
+    static final class UdpEchoServer extends AbstractUdpServer {
+
+        public UdpEchoServer() {
+            this(0L);
+        }
+
+        public UdpEchoServer(long linger) {
+            super(linger);
+        }
+
+        @Override
+        protected UdpEchoRequest createConnection(DatagramSocket socket,
+                DatagramPacket request) {
+            return new UdpEchoRequest(socket, request);
+        }
+
+        private final class UdpEchoRequest extends UdpRequestThread {
+
+            public UdpEchoRequest(DatagramSocket socket, DatagramPacket request) {
+                super(socket, request);
+            }
+
+            @Override
+            public void run() {
+                try {
+                    lingerIfRequired();
+                    final DatagramPacket response =
+                            new DatagramPacket(request.getData(),
+                                    request.getOffset(), request.getLength(),
+                                    request.getAddress(), request.getPort());
+                    send(socket, response);
+                } catch (IOException io) {
+                    System.err.println("Failed to send response: " + io);
+                    io.printStackTrace(System.err);
+                }
+            }
+        }
+
+        public static UdpEchoServer startNewServer() throws IOException {
+            return startNewServer(0);
+        }
+
+        public static UdpEchoServer startNewServer(long linger) throws IOException {
+            final UdpEchoServer echoServer = new UdpEchoServer(linger);
+            echoServer.start();
+            return echoServer;
+        }
+    }
+
+    /**
+     * A small UDP server that emulates the Day & Time service for tests
+     * purposes. See http://en.wikipedia.org/wiki/Daytime_Protocol This server
+     * uses an anonymous port - NOT the standard port 13. We don't guarantee
+     * that its behavior exactly matches the RFC - the only purpose of this
+     * server is to have something that responds to nio tests...
+     */
+    static final class UdpDayTimeServer extends AbstractUdpServer {
+
+        public UdpDayTimeServer() {
+            this(0L);
+        }
+
+        public UdpDayTimeServer(long linger) {
+            super(linger);
+        }
+
+        @Override
+        protected UdpDayTimeRequestThread createConnection(DatagramSocket socket,
+                DatagramPacket request) {
+            return new UdpDayTimeRequestThread(socket, request);
+        }
+
+        private final class UdpDayTimeRequestThread extends UdpRequestThread {
+
+            public UdpDayTimeRequestThread(DatagramSocket socket,
+                    DatagramPacket request) {
+                super(socket, request);
+            }
+
+            @Override
+            public void run() {
+                try {
+                    lingerIfRequired();
+                    final byte[] data = new Date(System.currentTimeMillis())
+                            .toString().getBytes("US-ASCII");
+                    final DatagramPacket response =
+                            new DatagramPacket(data, 0, data.length,
+                                    request.getAddress(), request.getPort());
+                    send(socket, response);
+                } catch (IOException io) {
+                    System.err.println("Failed to send response: " + io);
+                    io.printStackTrace(System.err);
+                }
+            }
+        }
+
+        public static UdpDayTimeServer startNewServer() throws IOException {
+            return startNewServer(0);
+        }
+
+        public static UdpDayTimeServer startNewServer(long linger)
+                throws IOException {
+            final UdpDayTimeServer echoServer = new UdpDayTimeServer(linger);
+            echoServer.start();
+            return echoServer;
+        }
+    }
+}
--- a/test/java/nio/channels/TestUtil.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/java/nio/channels/TestUtil.java	Sun Dec 02 23:39:15 2012 -0800
@@ -27,7 +27,6 @@
 
 import java.io.*;
 import java.net.*;
-import java.nio.*;
 import java.nio.channels.*;
 import java.util.Random;
 
@@ -36,9 +35,6 @@
 
     // Test hosts used by the channels tests - change these when
     // executing in a different network.
-    public static final String HOST = "javaweb.sfbay.sun.com";
-    public static final String REFUSING_HOST = "jano1.sfbay.sun.com";
-    public static final String FAR_HOST = "irejano.ireland.sun.com";
     public static final String UNRESOLVABLE_HOST = "blah-blah.blah-blah.blah";
 
     private TestUtil() { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/TreeMap/Clone.java	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 7198904
+ * @summary Verify that cloned TreeMap gets new keyset
+ * @author david.buck@oracle.com
+ * @run main/othervm Clone
+ * @run main/othervm -XX:+AggressiveOpts Clone
+ */
+
+import java.util.TreeMap;
+
+public class Clone  {
+
+    public static void main(String[] args) throws Exception {
+        TreeMap<String,Object> m1 = new TreeMap<String,Object>();
+        m1.put( "one", 1 );
+        m1.keySet();
+        TreeMap<String,Object> m2 = (TreeMap<String,Object>)m1.clone();
+        m1.put( "two", 2 );
+        m2.put( "three", 3 );
+        // iterate over the clone (m2) and we should get "one" and "three"
+        for( final String key : m2.keySet() ) {
+            if( !"one".equals( key ) && !"three".equals( key ) ) {
+                throw new IllegalStateException( "Unexpected key: " + key );
+            }
+        }
+        // iterate over the original (m1) and we should get "one" and "two"
+        for( final String key : m1.keySet() ) {
+            if( !"one".equals( key ) && !"two".equals( key ) ) {
+                throw new IllegalStateException( "Unexpected key: " + key );
+            }
+        }
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/misc/IoTrace/IoTraceAgent.java	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import static com.sun.xml.internal.ws.org.objectweb.asm.Opcodes.ACC_FINAL;
+import static com.sun.xml.internal.ws.org.objectweb.asm.Opcodes.ACC_PRIVATE;
+import static com.sun.xml.internal.ws.org.objectweb.asm.Opcodes.ACC_PUBLIC;
+import static com.sun.xml.internal.ws.org.objectweb.asm.Opcodes.ACC_STATIC;
+import static com.sun.xml.internal.ws.org.objectweb.asm.Opcodes.ACC_SUPER;
+import static com.sun.xml.internal.ws.org.objectweb.asm.Opcodes.ILOAD;
+import static com.sun.xml.internal.ws.org.objectweb.asm.Opcodes.INVOKESPECIAL;
+import static com.sun.xml.internal.ws.org.objectweb.asm.Opcodes.INVOKESTATIC;
+import static com.sun.xml.internal.ws.org.objectweb.asm.Opcodes.IRETURN;
+import static com.sun.xml.internal.ws.org.objectweb.asm.Opcodes.RETURN;
+import static com.sun.xml.internal.ws.org.objectweb.asm.Opcodes.V1_6;
+
+import java.lang.instrument.ClassDefinition;
+import java.lang.instrument.Instrumentation;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.net.InetAddress;
+
+import com.sun.xml.internal.ws.org.objectweb.asm.ClassWriter;
+import com.sun.xml.internal.ws.org.objectweb.asm.MethodVisitor;
+import com.sun.xml.internal.ws.org.objectweb.asm.Type;
+import sun.misc.IoTrace;
+
+public class IoTraceAgent {
+
+    private static IoTraceListener listener;
+
+    public static void setListener(IoTraceListener l) {
+        listener = l;
+    }
+
+    public static Object socketReadBegin(InetAddress address, int port,
+            int timeout) {
+        IoTraceListener l = listener;
+        if (l != null) {
+            return l.socketReadBegin(address, port, timeout);
+        }
+        return null;
+    }
+
+    public static void socketReadEnd(Object context, long bytesRead) {
+        IoTraceListener l = listener;
+        if (l != null) {
+            l.socketReadEnd(context, bytesRead);
+        }
+    }
+
+    public static Object socketWriteBegin(InetAddress address, int port) {
+        IoTraceListener l = listener;
+        if (l != null) {
+            return l.socketWriteBegin(address, port);
+        }
+        return null;
+    }
+
+    public static void socketWriteEnd(Object context, long bytesWritten) {
+        IoTraceListener l = listener;
+        if (l != null) {
+            l.socketWriteEnd(context, bytesWritten);
+        }
+    }
+
+    public static Object fileReadBegin(String path) {
+        IoTraceListener l = listener;
+        if (l != null) {
+            return l.fileReadBegin(path);
+        }
+        return null;
+    }
+
+    public static void fileReadEnd(Object context, long bytesRead) {
+        IoTraceListener l = listener;
+        if (l != null) {
+            l.fileReadEnd(context, bytesRead);
+        }
+    }
+
+    public static Object fileWriteBegin(String path) {
+        IoTraceListener l = listener;
+        if (l != null) {
+            return l.fileWriteBegin(path);
+        }
+        return null;
+    }
+
+    public static void fileWriteEnd(Object context, long bytesWritten) {
+        IoTraceListener l = listener;
+        if (l != null) {
+            l.fileWriteEnd(context, bytesWritten);
+        }
+    }
+
+    public static void premain(String agentArgs, Instrumentation inst)
+            throws Exception {
+        ClassDefinition cd = new ClassDefinition(IoTrace.class,
+                generateClassAsm());
+        inst.redefineClasses(cd);
+    }
+
+    private static byte[] generateClassAsm() {
+        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
+        cw.visit(V1_6, ACC_PUBLIC | ACC_SUPER | ACC_FINAL, "sun/misc/IoTrace",
+                null, "java/lang/Object", null);
+
+        // for all methods in the existing IoTrace class
+        // we want to create a method in the new version of it which call
+        // IoTraceAgent
+        //
+        // 0: aload_0
+        // 1: iload_1
+        // 2: iload_2
+        // 3: invokestatic #16 // Method
+        // IoTraceAgent.socketReadBegin:(Ljava/net/InetAddress;II)Ljava/lang/Object;
+        // 6: areturn
+
+        for (Method om : IoTrace.class.getDeclaredMethods()) {
+            if (!Modifier.isStatic(om.getModifiers())) {
+                continue;
+            }
+
+            // create a method with the same signature as the
+            // original method
+            MethodVisitor mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC,
+                    om.getName(), Type.getMethodDescriptor(om), null, null);
+            mv.visitCode();
+
+            // get the return type and argument list types
+            Type[] argTypes = Type.getArgumentTypes(om);
+            Type retType = Type.getReturnType(om);
+
+            // load all the arguments
+            int i = 0;
+            for (Type t : argTypes) {
+                mv.visitVarInsn(t.getOpcode(ILOAD), i++);
+            }
+
+            // call a method with the same signature (but in a different class)
+            // with all the arguments
+            mv.visitMethodInsn(INVOKESTATIC, "IoTraceAgent", om.getName(),
+                    Type.getMethodDescriptor(om));
+
+            // return the value from the called method
+            mv.visitInsn(retType.getOpcode(IRETURN));
+            mv.visitEnd();
+        }
+
+        // empty private constructor
+        MethodVisitor mv = cw.visitMethod(ACC_PRIVATE, "<init>", "()V", null,
+                null);
+        mv.visitCode();
+        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
+        mv.visitInsn(RETURN);
+        mv.visitEnd();
+
+        cw.visitEnd();
+        return cw.toByteArray();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/misc/IoTrace/IoTraceBase.java	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.File;
+import java.net.InetAddress;
+
+
+public class IoTraceBase implements IoTraceListener {
+
+    protected static final Object my_context = new Object() {
+    };
+
+    private String path;
+    private long bytesRead;
+    private long bytesWritten;
+    private Object context;
+    private InetAddress address;
+    private int port;
+    private int timeout;
+
+    protected void clear() {
+        context = null;
+        bytesRead = 0;
+        bytesWritten = 0;
+        address = null;
+        port = 0;
+        timeout = 0;
+        path = null;
+    }
+
+    @Override
+    public Object fileWriteBegin(String p) {
+        path = p;
+        return my_context;
+    }
+
+    @Override
+    public void fileWriteEnd(Object ctx, long bw) {
+        context = ctx;
+        bytesWritten = bw;
+    }
+
+    @Override
+    public Object fileReadBegin(String p) {
+        path = p;
+        return my_context;
+    }
+
+    @Override
+    public void fileReadEnd(Object ctx, long br) {
+        context = ctx;
+        bytesRead = br;
+    }
+
+    @Override
+    public Object socketReadBegin(InetAddress address, int port,
+            int timeout) {
+        this.address = address;
+        this.port = port;
+        this.timeout = timeout;
+        return my_context;
+    }
+
+    @Override
+    public void socketReadEnd(Object context, long bytesRead) {
+        this.context = context;
+        this.bytesRead = bytesRead;
+    }
+
+    @Override
+    public Object socketWriteBegin(InetAddress address, int port) {
+        this.address = address;
+        this.port = port;
+        return my_context;
+    }
+
+    @Override
+    public void socketWriteEnd(Object context, long bytesWritten) {
+        this.context = context;
+        this.bytesWritten = bytesWritten;
+    }
+
+    protected void expectFileRead(long br, File f) throws Exception {
+        expectFile(0, br, f);
+    }
+
+    protected void expectFileWrite(long bw, File f) throws Exception {
+        expectFile(bw, 0, f);
+    }
+
+    protected void expectFile(long bw, long br, File f) throws Exception {
+        if (context != my_context) {
+            throw new Exception("Wrong context: " + context);
+        }
+        if (bytesWritten != bw) {
+            throw new Exception("Expected " + bw + " byte to be read, got: "
+                    + bytesWritten);
+        }
+        if (bytesRead != br) {
+            throw new Exception("Expected " + br + " byte to be read, got: "
+                    + bytesWritten);
+        }
+        if (!path.equals(f.getPath())) {
+            throw new Exception("Incorrect path: " + path + ". Expected: "
+                    + f.getPath());
+        }
+    }
+
+    protected void expectSocket(int br, int bw, InetAddress ia, int p, int t)
+            throws Exception {
+        if (context != my_context) {
+            throw new Exception("Wrong context: " + context);
+        }
+        if (bytesWritten != bw) {
+            throw new Exception("Expected " + bw + " byte to be written, got: "
+                    + bytesWritten);
+        }
+        if (bytesRead != br) {
+            throw new Exception("Expected " + br + " byte to be read, got: "
+                    + bytesWritten);
+        }
+        if (!address.equals(ia)) {
+            throw new Exception("Incorrect address: " + address
+                    + ". Expected: " + ia);
+        }
+        if (port != p) {
+            throw new Exception("Expected " + p + " port, got: " + port);
+        }
+        if (timeout != t) {
+            throw new Exception("Expected " + t + " timeout, got: " + timeout);
+        }
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/misc/IoTrace/IoTraceFileChannelReadWrite.java	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.file.StandardOpenOption;
+
+/*
+ * @test
+ * @bug 8003322
+ * @run shell ioTraceTest.sh IoTraceFileChannelReadWrite
+ */
+public class IoTraceFileChannelReadWrite extends IoTraceBase {
+
+    private void testWrite(File f) throws IOException, FileNotFoundException,
+            Exception {
+        try (FileChannel fc = FileChannel.open(f.toPath(),
+                StandardOpenOption.WRITE)) {
+            ByteBuffer bb = ByteBuffer.allocate(1);
+            bb.put((byte) 11);
+            bb.flip();
+            fc.write(bb);
+        }
+        expectFile(1, 0, f);
+    }
+
+    private void testRead(File f) throws IOException, FileNotFoundException,
+            Exception {
+        try (FileChannel fc = FileChannel.open(f.toPath(),
+                StandardOpenOption.READ)) {
+            ByteBuffer bb = ByteBuffer.allocate(1);
+            fc.read(bb);
+        }
+        expectFile(0, 1, f);
+    }
+
+    public void test() throws Exception {
+        IoTraceAgent.setListener(this);
+        File f = File.createTempFile("IoTraceFileChannelReadWrite", ".bin");
+        try {
+            clear();
+            testWrite(f);
+            clear();
+            testRead(f);
+        } finally {
+            f.delete();
+        }
+    }
+
+    public static void main(String... args) throws Exception {
+        IoTraceFileChannelReadWrite t = new IoTraceFileChannelReadWrite();
+        t.test();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/misc/IoTrace/IoTraceFileReadWrite.java	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+
+/*
+ * @test
+ * @bug 8003322
+ * @run shell ioTraceTest.sh IoTraceFileReadWrite
+ */
+public class IoTraceFileReadWrite extends IoTraceBase {
+
+    private void testWrite(File f) throws IOException, FileNotFoundException,
+            Exception {
+        try (FileOutputStream fos = new FileOutputStream(f)) {
+            fos.write(11);
+        }
+        expectFile(1, 0, f);
+    }
+
+
+    private void testRead(File f) throws IOException, FileNotFoundException,
+            Exception {
+        try (FileInputStream fos = new FileInputStream(f)) {
+            fos.read();
+        }
+        expectFile(0, 1, f);
+    }
+
+    private void testRandomAccessWrite(File f) throws Exception {
+        try (RandomAccessFile raf = new RandomAccessFile(f, "rw")) {
+            raf.write(11);
+        }
+        expectFile(1, 0, f);
+    }
+
+    private void testRandomAccessRead(File f) throws Exception {
+        try (RandomAccessFile raf = new RandomAccessFile(f, "r")) {
+            raf.read();
+        }
+        expectFile(0, 1, f);
+    }
+
+    public void test() throws Exception {
+        IoTraceAgent.setListener(this);
+        File f = File.createTempFile("IoTraceFileReadWrite", ".bin");
+        try {
+            clear();
+            testWrite(f);
+            clear();
+            testRead(f);
+            clear();
+            testRandomAccessWrite(f);
+            clear();
+            testRandomAccessRead(f);
+        } finally {
+            f.delete();
+        }
+    }
+
+    public static void main(String... args) throws Exception {
+        IoTraceFileReadWrite t = new IoTraceFileReadWrite();
+        t.test();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/misc/IoTrace/IoTraceListener.java	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.net.InetAddress;
+
+import sun.misc.IoTrace;
+
+/**
+ * Implementations of this interface can be registered with
+ * {@link IoTrace#setListener(IoTraceListener)} to receive callbacks when file
+ * and socket operations are performed.
+ * <p>
+ * The xxBegin() methods return a "context". This can be any Object. This
+ * context will be passed to the corresponding xxEnd() method. This way, an
+ * implementation can correlate the beginning of an operation with the end.
+ * <p>
+ * It is possible for a xxEnd() method to be called with a null handle. This
+ * happens if tracing was started between the call to xxBegin() and xxEnd(), in
+ * which case xxBegin() would not have been called. It is the implementation's
+ * responsibility to not throw an exception in this case.
+ * <p>
+ * Implementations should never throw exceptions since this will cause
+ * disruptions to the I/O operations.
+ * <p>
+ * An xxBegin() call is not guaranteed to be followed by an xxEnd() call, since
+ * the listener in IoTrace can be reset at any time.
+ */
+public interface IoTraceListener {
+
+    /**
+     * Called before data is read from a socket.
+     *
+     * @param address
+     *            the remote address the socket is bound to
+     * @param port
+     *            the remote port the socket is bound to
+     * @param timeout
+     *            the SO_TIMEOUT value of the socket (in milliseconds) or 0 if
+     *            there is no timeout set
+     * @return a context object
+     */
+    public Object socketReadBegin(InetAddress address, int port, int timeout);
+
+    /**
+     * Called after data is read from the socket.
+     *
+     * @param context
+     *            the context returned by the previous call to socketReadBegin()
+     * @param bytesRead
+     *            the number of bytes read from the socket, 0 if there was an
+     *            error reading from the socket
+     */
+    public void socketReadEnd(Object context, long bytesRead);
+
+    /**
+     * Called before data is written to a socket.
+     *
+     * @param address
+     *            the remote address the socket is bound to
+     * @param port
+     *            the remote port the socket is bound to
+     * @return a context object
+     */
+    public Object socketWriteBegin(InetAddress address, int port);
+
+    /**
+     * Called after data is written to a socket.
+     *
+     * @param context
+     *            the context returned by the previous call to
+     *            socketWriteBegin()
+     * @param bytesWritten
+     *            the number of bytes written to the socket, 0 if there was an
+     *            error writing to the socket
+     */
+    public void socketWriteEnd(Object context, long bytesWritten);
+
+    /**
+     * Called before data is read from a file.
+     *
+     * @param path
+     *            the path of the file
+     * @return a context object
+     */
+    public Object fileReadBegin(String path);
+
+    /**
+     * Called after data is read from a file.
+     *
+     * @param context
+     *            the context returned by the previous call to fileReadBegin()
+     * @param bytesRead
+     *            the number of bytes written to the file, 0 if there was an
+     *            error writing to the file
+     */
+    public void fileReadEnd(Object context, long bytesRead);
+
+    /**
+     * Called before data is written to a file.
+     *
+     * @param path
+     *            the path of the file
+     * @return a context object
+     */
+    public Object fileWriteBegin(String path);
+
+    /**
+     * Called after data is written to a file.
+     *
+     * @param context
+     *            the context returned by the previous call to fileReadBegin()
+     * @param bytesWritten
+     *            the number of bytes written to the file, 0 if there was an
+     *            error writing to the file
+     */
+    public void fileWriteEnd(Object context, long bytesWritten);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/misc/IoTrace/IoTraceSocketReadWrite.java	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+
+/*
+ * @test
+ * @bug 8003322
+ * @run shell ioTraceTest.sh IoTraceSocketReadWrite
+ */
+public class IoTraceSocketReadWrite extends IoTraceBase {
+
+    public void test() throws Exception {
+        IoTraceAgent.setListener(this);
+
+        ServerSocket ss = null;
+        Socket s1 = null, s2 = null;
+        OutputStream os = null;
+        InputStream is = null;
+
+        try {
+            InetAddress iaddr = InetAddress.getLocalHost();
+            ss = new ServerSocket(0);
+            s1 = new Socket(iaddr, ss.getLocalPort());
+            s2 = ss.accept();
+
+            os = s1.getOutputStream();
+            is = s2.getInputStream();
+
+            os.write((byte) 11);
+            is.read();
+
+            expectSocket(1, 1, s2.getInetAddress(), s2.getPort(), 0);
+
+        } finally {
+            if (ss != null) {
+                ss.close();
+            }
+            if (s1 != null) {
+                s1.close();
+            }
+            if (s2 != null) {
+                s2.close();
+            }
+        }
+    }
+
+    public static void main(String... args) throws Exception {
+        IoTraceSocketReadWrite t = new IoTraceSocketReadWrite();
+        t.test();
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/misc/IoTrace/ioTraceTest.sh	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,34 @@
+#
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+set -x
+PWD=`pwd`
+
+cd ${TESTSRC}
+${TESTJAVA}/bin/javac -XDignore.symbol.file=true -d ${TESTCLASSES} *.java
+
+cd ${TESTCLASSES}
+${TESTJAVA}/bin/jar cfm iotraceagent.jar ${TESTSRC}/iotraceagent.mf IoTraceAgent.class IoTraceListener.class
+
+cd ${PWD}
+${TESTJAVA}/bin/java ${TESTVMOPTS} -javaagent:${TESTCLASSES}/iotraceagent.jar -cp ${TESTCLASSES} $*
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/misc/IoTrace/iotraceagent.mf	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,3 @@
+Premain-Class: IoTraceAgent
+Can-Redefine-Classes: true
+Boot-Class-Path: iotraceagent.jar
--- a/test/sun/security/krb5/auto/BadKdc.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/sun/security/krb5/auto/BadKdc.java	Sun Dec 02 23:39:15 2012 -0800
@@ -67,7 +67,7 @@
      *       This is tough.
      *    c. Feed the KDC a UDP packet first. The current "solution".
      */
-    public static void go(int[]... expected)
+    public static void go(String... expected)
             throws Exception {
         try {
             go0(expected);
@@ -83,7 +83,7 @@
         }
     }
 
-    public static void go0(int[]... expected)
+    public static void go0(String... expected)
             throws Exception {
         System.setProperty("sun.security.krb5.debug", "true");
 
@@ -135,8 +135,9 @@
         return k;
     }
 
-    private static void test(int... expected) throws Exception {
+    private static void test(String expected) throws Exception {
         ByteArrayOutputStream bo = new ByteArrayOutputStream();
+        System.out.println("----------------- TEST -----------------");
         try {
             test0(bo, expected);
         } catch (Exception e) {
@@ -151,31 +152,34 @@
      * One round of test for max_retries and timeout.
      * @param expected the expected kdc# timeout kdc# timeout...
      */
-    private static void test0(ByteArrayOutputStream bo, int... expected)
+    private static void test0(ByteArrayOutputStream bo, String expected)
             throws Exception {
         PrintStream oldout = System.out;
+        boolean failed = false;
         System.setOut(new PrintStream(bo));
         try {
             Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false);
+        } catch (Exception e) {
+            failed = true;
         } finally {
             System.setOut(oldout);
         }
 
         String[] lines = new String(bo.toByteArray()).split("\n");
-        System.out.println("----------------- TEST -----------------");
-        int count = 0;
+        StringBuilder sb = new StringBuilder();
         for (String line: lines) {
             Matcher m = re.matcher(line);
             if (m.find()) {
                 System.out.println(line);
-                if (Integer.parseInt(m.group(1)) != expected[count++] ||
-                        Integer.parseInt(m.group(2)) != expected[count++]) {
-                    throw new Exception("Fail here");
-                }
+                sb.append(m.group(1)).append(m.group(2));
             }
         }
-        if (count != expected.length) {
-            throw new Exception("Less rounds");
+        if (failed) sb.append('-');
+
+        String output = sb.toString();
+        System.out.println("Expected: " + expected + ", actual " + output);
+        if (!output.matches(expected)) {
+            throw new Exception("Does not match");
         }
     }
 }
--- a/test/sun/security/krb5/auto/BadKdc1.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/sun/security/krb5/auto/BadKdc1.java	Sun Dec 02 23:39:15 2012 -0800
@@ -37,16 +37,16 @@
            throws Exception {
        Security.setProperty("krb5.kdc.bad.policy", "tryLess");
        BadKdc.go(
-               new int[]{1,2,1,2,1,2,2,2,2,2,2,2,3,2,1,2,2,2,3,2}, // 1, 2
-               // The above line means try kdc1 for 2 seconds, then kdc1
-               // for 2 seconds,..., finally kdc3 for 2 seconds.
-               new int[]{1,2,2,2,3,2,1,2,2,2,3,2}, // 1, 2
+               "121212222222(32){1,2}1222(32){1,2}", // 1 2
+               // The above line means try kdc1 for 2 seconds then kdc1
+               // for 2 seconds... finally kdc3 for 2 seconds.
+               "1222(32){1,2}1222(32){1,2}",    // 1 2
                // refresh
-               new int[]{1,2,1,2,1,2,2,2,2,2,2,2,3,2,1,2,2,2,3,2}, // 1, 2
-               // k3 off, k2 on
-               new int[]{1,2,2,2,1,2,2,2}, // 1
+               "121212222222(32){1,2}1222(32){1,2}",  // 1 2
+               // k3 off k2 on
+               "(122212(22){1,2}|1222323232-)", // 1
                // k1 on
-               new int[]{1,2,1,2}  // empty
+               "(12(12){1,2}|122232-)"  // empty
        );
    }
 }
--- a/test/sun/security/krb5/auto/BadKdc2.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/sun/security/krb5/auto/BadKdc2.java	Sun Dec 02 23:39:15 2012 -0800
@@ -37,14 +37,14 @@
             throws Exception {
         Security.setProperty("krb5.kdc.bad.policy", "tryLess:2,1000");
         BadKdc.go(
-                new int[]{1,2,1,2,1,2,2,2,2,2,2,2,3,2,1,1,1,1,2,1,2,1,3,2}, // 1, 2
-                new int[]{1,1,1,1,2,1,2,1,3,2,1,1,1,1,2,1,2,1,3,2}, // 1, 2
+                "121212222222(32){1,2}11112121(32){1,2}", // 1 2
+                "11112121(32){1,2}11112121(32){1,2}", // 1 2
                 // refresh
-                new int[]{1,2,1,2,1,2,2,2,2,2,2,2,3,2,1,1,1,1,2,1,2,1,3,2}, // 1, 2
-                // k3 off, k2 on
-                new int[]{1,1,1,1,2,1,1,1,1,1,2,2}, // 1
+                "121212222222(32){1,2}11112121(32){1,2}", // 1 2
+                // k3 off k2 on
+                "1111(21){1,2}1111(22){1,2}", // 1
                 // k1 on
-                new int[]{1,1,1,2}  // empty
+                "(11){1,2}(12){1,2}"  // empty
         );
     }
 }
--- a/test/sun/security/krb5/auto/BadKdc3.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/sun/security/krb5/auto/BadKdc3.java	Sun Dec 02 23:39:15 2012 -0800
@@ -37,14 +37,14 @@
             throws Exception {
         Security.setProperty("krb5.kdc.bad.policy", "tryLast");
         BadKdc.go(
-                new int[]{1,2,1,2,1,2,2,2,2,2,2,2,3,2,3,2}, // 1, 2
-                new int[]{3,2,3,2}, // 1, 2
+                "121212222222(32){2,4}", // 1 2
+                "(32){2,4}", // 1 2
                 // refresh
-                new int[]{1,2,1,2,1,2,2,2,2,2,2,2,3,2,3,2}, // 1, 2
-                // k3 off, k2 on
-                new int[]{3,2,3,2,3,2,1,2,1,2,1,2,2,2,2,2}, // 1, 3
+                "121212222222(32){2,4}", // 1 2
+                // k3 off k2 on
+                "323232121212(22){2,4}", // 1 3
                 // k1 on
-                new int[]{2,2,2,2}  // 1, 3
+                "(22){2,4}"  // 1 3
         );
     }
 }
--- a/test/sun/security/krb5/auto/BadKdc4.java	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/sun/security/krb5/auto/BadKdc4.java	Sun Dec 02 23:39:15 2012 -0800
@@ -37,14 +37,14 @@
             throws Exception {
         Security.setProperty("krb5.kdc.bad.policy", "");
         BadKdc.go(
-            new int[]{1,2,1,2,1,2,2,2,2,2,2,2,3,2,1,2,1,2,1,2,2,2,2,2,2,2,3,2},
-            new int[]{1,2,1,2,1,2,2,2,2,2,2,2,3,2,1,2,1,2,1,2,2,2,2,2,2,2,3,2},
+            "121212222222(32){1,2}121212222222(32){1,2}",
+            "121212222222(32){1,2}121212222222(32){1,2}",
             // refresh
-            new int[]{1,2,1,2,1,2,2,2,2,2,2,2,3,2,1,2,1,2,1,2,2,2,2,2,2,2,3,2},
-            // k3 off, k2 on
-            new int[]{1,2,1,2,1,2,2,2,1,2,1,2,1,2,2,2},
+            "121212222222(32){1,2}121212222222(32){1,2}",
+            // k3 off k2 on
+            "121212(22){1,2}121212(22){1,2}",
             // k1 on
-            new int[]{1,2,1,2}
+            "(12){2,4}"
         );
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/krb5/config/DNS.java	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// See dns.sh.
+import sun.security.krb5.Config;
+
+public class DNS {
+    public static void main(String[] args) throws Exception {
+        System.setProperty("java.security.krb5.conf",
+                System.getProperty("test.src", ".") +"/nothing.conf");
+        Config config = Config.getInstance();
+        String kdcs = config.getKDCList("X");
+        if (!kdcs.equals("a.com.:88 b.com.:99") &&
+                !kdcs.equals("a.com. b.com.:99")) {
+            throw new Exception("Strange KDC: [" + kdcs + "]");
+        };
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/krb5/config/NamingManager.java	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package javax.naming.spi;
+
+import com.sun.jndi.dns.DnsContext;
+import java.util.Hashtable;
+import javax.naming.Context;
+import javax.naming.NamingException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.BasicAttribute;
+import javax.naming.directory.BasicAttributes;
+
+/**
+ * A fake javax.naming.spi.NamingManager. It allows reading a DNS
+ * record without contacting a real server.
+ *
+ * See DNS.java and dns.sh.
+ */
+public class NamingManager {
+    NamingManager() {}
+    public static Context getURLContext(
+            String scheme, Hashtable<?,?> environment)
+            throws NamingException {
+        return new DnsContext("", null, new Hashtable<String,String>()) {
+            public Attributes getAttributes(String name, String[] attrIds)
+                    throws NamingException {
+                return new BasicAttributes() {
+                    public Attribute get(String attrID) {
+                        BasicAttribute ba  = new BasicAttribute(attrID);
+                        ba.add("1 1 99 b.com.");
+                        ba.add("0 0 88 a.com.");    // 2nd has higher priority
+                        return ba;
+                    }
+                };
+            }
+        };
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/sun/security/krb5/config/dns.sh	Sun Dec 02 23:39:15 2012 -0800
@@ -0,0 +1,41 @@
+#
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+# @test
+# @bug 8002344
+# @summary Krb5LoginModule config class does not return proper KDC list from DNS
+#
+
+if [ "${TESTJAVA}" = "" ] ; then
+  JAVAC_CMD=`which javac`
+  TESTJAVA=`dirname $JAVAC_CMD`/..
+fi
+
+if [ "${TESTSRC}" = "" ] ; then
+   TESTSRC="."
+fi
+
+$TESTJAVA/bin/javac -d . \
+        ${TESTSRC}/NamingManager.java ${TESTSRC}/DNS.java
+$TESTJAVA/bin/java -Xbootclasspath/p:. DNS
+
--- a/test/sun/tools/jinfo/Basic.sh	Thu Nov 29 19:42:30 2012 -0800
+++ b/test/sun/tools/jinfo/Basic.sh	Sun Dec 02 23:39:15 2012 -0800
@@ -44,7 +44,20 @@
 
 failed=0
 
-if [ $isWindows = false ]; then
+# Skip SA options for now, see 7175133
+runSA=false
+
+if [ $isLinux = true ]; then
+    # Some Linux systems disable non-child ptrace (see 7050524)
+    ptrace_scope=`/sbin/sysctl -n kernel.yama.ptrace_scope`
+    if [ $? = 0 ]; then
+        if [ $ptrace_scope = 1 ]; then
+            runSA=false
+        fi
+    fi
+fi
+
+if [ $runSA = true ]; then
     # -sysprops option
     ${JINFO} -J-XX:+UsePerfData -sysprops $appJavaPid
     if [ $? != 0 ]; then failed=1; fi