changeset 10871:c82051dfbe73

Merge
author prr
date Mon, 20 Oct 2014 12:04:12 -0700
parents 8cf2f9e29de6 57d07aa0a0eb
children be34425400ec
files src/java.desktop/unix/classes/sun/print/CUPSPrinter.java src/java.desktop/unix/classes/sun/print/IPPPrintService.java test/java/security/cert/CertificateFactory/invalidEncodedCerts/invalidcert.pem
diffstat 78 files changed, 3256 insertions(+), 465 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Mon Oct 20 11:22:58 2014 -0700
+++ b/.hgtags	Mon Oct 20 12:04:12 2014 -0700
@@ -277,3 +277,4 @@
 8bdf7083b5bd02aa330ba622895e586dd3378d37 jdk9-b32
 60fe681c30bc3821545a2506d4d3c2e04073f67c jdk9-b33
 21568031434d7a9dbb0cc6516cc3183d349c2253 jdk9-b34
+e549291a0227031310fa91c574891f892d27f959 jdk9-b35
--- a/make/gensrc/Gensrc-java.base.gmk	Mon Oct 20 11:22:58 2014 -0700
+++ b/make/gensrc/Gensrc-java.base.gmk	Mon Oct 20 12:04:12 2014 -0700
@@ -25,10 +25,6 @@
 
 include GensrcCommon.gmk
 
-# TODO: maybe split into separate modules?
-include GensrcProperties.gmk
-GENSRC_JAVA_BASE += $(GENSRC_PROPERTIES)
-
 include GensrcLocaleData.gmk
 include GensrcCharacterData.gmk
 include GensrcMisc.gmk
@@ -37,6 +33,34 @@
 include GensrcBuffer.gmk
 include GensrcExceptions.gmk
 
+################################################################################
+
+include GensrcProperties.gmk
+
+$(eval $(call SetupCompileProperties,LIST_RESOURCE_BUNDLE, \
+    $(filter %.properties, \
+        $(call CacheFind, $(JDK_TOPDIR)/src/java.base/share/classes/sun/launcher/resources)), \
+    ListResourceBundle))
+
+$(eval $(call SetupCompileProperties,SUN_UTIL, \
+    $(filter %.properties, \
+        $(call CacheFind, $(JDK_TOPDIR)/src/java.base/share/classes/sun/util/resources)), \
+    sun.util.resources.LocaleNamesBundle))
+
+GENSRC_JAVA_BASE += $(LIST_RESOURCE_BUNDLE) $(SUN_UTIL)
+
+# Some resources bundles are already present as java files but still need to be
+# copied to zh_HK locale.
+$(eval $(call SetupCopy-zh_HK,COPY_ZH_HK, \
+    $(addprefix $(JDK_TOPDIR)/src/java.base/share/classes/, \
+        sun/misc/resources/Messages_zh_TW.java \
+        sun/security/util/AuthResources_zh_TW.java \
+        sun/security/util/Resources_zh_TW.java)))
+
+GENSRC_JAVA_BASE += $(COPY_ZH_HK)
+
+################################################################################
+
 java.base: $(GENSRC_JAVA_BASE)
 
 all: java.base
--- a/make/gensrc/Gensrc-java.desktop.gmk	Mon Oct 20 11:22:58 2014 -0700
+++ b/make/gensrc/Gensrc-java.desktop.gmk	Mon Oct 20 12:04:12 2014 -0700
@@ -38,6 +38,48 @@
 
 include GensrcSwing.gmk
 
+################################################################################
+
+include GensrcProperties.gmk
+
+PROP_SRC_DIRS := \
+    $(JDK_TOPDIR)/src/java.desktop/share/classes/sun/awt/resources \
+    $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/accessibility/internal/resources \
+    $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/resources \
+    $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/resources \
+    $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/swing/internal/plaf/basic/resources \
+    $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/swing/internal/plaf/metal/resources \
+    $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/swing/internal/plaf/synth/resources \
+    $(JDK_TOPDIR)/src/java.desktop/share/classes/sun/print/resources \
+    #
+
+ifeq ($(OPENJDK_TARGET_OS), macosx)
+  PROP_SRC_DIRS += \
+      $(JDK_TOPDIR)/src/java.desktop/macosx/classes/com/apple/laf/resources \
+      $(JDK_TOPDIR)/src/java.desktop/macosx/classes/sun/awt/resources \
+      #
+endif
+
+ifeq ($(OPENJDK_TARGET_OS), windows)
+  PROP_SRC_DIRS += $(JDK_TOPDIR)/src/java.desktop/windows/classes/sun/awt/windows
+else
+  PROP_SRC_DIRS += $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/resources
+endif
+
+$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES, \
+    $(filter %.properties, $(call CacheFind, $(PROP_SRC_DIRS))), ListResourceBundle))
+
+GENSRC_JAVA_DESKTOP += $(COMPILE_PROPERTIES)
+
+# Some resources bundles are already present as java files but still need to be
+# copied to zh_HK locale.
+$(eval $(call SetupCopy-zh_HK,COPY_ZH_HK, \
+    $(JDK_TOPDIR)/src/java.desktop/share/classes/sun/applet/resources/MsgAppletViewer_zh_TW.java))
+
+GENSRC_JAVA_DESKTOP += $(COPY_ZH_HK)
+
+################################################################################
+
 java.desktop: $(GENSRC_JAVA_DESKTOP)
 
 all: java.desktop
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/gensrc/Gensrc-java.logging.gmk	Mon Oct 20 12:04:12 2014 -0700
@@ -0,0 +1,43 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+include GensrcCommon.gmk
+
+################################################################################
+
+include GensrcProperties.gmk
+
+$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES, \
+    $(filter %.properties, \
+        $(call CacheFind, $(JDK_TOPDIR)/src/java.logging/share/classes/sun/util/logging/resources)), \
+    ListResourceBundle))
+
+TARGETS += $(COMPILE_PROPERTIES)
+
+################################################################################
+
+all: $(TARGETS)
+
+.PHONY: all
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/gensrc/Gensrc-java.management.gmk	Mon Oct 20 12:04:12 2014 -0700
@@ -0,0 +1,43 @@
+#
+# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+include GensrcCommon.gmk
+
+################################################################################
+
+include GensrcProperties.gmk
+
+$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES, \
+    $(filter %.properties, \
+        $(call CacheFind, $(JDK_TOPDIR)/src/java.management/share/classes/sun/management/resources)), \
+    ListResourceBundle))
+
+TARGETS += $(COMPILE_PROPERTIES)
+
+################################################################################
+
+all: $(TARGETS)
+
+.PHONY: all
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/gensrc/Gensrc-jdk.dev.gmk	Mon Oct 20 12:04:12 2014 -0700
@@ -0,0 +1,43 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+include GensrcCommon.gmk
+
+################################################################################
+
+include GensrcProperties.gmk
+
+$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES, \
+    $(filter %.properties, \
+        $(call CacheFind, $(JDK_TOPDIR)/src/jdk.dev/share/classes/sun/tools/jar/resources)), \
+    ListResourceBundle))
+
+TARGETS += $(COMPILE_PROPERTIES)
+
+################################################################################
+
+all: $(TARGETS)
+
+.PHONY: all
--- a/make/gensrc/Gensrc-jdk.jdi.gmk	Mon Oct 20 11:22:58 2014 -0700
+++ b/make/gensrc/Gensrc-jdk.jdi.gmk	Mon Oct 20 12:04:12 2014 -0700
@@ -69,6 +69,17 @@
 
 ################################################################################
 
+include GensrcProperties.gmk
+
+$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES, \
+    $(filter %.properties, \
+        $(call CacheFind, $(JDK_TOPDIR)/src/jdk.jdi/share/classes/com/sun/tools/jdi/resources)), \
+    ListResourceBundle))
+
+GENSRC_JDK_JDI += $(COMPILE_PROPERTIES)
+
+################################################################################
+
 jdk.jdi: $(GENSRC_JDK_JDI)
 
 all: jdk.jdi
--- a/make/gensrc/Gensrc-jdk.localedata.gmk	Mon Oct 20 11:22:58 2014 -0700
+++ b/make/gensrc/Gensrc-jdk.localedata.gmk	Mon Oct 20 12:04:12 2014 -0700
@@ -31,6 +31,20 @@
 include GensrcLocaleData.gmk
 include GensrcCLDR.gmk
 
+################################################################################
+
+include GensrcProperties.gmk
+
+$(eval $(call SetupCompileProperties,COMPILE_PROPERTIES, \
+    $(filter %.properties, \
+        $(call CacheFind, $(JDK_TOPDIR)/src/jdk.localedata/share/classes/sun/util/resources)), \
+    sun.util.resources.LocaleNamesBundle))
+
+# Skip generating zh_HK from zh_TW for this module.
+GENSRC_JDK_LOCALEDATA += $(filter-out %_zh_HK.java, $(COMPILE_PROPERTIES))
+
+################################################################################
+
 jdk.localedata: $(GENSRC_JDK_LOCALEDATA)
 
 all: jdk.localedata
--- a/make/gensrc/GensrcProperties.gmk	Mon Oct 20 11:22:58 2014 -0700
+++ b/make/gensrc/GensrcProperties.gmk	Mon Oct 20 12:04:12 2014 -0700
@@ -23,132 +23,81 @@
 # questions.
 #
 
-# All .properties files to be compiled are appended to this variable.
-ALL_COMPILED_PROPSOURCES :=
-# All generated .java files from compilation are appended to this variable.
-ALL_COMPILED_PROPJAVAS :=
-# The (very long) command line for compilation, stored in a file, prior to use.
-COMPILE_PROPCMDLINE :=
+# This file defines macros that sets up rules for generating java classes
+# from resource bundle properties files.
 
-define add_properties_to_compile
-  # $1 is the name of the properties group
-  # $2 is the files belonging to this group
-  # $3 is the super class for the generated java file.
+################################################################################
+# Helper macro for SetupCopy-zh_HK.
+define SetupOneCopy-zh_HK
+  $1_$2_TARGET := $$(patsubst $(JDK_TOPDIR)/src/$(MODULE)/share/classes/%, \
+      $(JDK_OUTPUTDIR)/gensrc/$(MODULE)/%, \
+      $$(subst _zh_TW,_zh_HK, $2))
 
-  # Convert <root>/jdk/src/<module>/share/classes/sun/util/resources/CurrencyNames_sv.properties
-  # to <build>/jdk/gensrc/<module/sun/util/resources/CurrencyNames_sv.java
-  $1_PROPJAVAS := $$(patsubst $(JDK_TOPDIR)/src/%.properties, \
-      $(JDK_OUTPUTDIR)/gensrc/%.java, \
-      $$(subst /share/classes,, \
-      $$(subst /$(OPENJDK_TARGET_OS_API_DIR)/classes,, \
-      $$(subst /$(OPENJDK_TARGET_OS)/classes,, $2))))
+  $$($1_$2_TARGET): $2
+	$(MKDIR) -p $$(@D)
+	$(CAT) $$< | $(SED) -e '/class/s/_zh_TW/_zh_HK/' > $$@
 
-  # Accumulate all found properties files.
-  ALL_COMPILED_PROPSOURCES += $2
-
-  # Generate the list of to be created java files.
-  ALL_COMPILED_PROPJAVAS += $$($1_PROPJAVAS)
-
-  # Now generate a sequence of 
-  # "-compile ...CurrencyNames_sv.properties ...CurrencyNames_sv.java ListResourceBundle"
-  # suitable to be fed into the CompileProperties command.
-  COMPILE_PROPCMDLINE += $$(subst _SPACE_,$(SPACE),$$(join $$(addprefix -compile_SPACE_, $2), \
-      $$(addsuffix _SPACE_$(strip $3), \
-      $$(addprefix _SPACE_, $$($1_PROPJAVAS)))))
+  $1 += $$($1_$2_TARGET)
 endef
 
 ################################################################################
-# Some packages have properties that need to be converted to java source files.
-COMPILE_PROP_SRC_FILES := \
-    $(filter %.properties, $(call CacheFind, \
-        $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/accessibility/internal/resources \
-        $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/resources \
-        $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/resources \
-        $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/swing/internal/plaf/basic/resources \
-        $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/swing/internal/plaf/metal/resources \
-        $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/swing/internal/plaf/synth/resources \
-        $(JDK_TOPDIR)/src/jdk.jdi/share/classes/com/sun/tools/jdi/resources \
-        $(JDK_TOPDIR)/src/java.desktop/share/classes/sun/awt/resources \
-        $(JDK_TOPDIR)/src/java.base/share/classes/sun/launcher/resources \
-        $(JDK_TOPDIR)/src/java.management/share/classes/sun/management/resources \
-        $(JDK_TOPDIR)/src/java.desktop/share/classes/sun/print/resources \
-        $(JDK_TOPDIR)/src/jdk.dev/share/classes/sun/tools/jar/resources \
-        $(JDK_TOPDIR)/src/java.logging/share/classes/sun/util/logging/resources)) \
-    #
-
-ifeq ($(OPENJDK_TARGET_OS), macosx)
-  COMPILE_PROP_SRC_FILES += \
-      $(filter %.properties, $(call CacheFind, \
-          $(JDK_TOPDIR)/src/java.desktop/macosx/classes/com/apple/laf/resources \
-          $(JDK_TOPDIR)/src/java.desktop/macosx/classes/sun/awt/resources)) \
-      #
-endif
-
-ifeq ($(OPENJDK_TARGET_OS), windows)
-  COMPILE_PROP_SRC_FILES += \
-      $(filter %.properties, $(call CacheFind, \
-          $(JDK_TOPDIR)/src/java.desktop/windows/classes/sun/awt/windows)) \
-      #
-else # ! windows
-  COMPILE_PROP_SRC_FILES += \
-      $(filter %.properties, $(call CacheFind, \
-          $(JDK_TOPDIR)/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/resources)) \
-      #
-endif
-
-$(eval $(call add_properties_to_compile,LIST_RESOURCE_BUNDLE, \
-    $(COMPILE_PROP_SRC_FILES), ListResourceBundle))
-
-# sun/util/resources
-$(eval $(call add_properties_to_compile,SUN_UTIL, \
-    $(filter %.properties, \
-        $(call CacheFind, $(JDK_TOPDIR)/src/java.base/share/classes/sun/util/resources) \
-        $(call CacheFind, $(JDK_TOPDIR)/src/jdk.localedata/share/classes/sun/util/resources)), \
-    sun.util.resources.LocaleNamesBundle))
+# Creates rules for copying zh_TW resources to zh_HK.
+# Param 1 - Variable to add targets to
+# Param 2 - Files to copy from
+define SetupCopy-zh_HK
+  $$(foreach f, $2, $$(eval $$(call SetupOneCopy-zh_HK,$1,$$f)))
+endef
 
 ################################################################################
-# Now setup the rule for the generation of the resource bundles.
-$(JDK_OUTPUTDIR)/gensrc/_the.compiled_properties: $(ALL_COMPILED_PROPSOURCES) $(BUILD_TOOLS_JDK)
-        # Generate all output directories in advance since the build tool does not do that...
-	$(MKDIR) -p $(sort $(dir $(ALL_COMPILED_PROPJAVAS)))
-	$(ECHO) Compiling $(words $(ALL_COMPILED_PROPSOURCES)) properties into resource bundles
-	$(call ListPathsSafely,COMPILE_PROPCMDLINE,\n, >> $(JDK_OUTPUTDIR)/gensrc/_the.cmdline)
-	$(TOOL_COMPILEPROPERTIES) -quiet @$(JDK_OUTPUTDIR)/gensrc/_the.cmdline
-	$(TOUCH) $@
+# Creates a rule that runs CompileProperties on a set of properties files.
+# Param 1 - Variable to add targets to, must not contain space
+# Param 2 - Properties files to process
+# Param 3 - The super class for the generated classes
+define SetupCompileProperties
+  $1_SRCS := $2
+  $1_CLASS := $3
 
-$(ALL_COMPILED_PROPJAVAS): $(JDK_OUTPUTDIR)/gensrc/_the.compiled_properties
+  # Convert .../src/<module>/share/classes/com/sun/tools/javac/resources/javac_zh_CN.properties
+  # to .../langtools/gensrc/<module>/com/sun/tools/javac/resources/javac_zh_CN.java
+  # Strip away prefix and suffix, leaving for example only: 
+  # "<module>/share/classes/com/sun/tools/javac/resources/javac_zh_CN"
+  $1_JAVAS := $$(patsubst $(JDK_TOPDIR)/src/%, \
+      $(JDK_OUTPUTDIR)/gensrc/%, \
+      $$(patsubst %.properties, %.java, \
+      $$(subst /share/classes,, $$($1_SRCS))))
+
+  # Generate the package dirs for the to be generated java files. Sort to remove
+  # duplicates.
+  $1_DIRS := $$(sort $$(dir $$($1_JAVAS)))
+
+  # Now generate a sequence of:
+  # "-compile ...javac_zh_CN.properties ...javac_zh_CN.java java.util.ListResourceBundle"
+  # suitable to be fed into the CompileProperties command.
+  $1_CMDLINE := $$(subst _SPACE_, $(SPACE), \
+      $$(join $$(addprefix -compile_SPACE_, $$($1_SRCS)), \
+      $$(addsuffix _SPACE_$$($1_CLASS), \
+      $$(addprefix _SPACE_, $$($1_JAVAS)))))
+
+  $1_TARGET := $(JDK_OUTPUTDIR)/gensrc/$(MODULE)/_the.$1.done
+  $1_CMDLINE_FILE := $(JDK_OUTPUTDIR)/gensrc/$(MODULE)/_the.$1.cmdline
+
+  # Now setup the rule for the generation of the resource bundles.
+  $$($1_TARGET): $$($1_SRCS) $$($1_JAVAS) $(BUILD_TOOLS_JDK)
+	$(MKDIR) -p $$(@D) $$($1_DIRS)
+	$(ECHO) Compiling $$(words $$($1_SRCS)) properties into resource bundles for $(MODULE)
+	$(RM) $$($1_CMDLINE_FILE)
+	$$(call ListPathsSafely,$1_CMDLINE,\n, >> $$($1_CMDLINE_FILE))
+	$(TOOL_COMPILEPROPERTIES) -quiet @$$($1_CMDLINE_FILE)
+	$(TOUCH) $$@
+
+  $$($1_JAVAS): $$($1_SRCS)
+
+  # Create zh_HK versions of all zh_TW files created above
+  $$(eval $$(call SetupCopy-zh_HK,$1_HK,$$(filter %_zh_TW.java, $$($1_JAVAS))))
+  # The zh_HK copy must wait for the compile properties tool to run
+  $$($1_HK): $$($1_TARGET)
+
+  $1 += $$($1_JAVAS) $$($1_TARGET) $$($1_HK)
+endef
 
 ################################################################################
-# Some zh_HK resources are just copies of zh_TW
-
-define convert_tw_to_hk
-  $(MKDIR) -p $(@D)
-  $(CAT) $< | $(SED) -e '/class/s/_zh_TW/_zh_HK/' > $@
-endef
-
-# Some are copies of existing sources
-$(JDK_OUTPUTDIR)/gensrc/java.desktop/%_zh_HK.java: \
-    $(JDK_TOPDIR)/src/java.desktop/share/classes/%_zh_TW.java
-	$(call convert_tw_to_hk)
-
-$(JDK_OUTPUTDIR)/gensrc/java.base/%_zh_HK.java: \
-    $(JDK_TOPDIR)/src/java.base/share/classes/%_zh_TW.java
-	$(call convert_tw_to_hk)
-
-# Others are copies of sources generated by this makefile
-$(JDK_OUTPUTDIR)/gensrc/%_zh_HK.java: $(JDK_OUTPUTDIR)/gensrc/%_zh_TW.java
-	$(call convert_tw_to_hk)
-
-# The existing sources
-ZH_HK_JAVA := java.desktop/sun/applet/resources/MsgAppletViewer_zh_HK.java \
-    java.base/sun/misc/resources/Messages_zh_HK.java \
-    java.base/sun/security/util/AuthResources_zh_HK.java \
-    java.base/sun/security/util/Resources_zh_HK.java
-
-ZH_HK_JAVA_FILES := $(addprefix $(JDK_OUTPUTDIR)/gensrc/, $(ZH_HK_JAVA)) \
-    $(filter-out $(JDK_OUTPUTDIR)/gensrc/jdk.localedata/sun/util/resources/zh/%, \
-    $(subst _zh_TW,_zh_HK,$(filter %_zh_TW.java, $(ALL_COMPILED_PROPJAVAS))))
-
-################################################################################
-
-GENSRC_PROPERTIES := $(ALL_COMPILED_PROPJAVAS) $(ZH_HK_JAVA_FILES)
--- a/make/lib/CoreLibraries.gmk	Mon Oct 20 11:22:58 2014 -0700
+++ b/make/lib/CoreLibraries.gmk	Mon Oct 20 12:04:12 2014 -0700
@@ -224,7 +224,7 @@
         $(call SET_SHARED_LIBRARY_ORIGIN) \
         $(EXPORT_ZIP_FUNCS), \
     LDFLAGS_windows := -export:ZIP_Open -export:ZIP_Close -export:ZIP_FindEntry \
-        -export:ZIP_ReadEntry -export:ZIP_GetNextEntry jvm.lib \
+        -export:ZIP_ReadEntry -export:ZIP_GetNextEntry -export:ZIP_CRC32 jvm.lib \
         $(WIN_JAVA_LIB), \
     LDFLAGS_SUFFIX_linux := -ljvm -ljava $(LIBZ), \
     LDFLAGS_SUFFIX_solaris := -ljvm -ljava $(LIBZ) -lc, \
--- a/make/mapfiles/libnet/mapfile-vers	Mon Oct 20 11:22:58 2014 -0700
+++ b/make/mapfiles/libnet/mapfile-vers	Mon Oct 20 12:04:12 2014 -0700
@@ -28,6 +28,8 @@
 SUNWprivate_1.1 {
 	global:
 		JNI_OnLoad;
+		Java_java_net_AbstractPlainDatagramSocketImpl_init;
+		Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable;
 		Java_java_net_PlainSocketImpl_socketListen;
 		Java_java_net_PlainDatagramSocketImpl_getTTL;
 		Java_java_net_PlainDatagramSocketImpl_init;
@@ -108,6 +110,8 @@
 		NET_Bind;
 		NET_MapSocketOption;
 		NET_Wait;
+		NET_EnableFastTcpLoopback;
+		NET_ThrowNew;
                 ipv6_available;
                 initInetAddressIDs;
 
--- a/make/src/classes/build/tools/module/GenModulesList.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/make/src/classes/build/tools/module/GenModulesList.java	Mon Oct 20 12:04:12 2014 -0700
@@ -112,8 +112,7 @@
     }
 
     static final List<String> AGGREGATORS = Arrays.asList(new String[] {
-            "java.se", "java.compact1", "java.compact2",
-            "java.compact3", "jdk.compact3"});
+            "java.se", "java.compact1", "java.compact2", "java.compact3"});
 
     class TopoSorter {
         final Deque<Module> result = new LinkedList<>();
--- a/src/java.base/share/classes/java/lang/Class.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/java/lang/Class.java	Mon Oct 20 12:04:12 2014 -0700
@@ -262,8 +262,8 @@
     @CallerSensitive
     public static Class<?> forName(String className)
                 throws ClassNotFoundException {
-        return forName0(className, true,
-                        ClassLoader.getClassLoader(Reflection.getCallerClass()));
+        Class<?> caller = Reflection.getCallerClass();
+        return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
     }
 
 
@@ -333,22 +333,27 @@
                                    ClassLoader loader)
         throws ClassNotFoundException
     {
-        if (sun.misc.VM.isSystemDomainLoader(loader)) {
-            SecurityManager sm = System.getSecurityManager();
-            if (sm != null) {
-                ClassLoader ccl = ClassLoader.getClassLoader(Reflection.getCallerClass());
+        Class<?> caller = null;
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            // Reflective call to get caller class is only needed if a security manager
+            // is present.  Avoid the overhead of making this call otherwise.
+            caller = Reflection.getCallerClass();
+            if (sun.misc.VM.isSystemDomainLoader(loader)) {
+                ClassLoader ccl = ClassLoader.getClassLoader(caller);
                 if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
                     sm.checkPermission(
                         SecurityConstants.GET_CLASSLOADER_PERMISSION);
                 }
             }
         }
-        return forName0(name, initialize, loader);
+        return forName0(name, initialize, loader, caller);
     }
 
-    /** Called after security checks have been made. */
+    /** Called after security check for system loader access checks have been made. */
     private static native Class<?> forName0(String name, boolean initialize,
-                                            ClassLoader loader)
+                                            ClassLoader loader,
+                                            Class<?> caller)
         throws ClassNotFoundException;
 
     /**
--- a/src/java.base/share/classes/java/lang/String.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/java/lang/String.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1045,8 +1045,9 @@
             }
         }
         // Argument is a String
-        if (cs.equals(this))
-            return true;
+        if (cs instanceof String) {
+            return equals(cs);
+        }
         // Argument is a generic CharSequence
         char v1[] = value;
         int n = v1.length;
--- a/src/java.base/share/classes/java/lang/invoke/MethodType.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/java/lang/invoke/MethodType.java	Mon Oct 20 12:04:12 2014 -0700
@@ -727,7 +727,7 @@
      * @return the parameter types (as an immutable list)
      */
     public List<Class<?>> parameterList() {
-        return Collections.unmodifiableList(Arrays.asList(ptypes));
+        return Collections.unmodifiableList(Arrays.asList(ptypes.clone()));
     }
 
     /*non-public*/ Class<?> lastParameterType() {
--- a/src/java.base/share/classes/java/net/AbstractPlainDatagramSocketImpl.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/java/net/AbstractPlainDatagramSocketImpl.java	Mon Oct 20 12:04:12 2014 -0700
@@ -68,6 +68,7 @@
                     return null;
                 }
             });
+        init();
     }
 
     /**
@@ -362,4 +363,7 @@
     protected boolean nativeConnectDisabled() {
         return connectDisabled;
     }
+
+    native int dataAvailable();
+    private static native void init();
 }
--- a/src/java.base/share/classes/java/net/DatagramSocket.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/java/net/DatagramSocket.java	Mon Oct 20 12:04:12 2014 -0700
@@ -85,6 +85,17 @@
      */
     boolean oldImpl = false;
 
+    /**
+     * Set when a socket is ST_CONNECTED until we are certain
+     * that any packets which might have been received prior
+     * to calling connect() but not read by the application
+     * have been read. During this time we check the source
+     * address of all packets received to be sure they are from
+     * the connected destination. Other packets are read but
+     * silently dropped.
+     */
+    private boolean explicitFilter = false;
+    private int bytesLeftToFilter;
     /*
      * Connection state:
      * ST_NOT_CONNECTED = socket not connected
@@ -144,6 +155,15 @@
 
                 // socket is now connected by the impl
                 connectState = ST_CONNECTED;
+                // Do we need to filter some packets?
+                int avail = getImpl().dataAvailable();
+                if (avail == -1) {
+                    throw new SocketException();
+                }
+                explicitFilter = avail > 0;
+                if (explicitFilter) {
+                    bytesLeftToFilter = getReceiveBufferSize();
+                }
             } catch (SocketException se) {
 
                 // connection will be emulated by DatagramSocket
@@ -492,6 +512,7 @@
             connectedAddress = null;
             connectedPort = -1;
             connectState = ST_NOT_CONNECTED;
+            explicitFilter = false;
         }
     }
 
@@ -750,10 +771,12 @@
                     } // end of while
                 }
             }
-            if (connectState == ST_CONNECTED_NO_IMPL) {
+            if ((connectState == ST_CONNECTED_NO_IMPL) || explicitFilter) {
                 // We have to do the filtering the old fashioned way since
                 // the native impl doesn't support connect or the connect
-                // via the impl failed.
+                // via the impl failed, or .. "explicitFilter" may be set when
+                // a socket is connected via the impl, for a period of time
+                // when packets from other sources might be queued on socket.
                 boolean stop = false;
                 while (!stop) {
                     InetAddress peekAddress = null;
@@ -772,8 +795,12 @@
                     if ((!connectedAddress.equals(peekAddress)) ||
                         (connectedPort != peekPort)) {
                         // throw the packet away and silently continue
-                        DatagramPacket tmp = new DatagramPacket(new byte[1], 1);
+                        DatagramPacket tmp = new DatagramPacket(
+                                                new byte[1024], 1024);
                         getImpl().receive(tmp);
+                        if (explicitFilter) {
+                            bytesLeftToFilter -= tmp.getLength();
+                        }
                     } else {
                         stop = true;
                     }
@@ -782,6 +809,15 @@
             // If the security check succeeds, or the datagram is
             // connected then receive the packet
             getImpl().receive(p);
+            if (explicitFilter) {
+                bytesLeftToFilter -= p.getLength();
+                if (bytesLeftToFilter <= 0) {
+                    explicitFilter = false;
+                } else {
+                    // break out of filter, if there is no more data queued
+                    explicitFilter = getImpl().dataAvailable() > 0;
+                }
+            }
         }
     }
 
--- a/src/java.base/share/classes/java/net/DatagramSocketImpl.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/java/net/DatagramSocketImpl.java	Mon Oct 20 12:04:12 2014 -0700
@@ -63,6 +63,12 @@
         return socket;
     }
 
+    int dataAvailable() {
+        // default impl returns zero, which disables the calling
+        // functionality
+        return 0;
+    }
+
     /**
      * Creates a datagram socket.
      * @exception SocketException if there is an error in the
--- a/src/java.base/share/classes/java/security/ProtectionDomain.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/java/security/ProtectionDomain.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
 
 package java.security;
 
+import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Enumeration;
@@ -447,24 +448,37 @@
     /**
      * Used for storing ProtectionDomains as keys in a Map.
      */
-    final class Key {}
+    final static class Key {}
+
+    // A cache of ProtectionDomains and their Permissions
+    private static class PDCache implements ProtectionDomainCache {
+        // We must wrap the PermissionCollection in a WeakReference as there
+        // are some PermissionCollections which contain strong references
+        // back to a ProtectionDomain and otherwise would never be removed
+        // from the WeakHashMap
+        private final Map<Key, WeakReference<PermissionCollection>>
+            map = new WeakHashMap<>();
+
+        @Override
+        public synchronized void put(ProtectionDomain pd,
+                                     PermissionCollection pc) {
+            map.put(pd == null ? null : pd.key, new WeakReference<>(pc));
+        }
+
+        @Override
+        public synchronized PermissionCollection get(ProtectionDomain pd) {
+            WeakReference<PermissionCollection> ref =
+                map.get(pd == null ? null : pd.key);
+            return ref == null ? null : ref.get();
+        }
+    }
 
     static {
         SharedSecrets.setJavaSecurityProtectionDomainAccess(
             new JavaSecurityProtectionDomainAccess() {
+                @Override
                 public ProtectionDomainCache getProtectionDomainCache() {
-                    return new ProtectionDomainCache() {
-                        private final Map<Key, PermissionCollection> map =
-                            Collections.synchronizedMap
-                                (new WeakHashMap<Key, PermissionCollection>());
-                        public void put(ProtectionDomain pd,
-                            PermissionCollection pc) {
-                            map.put((pd == null ? null : pd.key), pc);
-                        }
-                        public PermissionCollection get(ProtectionDomain pd) {
-                            return pd == null ? map.get(null) : map.get(pd.key);
-                        }
-                    };
+                    return new PDCache();
                 }
             });
     }
--- a/src/java.base/share/classes/java/security/Signature.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/java/security/Signature.java	Mon Oct 20 12:04:12 2014 -0700
@@ -604,9 +604,13 @@
      * @return the number of bytes placed into {@code outbuf}.
      *
      * @exception SignatureException if this signature object is not
-     * initialized properly, if this signature algorithm is unable to
-     * process the input data provided, or if {@code len} is less
-     * than the actual signature length.
+     *     initialized properly, if this signature algorithm is unable to
+     *     process the input data provided, or if {@code len} is less
+     *     than the actual signature length.
+     * @exception IllegalArgumentException if {@code outbuf} is {@code null},
+     *     or {@code offset} or {@code len} is less than 0, or the sum of
+     *     {@code offset} and {@code len} is greater than the length of
+     *     {@code outbuf}.
      *
      * @since 1.2
      */
@@ -615,6 +619,9 @@
         if (outbuf == null) {
             throw new IllegalArgumentException("No output buffer given");
         }
+        if (offset < 0 || len < 0) {
+            throw new IllegalArgumentException("offset or len is less than 0");
+        }
         if (outbuf.length - offset < len) {
             throw new IllegalArgumentException
                 ("Output buffer too small for specified offset and length");
@@ -683,9 +690,16 @@
     public final boolean verify(byte[] signature, int offset, int length)
         throws SignatureException {
         if (state == VERIFY) {
-            if ((signature == null) || (offset < 0) || (length < 0) ||
-                (length > signature.length - offset)) {
-                throw new IllegalArgumentException("Bad arguments");
+            if (signature == null) {
+                throw new IllegalArgumentException("signature is null");
+            }
+            if (offset < 0 || length < 0) {
+                throw new IllegalArgumentException
+                    ("offset or length is less than 0");
+            }
+            if (signature.length - offset < length) {
+                throw new IllegalArgumentException
+                    ("signature too small for specified offset and length");
             }
 
             return engineVerify(signature, offset, length);
@@ -733,11 +747,25 @@
      * @param len the number of bytes to use, starting at offset.
      *
      * @exception SignatureException if this signature object is not
-     * initialized properly.
+     *     initialized properly.
+     * @exception IllegalArgumentException if {@code data} is {@code null},
+     *     or {@code off} or {@code len} is less than 0, or the sum of
+     *     {@code off} and {@code len} is greater than the length of
+     *     {@code data}.
      */
     public final void update(byte[] data, int off, int len)
             throws SignatureException {
         if (state == SIGN || state == VERIFY) {
+            if (data == null) {
+                throw new IllegalArgumentException("data is null");
+            }
+            if (off < 0 || len < 0) {
+                throw new IllegalArgumentException("off or len is less than 0");
+            }
+            if (data.length - off < len) {
+                throw new IllegalArgumentException
+                    ("data too small for specified offset and length");
+            }
             engineUpdate(data, off, len);
         } else {
             throw new SignatureException("object not initialized for "
--- a/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -84,6 +84,8 @@
      * @throws NullPointerException if {@code revocationDate},
      *    {@code reason}, {@code authority}, or
      *    {@code extensions} is {@code null}
+     * @throws ClassCastException if {@code extensions} contains an incorrectly
+     *    typed key or value
      */
     public CertificateRevokedException(Date revocationDate, CRLReason reason,
         X500Principal authority, Map<String, Extension> extensions) {
@@ -94,7 +96,10 @@
         this.revocationDate = new Date(revocationDate.getTime());
         this.reason = reason;
         this.authority = authority;
-        this.extensions = new HashMap<String, Extension>(extensions);
+        // make sure Map only contains correct types
+        this.extensions = Collections.checkedMap(new HashMap<>(),
+                                                 String.class, Extension.class);
+        this.extensions.putAll(extensions);
     }
 
     /**
@@ -172,7 +177,8 @@
     public String getMessage() {
         return "Certificate has been revoked, reason: "
                + reason + ", revocation date: " + revocationDate
-               + ", authority: " + authority + ", extensions: " + extensions;
+               + ", authority: " + authority + ", extension OIDs: "
+               + extensions.keySet();
     }
 
     /**
--- a/src/java.base/share/classes/java/util/ResourceBundle.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/java/util/ResourceBundle.java	Mon Oct 20 12:04:12 2014 -0700
@@ -2646,7 +2646,10 @@
                 } catch (ClassNotFoundException e) {
                 }
             } else if (format.equals("java.properties")) {
-                final String resourceName = toResourceName(bundleName, "properties");
+                final String resourceName = toResourceName0(bundleName, "properties");
+                if (resourceName == null) {
+                    return bundle;
+                }
                 final ClassLoader classLoader = loader;
                 final boolean reloadFlag = reload;
                 InputStream stream = null;
@@ -2800,7 +2803,10 @@
             }
             boolean result = false;
             try {
-                String resourceName = toResourceName(toBundleName(baseName, locale), format);
+                String resourceName = toResourceName0(toBundleName(baseName, locale), format);
+                if (resourceName == null) {
+                    return result;
+                }
                 URL url = loader.getResource(resourceName);
                 if (url != null) {
                     long lastModified = 0;
@@ -2934,6 +2940,15 @@
             sb.append(bundleName.replace('.', '/')).append('.').append(suffix);
             return sb.toString();
         }
+
+        private String toResourceName0(String bundleName, String suffix) {
+            // application protocol check
+            if (bundleName.contains("://")) {
+                return null;
+            } else {
+                return toResourceName(bundleName, suffix);
+            }
+        }
     }
 
     private static class SingleFormatControl extends Control {
--- a/src/java.base/share/classes/javax/crypto/CipherInputStream.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/javax/crypto/CipherInputStream.java	Mon Oct 20 12:04:12 2014 -0700
@@ -107,9 +107,10 @@
             done = true;
             try {
                 obuffer = cipher.doFinal();
+            } catch (IllegalBlockSizeException | BadPaddingException e) {
+                obuffer = null;
+                throw new IOException(e);
             }
-            catch (IllegalBlockSizeException e) {obuffer = null;}
-            catch (BadPaddingException e) {obuffer = null;}
             if (obuffer == null)
                 return -1;
             else {
@@ -120,7 +121,10 @@
         }
         try {
             obuffer = cipher.update(ibuffer, 0, readin);
-        } catch (IllegalStateException e) {obuffer = null;};
+        } catch (IllegalStateException e) {
+            obuffer = null;
+            throw e;
+        }
         ostart = 0;
         if (obuffer == null)
             ofinish = 0;
@@ -302,6 +306,7 @@
             }
         }
         catch (BadPaddingException | IllegalBlockSizeException ex) {
+            throw new IOException(ex);
         }
         ostart = 0;
         ofinish = 0;
--- a/src/java.base/share/classes/sun/invoke/util/VerifyAccess.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/sun/invoke/util/VerifyAccess.java	Mon Oct 20 12:04:12 2014 -0700
@@ -102,19 +102,24 @@
         case PUBLIC:
             return true;  // already checked above
         case PROTECTED:
+            assert !defc.isInterface(); // protected members aren't allowed in interfaces
             if ((allowedModes & PROTECTED_OR_PACKAGE_ALLOWED) != 0 &&
                 isSamePackage(defc, lookupClass))
                 return true;
             if ((allowedModes & PROTECTED) == 0)
                 return false;
+            // Protected members are accessible by subclasses, which does not include interfaces.
+            // Interfaces are types, not classes. They should not have access to
+            // protected members in j.l.Object, even though it is their superclass.
             if ((mods & STATIC) != 0 &&
                 !isRelatedClass(refc, lookupClass))
                 return false;
             if ((allowedModes & PROTECTED) != 0 &&
-                isSuperClass(defc, lookupClass))
+                isSubClass(lookupClass, defc))
                 return true;
             return false;
         case PACKAGE_ONLY:  // That is, zero.  Unmarked member is package-only access.
+            assert !defc.isInterface(); // package-private members aren't allowed in interfaces
             return ((allowedModes & PACKAGE_ALLOWED) != 0 &&
                     isSamePackage(defc, lookupClass));
         case PRIVATE:
@@ -129,12 +134,13 @@
 
     static boolean isRelatedClass(Class<?> refc, Class<?> lookupClass) {
         return (refc == lookupClass ||
-                refc.isAssignableFrom(lookupClass) ||
-                lookupClass.isAssignableFrom(refc));
+                isSubClass(refc, lookupClass) ||
+                isSubClass(lookupClass, refc));
     }
 
-    static boolean isSuperClass(Class<?> defc, Class<?> lookupClass) {
-        return defc.isAssignableFrom(lookupClass);
+    static boolean isSubClass(Class<?> lookupClass, Class<?> defc) {
+        return defc.isAssignableFrom(lookupClass) &&
+               !lookupClass.isInterface(); // interfaces are types, not classes.
     }
 
     static int getClassModifiers(Class<?> c) {
--- a/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1046,7 +1046,7 @@
             try {
                 URI uri = ParseUtil.toURI(url);
                 if (uri != null) {
-                    cachedResponse = cacheHandler.get(uri, getRequestMethod(), requests.getHeaders(EXCLUDE_HEADERS));
+                    cachedResponse = cacheHandler.get(uri, getRequestMethod(), getUserSetHeaders().getHeaders());
                     if ("https".equalsIgnoreCase(uri.getScheme())
                         && !(cachedResponse instanceof SecureCacheResponse)) {
                         cachedResponse = null;
--- a/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java	Mon Oct 20 12:04:12 2014 -0700
@@ -740,6 +740,25 @@
 
                     // set or refresh local address
                     localAddress = Net.localAddress(fd);
+
+                    // flush any packets already received.
+                    boolean blocking = false;
+                    synchronized (blockingLock()) {
+                        try {
+                            blocking = isBlocking();
+                            ByteBuffer tmpBuf = ByteBuffer.allocate(100);
+                            if (blocking) {
+                                configureBlocking(false);
+                            }
+                            do {
+                                tmpBuf.clear();
+                            } while (read(tmpBuf) > 0);
+                        } finally {
+                            if (blocking) {
+                                configureBlocking(true);
+                            }
+                        }
+                    }
                 }
             }
         }
--- a/src/java.base/share/classes/sun/nio/ch/Net.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/sun/nio/ch/Net.java	Mon Oct 20 12:04:12 2014 -0700
@@ -50,30 +50,8 @@
     // set to true if exclusive binding is on for Windows
     private static final boolean exclusiveBind;
 
-    static {
-        int availLevel = isExclusiveBindAvailable();
-        if (availLevel >= 0) {
-            String exclBindProp =
-                java.security.AccessController.doPrivileged(
-                    new PrivilegedAction<String>() {
-                        @Override
-                        public String run() {
-                            return System.getProperty(
-                                    "sun.net.useExclusiveBind");
-                        }
-                    });
-            if (exclBindProp != null) {
-                exclusiveBind = exclBindProp.length() == 0 ?
-                        true : Boolean.parseBoolean(exclBindProp);
-            } else if (availLevel == 1) {
-                exclusiveBind = true;
-            } else {
-                exclusiveBind = false;
-            }
-        } else {
-            exclusiveBind = false;
-        }
-    }
+    // set to true if the fast tcp loopback should be enabled on Windows
+    private static final boolean fastLoopback;
 
     // -- Miscellaneous utilities --
 
@@ -391,6 +369,23 @@
         }
     }
 
+    public static boolean isFastTcpLoopbackRequested() {
+        String loopbackProp = java.security.AccessController.doPrivileged(
+            new PrivilegedAction<String>() {
+                @Override
+                public String run() {
+                    return System.getProperty("jdk.net.useFastTcpLoopback");
+                }
+            });
+        boolean enable;
+        if ("".equals(loopbackProp)) {
+            enable = true;
+        } else {
+            enable = Boolean.parseBoolean(loopbackProp);
+        }
+        return enable;
+    }
+
     // -- Socket operations --
 
     private static native boolean isIPv6Available0();
@@ -413,15 +408,16 @@
         throws IOException {
         boolean preferIPv6 = isIPv6Available() &&
             (family != StandardProtocolFamily.INET);
-        return IOUtil.newFD(socket0(preferIPv6, stream, false));
+        return IOUtil.newFD(socket0(preferIPv6, stream, false, fastLoopback));
     }
 
     static FileDescriptor serverSocket(boolean stream) {
-        return IOUtil.newFD(socket0(isIPv6Available(), stream, true));
+        return IOUtil.newFD(socket0(isIPv6Available(), stream, true, fastLoopback));
     }
 
     // Due to oddities SO_REUSEADDR on windows reuse is ignored
-    private static native int socket0(boolean preferIPv6, boolean stream, boolean reuse);
+    private static native int socket0(boolean preferIPv6, boolean stream, boolean reuse,
+                                      boolean fastLoopback);
 
     public static void bind(FileDescriptor fd, InetAddress addr, int port)
         throws IOException
@@ -634,4 +630,30 @@
         POLLCONN   = pollconnValue();
     }
 
+    static {
+        int availLevel = isExclusiveBindAvailable();
+        if (availLevel >= 0) {
+            String exclBindProp =
+                java.security.AccessController.doPrivileged(
+                    new PrivilegedAction<String>() {
+                        @Override
+                        public String run() {
+                            return System.getProperty(
+                                    "sun.net.useExclusiveBind");
+                        }
+                    });
+            if (exclBindProp != null) {
+                exclusiveBind = exclBindProp.length() == 0 ?
+                        true : Boolean.parseBoolean(exclBindProp);
+            } else if (availLevel == 1) {
+                exclusiveBind = true;
+            } else {
+                exclusiveBind = false;
+            }
+        } else {
+            exclusiveBind = false;
+        }
+
+        fastLoopback = isFastTcpLoopbackRequested();
+    }
 }
--- a/src/java.base/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,7 +29,6 @@
 import java.lang.reflect.*;
 import java.io.Serializable;
 import java.util.*;
-import java.lang.annotation.*;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 
@@ -45,6 +44,11 @@
     private final Map<String, Object> memberValues;
 
     AnnotationInvocationHandler(Class<? extends Annotation> type, Map<String, Object> memberValues) {
+        Class<?>[] superInterfaces = type.getInterfaces();
+        if (!type.isAnnotation() ||
+            superInterfaces.length != 1 ||
+            superInterfaces[0] != java.lang.annotation.Annotation.class)
+            throw new AnnotationFormatError("Attempt to create proxy for a non-annotation type.");
         this.type = type;
         this.memberValues = memberValues;
     }
@@ -57,13 +61,17 @@
         if (member.equals("equals") && paramTypes.length == 1 &&
             paramTypes[0] == Object.class)
             return equalsImpl(args[0]);
-        assert paramTypes.length == 0;
-        if (member.equals("toString"))
+        if (paramTypes.length != 0)
+            throw new AssertionError("Too many parameters for an annotation method");
+
+        switch(member) {
+        case "toString":
             return toStringImpl();
-        if (member.equals("hashCode"))
+        case "hashCode":
             return hashCodeImpl();
-        if (member.equals("annotationType"))
+        case "annotationType":
             return type;
+        }
 
         // Handle annotation member accessors
         Object result = memberValues.get(member);
@@ -129,7 +137,7 @@
      * Implementation of dynamicProxy.toString()
      */
     private String toStringImpl() {
-        StringBuffer result = new StringBuffer(128);
+        StringBuilder result = new StringBuilder(128);
         result.append('@');
         result.append(type.getName());
         result.append('(');
@@ -277,6 +285,7 @@
                 new PrivilegedAction<Method[]>() {
                     public Method[] run() {
                         final Method[] mm = type.getDeclaredMethods();
+                        validateAnnotationMethods(mm);
                         AccessibleObject.setAccessible(mm, true);
                         return mm;
                     }
@@ -287,6 +296,94 @@
     private transient volatile Method[] memberMethods = null;
 
     /**
+     * Validates that a method is structurally appropriate for an
+     * annotation type. As of Java SE 8, annotation types cannot
+     * contain static methods and the declared methods of an
+     * annotation type must take zero arguments and there are
+     * restrictions on the return type.
+     */
+    private void validateAnnotationMethods(Method[] memberMethods) {
+        /*
+         * Specification citations below are from JLS
+         * 9.6.1. Annotation Type Elements
+         */
+        boolean valid = true;
+        for(Method method : memberMethods) {
+            /*
+             * "By virtue of the AnnotationTypeElementDeclaration
+             * production, a method declaration in an annotation type
+             * declaration cannot have formal parameters, type
+             * parameters, or a throws clause.
+             *
+             * "By virtue of the AnnotationTypeElementModifier
+             * production, a method declaration in an annotation type
+             * declaration cannot be default or static."
+             */
+            if (method.getModifiers() != (Modifier.PUBLIC | Modifier.ABSTRACT) ||
+                method.isDefault() ||
+                method.getParameterCount() != 0 ||
+                method.getExceptionTypes().length != 0) {
+                valid = false;
+                break;
+            }
+
+            /*
+             * "It is a compile-time error if the return type of a
+             * method declared in an annotation type is not one of the
+             * following: a primitive type, String, Class, any
+             * parameterized invocation of Class, an enum type
+             * (section 8.9), an annotation type, or an array type
+             * (chapter 10) whose element type is one of the preceding
+             * types."
+             */
+            Class<?> returnType = method.getReturnType();
+            if (returnType.isArray()) {
+                returnType = returnType.getComponentType();
+                if (returnType.isArray()) { // Only single dimensional arrays
+                    valid = false;
+                    break;
+                }
+            }
+
+            if (!((returnType.isPrimitive() && returnType != void.class) ||
+                  returnType == java.lang.String.class ||
+                  returnType == java.lang.Class.class ||
+                  returnType.isEnum() ||
+                  returnType.isAnnotation())) {
+                valid = false;
+                break;
+            }
+
+            /*
+             * "It is a compile-time error if any method declared in an
+             * annotation type has a signature that is
+             * override-equivalent to that of any public or protected
+             * method declared in class Object or in the interface
+             * java.lang.annotation.Annotation."
+             *
+             * The methods in Object or Annotation meeting the other
+             * criteria (no arguments, contrained return type, etc.)
+             * above are:
+             *
+             * String toString()
+             * int hashCode()
+             * Class<? extends Annotation> annotationType()
+             */
+            String methodName = method.getName();
+            if ((methodName.equals("toString") && returnType == java.lang.String.class) ||
+                (methodName.equals("hashCode") && returnType == int.class) ||
+                (methodName.equals("annotationType") && returnType == java.lang.Class.class)) {
+                valid = false;
+                break;
+            }
+        }
+        if (valid)
+            return;
+        else
+            throw new AnnotationFormatError("Malformed method on an annotation type");
+    }
+
+    /**
      * Implementation of dynamicProxy.hashCode()
      */
     private int hashCodeImpl() {
@@ -330,7 +427,6 @@
         throws java.io.IOException, ClassNotFoundException {
         s.defaultReadObject();
 
-
         // Check to make sure that types have not evolved incompatibly
 
         AnnotationType annotationType = null;
@@ -343,7 +439,6 @@
 
         Map<String, Class<?>> memberTypes = annotationType.memberTypes();
 
-
         // If there are annotation members without values, that
         // situation is handled by the invoke method.
         for (Map.Entry<String, Object> memberValue : memberValues.entrySet()) {
--- a/src/java.base/share/classes/sun/security/provider/X509Factory.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/sun/security/provider/X509Factory.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -80,6 +80,7 @@
      *
      * @exception CertificateException on parsing errors.
      */
+    @Override
     public Certificate engineGenerateCertificate(InputStream is)
         throws CertificateException
     {
@@ -103,8 +104,8 @@
                 throw new IOException("Empty input");
             }
         } catch (IOException ioe) {
-            throw (CertificateException)new CertificateException
-            ("Could not parse certificate: " + ioe.toString()).initCause(ioe);
+            throw new CertificateException("Could not parse certificate: " +
+                    ioe.toString(), ioe);
         }
     }
 
@@ -140,6 +141,12 @@
      * It is useful for certificates that cannot be created via
      * generateCertificate() and for converting other X509Certificate
      * implementations to an X509CertImpl.
+     *
+     * @param c The source X509Certificate
+     * @return An X509CertImpl object that is either a cached certificate or a
+     *      newly built X509CertImpl from the provided X509Certificate
+     * @throws CertificateException if failures occur while obtaining the DER
+     *      encoding for certificate data.
      */
     public static synchronized X509CertImpl intern(X509Certificate c)
             throws CertificateException {
@@ -170,6 +177,12 @@
     /**
      * Return an interned X509CRLImpl for the given certificate.
      * For more information, see intern(X509Certificate).
+     *
+     * @param c The source X509CRL
+     * @return An X509CRLImpl object that is either a cached CRL or a
+     *      newly built X509CRLImpl from the provided X509CRL
+     * @throws CRLException if failures occur while obtaining the DER
+     *      encoding for CRL data.
      */
     public static synchronized X509CRLImpl intern(X509CRL c)
             throws CRLException {
@@ -229,6 +242,7 @@
      * @exception CertificateException if an exception occurs while decoding
      * @since 1.4
      */
+    @Override
     public CertPath engineGenerateCertPath(InputStream inStream)
         throws CertificateException
     {
@@ -260,6 +274,7 @@
      *   the encoding requested is not supported
      * @since 1.4
      */
+    @Override
     public CertPath engineGenerateCertPath(InputStream inStream,
         String encoding) throws CertificateException
     {
@@ -292,6 +307,7 @@
      * @exception CertificateException if an exception occurs
      * @since 1.4
      */
+    @Override
     public CertPath
         engineGenerateCertPath(List<? extends Certificate> certificates)
         throws CertificateException
@@ -311,6 +327,7 @@
      *         <code>CertPath</code> encodings (as <code>String</code>s)
      * @since 1.4
      */
+    @Override
     public Iterator<String> engineGetCertPathEncodings() {
         return(X509CertPath.getEncodingsStatic());
     }
@@ -326,6 +343,7 @@
      *
      * @exception CertificateException on parsing errors.
      */
+    @Override
     public Collection<? extends java.security.cert.Certificate>
             engineGenerateCertificates(InputStream is)
             throws CertificateException {
@@ -351,6 +369,7 @@
      *
      * @exception CRLException on parsing errors.
      */
+    @Override
     public CRL engineGenerateCRL(InputStream is)
         throws CRLException
     {
@@ -388,6 +407,7 @@
      *
      * @exception CRLException on parsing errors.
      */
+    @Override
     public Collection<? extends java.security.cert.CRL> engineGenerateCRLs(
             InputStream is) throws CRLException
     {
@@ -410,11 +430,30 @@
         parseX509orPKCS7Cert(InputStream is)
         throws CertificateException, IOException
     {
+        int peekByte;
+        byte[] data;
+        PushbackInputStream pbis = new PushbackInputStream(is);
         Collection<X509CertImpl> coll = new ArrayList<>();
-        byte[] data = readOneBlock(is);
+
+        // Test the InputStream for end-of-stream.  If the stream's
+        // initial state is already at end-of-stream then return
+        // an empty collection.  Otherwise, push the byte back into the
+        // stream and let readOneBlock look for the first certificate.
+        peekByte = pbis.read();
+        if (peekByte == -1) {
+            return new ArrayList<>(0);
+        } else {
+            pbis.unread(peekByte);
+            data = readOneBlock(pbis);
+        }
+
+        // If we end up with a null value after reading the first block
+        // then we know the end-of-stream has been reached and no certificate
+        // data has been found.
         if (data == null) {
-            return new ArrayList<>(0);
+            throw new CertificateException("No certificate data found");
         }
+
         try {
             PKCS7 pkcs7 = new PKCS7(data);
             X509Certificate[] certs = pkcs7.getCertificates();
@@ -422,13 +461,13 @@
             if (certs != null) {
                 return Arrays.asList(certs);
             } else {
-                // no crls provided
+                // no certificates provided
                 return new ArrayList<>(0);
             }
         } catch (ParsingException e) {
             while (data != null) {
                 coll.add(new X509CertImpl(data));
-                data = readOneBlock(is);
+                data = readOneBlock(pbis);
             }
         }
         return coll;
@@ -443,11 +482,30 @@
         parseX509orPKCS7CRL(InputStream is)
         throws CRLException, IOException
     {
+        int peekByte;
+        byte[] data;
+        PushbackInputStream pbis = new PushbackInputStream(is);
         Collection<X509CRLImpl> coll = new ArrayList<>();
-        byte[] data = readOneBlock(is);
+
+        // Test the InputStream for end-of-stream.  If the stream's
+        // initial state is already at end-of-stream then return
+        // an empty collection.  Otherwise, push the byte back into the
+        // stream and let readOneBlock look for the first CRL.
+        peekByte = pbis.read();
+        if (peekByte == -1) {
+            return new ArrayList<>(0);
+        } else {
+            pbis.unread(peekByte);
+            data = readOneBlock(pbis);
+        }
+
+        // If we end up with a null value after reading the first block
+        // then we know the end-of-stream has been reached and no CRL
+        // data has been found.
         if (data == null) {
-            return new ArrayList<>(0);
+            throw new CRLException("No CRL data found");
         }
+
         try {
             PKCS7 pkcs7 = new PKCS7(data);
             X509CRL[] crls = pkcs7.getCRLs();
@@ -461,7 +519,7 @@
         } catch (ParsingException e) {
             while (data != null) {
                 coll.add(new X509CRLImpl(data));
-                data = readOneBlock(is);
+                data = readOneBlock(pbis);
             }
         }
         return coll;
@@ -623,7 +681,7 @@
 
         int n = is.read();
         if (n == -1) {
-            throw new IOException("BER/DER length info ansent");
+            throw new IOException("BER/DER length info absent");
         }
         bout.write(n);
 
--- a/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,6 +36,8 @@
 
 import java.security.cert.X509Certificate;
 import java.security.cert.CertificateException;
+import java.security.cert.CertificateParsingException;
+import javax.security.auth.x500.X500Principal;
 
 import javax.crypto.SecretKey;
 import javax.crypto.spec.SecretKeySpec;
@@ -89,12 +91,66 @@
     private final static boolean enableSNIExtension =
             Debug.getBooleanProperty("jsse.enableSNIExtension", true);
 
+    /*
+     * Allow unsafe server certificate change?
+     *
+     * Server certificate change during SSL/TLS renegotiation may be considered
+     * unsafe, as described in the Triple Handshake attacks:
+     *
+     *     https://secure-resumption.com/tlsauth.pdf
+     *
+     * Endpoint identification (See
+     * SSLParameters.getEndpointIdentificationAlgorithm()) is a pretty nice
+     * guarantee that the server certificate change in renegotiation is legal.
+     * However, endpoing identification is only enabled for HTTPS and LDAP
+     * over SSL/TLS by default.  It is not enough to protect SSL/TLS
+     * connections other than HTTPS and LDAP.
+     *
+     * The renegotiation indication extension (See RFC 5764) is a pretty
+     * strong guarantee that the endpoints on both client and server sides
+     * are identical on the same connection.  However, the Triple Handshake
+     * attacks can bypass this guarantee if there is a session-resumption
+     * handshake between the initial full handshake and the renegotiation
+     * full handshake.
+     *
+     * Server certificate change may be unsafe and should be restricted if
+     * endpoint identification is not enabled and the previous handshake is
+     * a session-resumption abbreviated initial handshake, unless the
+     * identities represented by both certificates can be regraded as the
+     * same (See isIdentityEquivalent()).
+     *
+     * Considering the compatibility impact and the actual requirements to
+     * support server certificate change in practice, the system property,
+     * jdk.tls.allowUnsafeServerCertChange, is used to define whether unsafe
+     * server certificate change in renegotiation is allowed or not.  The
+     * default value of the system property is "false".  To mitigate the
+     * compactibility impact, applications may want to set the system
+     * property to "true" at their own risk.
+     *
+     * If the value of the system property is "false", server certificate
+     * change in renegotiation after a session-resumption abbreviated initial
+     * handshake is restricted (See isIdentityEquivalent()).
+     *
+     * If the system property is set to "true" explicitly, the restriction on
+     * server certificate change in renegotiation is disabled.
+     */
+    private final static boolean allowUnsafeServerCertChange =
+        Debug.getBooleanProperty("jdk.tls.allowUnsafeServerCertChange", false);
+
     private List<SNIServerName> requestedServerNames =
             Collections.<SNIServerName>emptyList();
 
     private boolean serverNamesAccepted = false;
 
     /*
+     * the reserved server certificate chain in previous handshaking
+     *
+     * The server certificate chain is only reserved if the previous
+     * handshake is a session-resumption abbreviated initial handshake.
+     */
+    private X509Certificate[] reservedServerCerts = null;
+
+    /*
      * Constructors
      */
     ClientHandshaker(SSLSocketImpl socket, SSLContextImpl context,
@@ -555,14 +611,19 @@
                 // we wanted to resume, but the server refused
                 session = null;
                 if (!enableNewSession) {
-                    throw new SSLException
-                        ("New session creation is disabled");
+                    throw new SSLException("New session creation is disabled");
                 }
             }
         }
 
         if (resumingSession && session != null) {
             setHandshakeSessionSE(session);
+            // Reserve the handshake state if this is a session-resumption
+            // abbreviated initial handshake.
+            if (isInitialHandshake) {
+                session.setAsSessionResumption(true);
+            }
+
             return;
         }
 
@@ -1064,6 +1125,13 @@
         }
 
         /*
+         * Reset the handshake state if this is not an initial handshake.
+         */
+        if (!isInitialHandshake) {
+            session.setAsSessionResumption(false);
+        }
+
+        /*
          * OK, it verified.  If we're doing the fast handshake, add that
          * "Finished" message to the hash of handshake messages, then send
          * our own change_cipher_spec and Finished message for the server
@@ -1161,8 +1229,23 @@
                 System.out.println("%% No cached client session");
             }
         }
-        if ((session != null) && (session.isRejoinable() == false)) {
-            session = null;
+        if (session != null) {
+            // If unsafe server certificate change is not allowed, reserve
+            // current server certificates if the previous handshake is a
+            // session-resumption abbreviated initial handshake.
+            if (!allowUnsafeServerCertChange && session.isSessionResumption()) {
+                try {
+                    // If existing, peer certificate chain cannot be null.
+                    reservedServerCerts =
+                        (X509Certificate[])session.getPeerCertificates();
+                } catch (SSLPeerUnverifiedException puve) {
+                    // Maybe not certificate-based, ignore the exception.
+                }
+            }
+
+            if (!session.isRejoinable()) {
+                session = null;
+            }
         }
 
         if (session != null) {
@@ -1331,9 +1414,28 @@
         }
         X509Certificate[] peerCerts = mesg.getCertificateChain();
         if (peerCerts.length == 0) {
-            fatalSE(Alerts.alert_bad_certificate,
-                "empty certificate chain");
+            fatalSE(Alerts.alert_bad_certificate, "empty certificate chain");
         }
+
+        // Allow server certificate change in client side during renegotiation
+        // after a session-resumption abbreviated initial handshake?
+        //
+        // DO NOT need to check allowUnsafeServerCertChange here. We only
+        // reserve server certificates when allowUnsafeServerCertChange is
+        // flase.
+        if (reservedServerCerts != null) {
+            // It is not necessary to check the certificate update if endpoint
+            // identification is enabled.
+            String identityAlg = getEndpointIdentificationAlgorithmSE();
+            if ((identityAlg == null || identityAlg.length() == 0) &&
+                !isIdentityEquivalent(peerCerts[0], reservedServerCerts[0])) {
+
+                fatalSE(Alerts.alert_bad_certificate,
+                        "server certificate change is restricted " +
+                        "during renegotiation");
+            }
+        }
+
         // ask the trust manager to verify the chain
         X509TrustManager tm = sslContext.getX509TrustManager();
         try {
@@ -1370,4 +1472,81 @@
         }
         session.setPeerCertificates(peerCerts);
     }
+
+    /*
+     * Whether the certificates can represent the same identity?
+     *
+     * The certificates can be used to represent the same identity:
+     *     1. If the subject alternative names of IP address are present in
+     *        both certificates, they should be identical; otherwise,
+     *     2. if the subject alternative names of DNS name are present in
+     *        both certificates, they should be identical; otherwise,
+     *     3. if the subject fields are present in both certificates, the
+     *        certificate subjects and issuers should be identical.
+     */
+    private static boolean isIdentityEquivalent(X509Certificate thisCert,
+            X509Certificate prevCert) {
+        if (thisCert.equals(prevCert)) {
+            return true;
+        }
+
+        // check the iPAddress field in subjectAltName extension
+        Object thisIPAddress = getSubjectAltName(thisCert, 7);  // 7: iPAddress
+        Object prevIPAddress = getSubjectAltName(prevCert, 7);
+        if (thisIPAddress != null && prevIPAddress!= null) {
+            // only allow the exactly match
+            return Objects.equals(thisIPAddress, prevIPAddress);
+        }
+
+        // check the dNSName field in subjectAltName extension
+        Object thisDNSName = getSubjectAltName(thisCert, 2);    // 2: dNSName
+        Object prevDNSName = getSubjectAltName(prevCert, 2);
+        if (thisDNSName != null && prevDNSName!= null) {
+            // only allow the exactly match
+            return Objects.equals(thisDNSName, prevDNSName);
+        }
+
+        // check the certificate subject and issuer
+        X500Principal thisSubject = thisCert.getSubjectX500Principal();
+        X500Principal prevSubject = prevCert.getSubjectX500Principal();
+        X500Principal thisIssuer = thisCert.getIssuerX500Principal();
+        X500Principal prevIssuer = prevCert.getIssuerX500Principal();
+        if (!thisSubject.getName().isEmpty() &&
+                !prevSubject.getName().isEmpty() &&
+                thisSubject.equals(prevSubject) &&
+                thisIssuer.equals(prevIssuer)) {
+            return true;
+        }
+
+        return false;
+    }
+
+    /*
+     * Returns the subject alternative name of the specified type in the
+     * subjectAltNames extension of a certificate.
+     */
+    private static Object getSubjectAltName(X509Certificate cert, int type) {
+        Collection<List<?>> subjectAltNames;
+
+        try {
+            subjectAltNames = cert.getSubjectAlternativeNames();
+        } catch (CertificateParsingException cpe) {
+            if (debug != null && Debug.isOn("handshake")) {
+                System.out.println(
+                        "Attempt to obtain subjectAltNames extension failed!");
+            }
+            return null;
+        }
+
+        if (subjectAltNames != null) {
+            for (List<?> subjectAltName : subjectAltNames) {
+                int subjectAltNameType = (Integer)subjectAltName.get(0);
+                if (subjectAltNameType == type) {
+                    return subjectAltName.get(1);
+                }
+            }
+        }
+
+        return null;
+    }
 }
--- a/src/java.base/share/classes/sun/security/ssl/Handshaker.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/Handshaker.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -359,6 +359,17 @@
         }
     }
 
+    String getEndpointIdentificationAlgorithmSE() {
+        SSLParameters paras;
+        if (conn != null) {
+            paras = conn.getSSLParameters();
+        } else {
+            paras = engine.getSSLParameters();
+        }
+
+        return paras.getEndpointIdentificationAlgorithm();
+    }
+
     private void setVersionSE(ProtocolVersion protocolVersion) {
         if (conn != null) {
             conn.setVersion(protocolVersion);
--- a/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -115,6 +115,14 @@
     private Principal localPrincipal;
 
     /*
+     * Is the session currently re-established with a session-resumption
+     * abbreviated initial handshake?
+     *
+     * Note that currently we only set this variable in client side.
+     */
+    private boolean isSessionResumption = false;
+
+    /*
      * We count session creations, eventually for statistical data but
      * also since counters make shorter debugging IDs than the big ones
      * we use in the protocol for uniqueness-over-time.
@@ -325,6 +333,22 @@
     }
 
     /**
+     * Return true if the session is currently re-established with a
+     * session-resumption abbreviated initial handshake.
+     */
+    boolean isSessionResumption() {
+        return isSessionResumption;
+    }
+
+    /**
+     * Resets whether the session is re-established with a session-resumption
+     * abbreviated initial handshake.
+     */
+    void setAsSessionResumption(boolean flag) {
+        isSessionResumption = flag;
+    }
+
+    /**
      * Returns the name of the cipher suite in use on this session
      */
     @Override
--- a/src/java.base/share/classes/sun/util/locale/BaseLocale.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/sun/util/locale/BaseLocale.java	Mon Oct 20 12:04:12 2014 -0700
@@ -31,6 +31,7 @@
  */
 
 package sun.util.locale;
+import java.lang.ref.SoftReference;
 
 import java.util.StringJoiner;
 
@@ -151,11 +152,11 @@
         return h;
     }
 
-    private static final class Key implements Comparable<Key> {
-        private final String lang;
-        private final String scrt;
-        private final String regn;
-        private final String vart;
+    private static final class Key {
+        private final SoftReference<String> lang;
+        private final SoftReference<String> scrt;
+        private final SoftReference<String> regn;
+        private final SoftReference<String> vart;
         private final boolean normalized;
         private final int hash;
 
@@ -167,10 +168,10 @@
             assert language.intern() == language
                    && region.intern() == region;
 
-            lang = language;
-            scrt = "";
-            regn = region;
-            vart = "";
+            lang = new SoftReference<>(language);
+            scrt = new SoftReference<>("");
+            regn = new SoftReference<>(region);
+            vart = new SoftReference<>("");
             this.normalized = true;
 
             int h = language.hashCode();
@@ -191,40 +192,40 @@
                     String variant, boolean normalized) {
             int h = 0;
             if (language != null) {
-                lang = language;
+                lang = new SoftReference<>(language);
                 int len = language.length();
                 for (int i = 0; i < len; i++) {
                     h = 31*h + LocaleUtils.toLower(language.charAt(i));
                 }
             } else {
-                lang = "";
+                lang = new SoftReference<>("");
             }
             if (script != null) {
-                scrt = script;
+                scrt = new SoftReference<>(script);
                 int len = script.length();
                 for (int i = 0; i < len; i++) {
                     h = 31*h + LocaleUtils.toLower(script.charAt(i));
                 }
             } else {
-                scrt = "";
+                scrt = new SoftReference<>("");
             }
             if (region != null) {
-                regn = region;
+                regn = new SoftReference<>(region);
                 int len = region.length();
                 for (int i = 0; i < len; i++) {
                     h = 31*h + LocaleUtils.toLower(region.charAt(i));
                 }
             } else {
-                regn = "";
+                regn = new SoftReference<>("");
             }
             if (variant != null) {
-                vart = variant;
+                vart = new SoftReference<>(variant);
                 int len = variant.length();
                 for (int i = 0; i < len; i++) {
                     h = 31*h + variant.charAt(i);
                 }
             } else {
-                vart = "";
+                vart = new SoftReference<>("");
             }
             hash = h;
             this.normalized = normalized;
@@ -232,28 +233,31 @@
 
         @Override
         public boolean equals(Object obj) {
-            return (this == obj) ||
-                    (obj instanceof Key)
-                    && this.hash == ((Key)obj).hash
-                    && LocaleUtils.caseIgnoreMatch(((Key)obj).lang, this.lang)
-                    && LocaleUtils.caseIgnoreMatch(((Key)obj).scrt, this.scrt)
-                    && LocaleUtils.caseIgnoreMatch(((Key)obj).regn, this.regn)
-                    && ((Key)obj).vart.equals(vart); // variant is case sensitive in JDK!
-        }
+            if (this == obj) {
+                return true;
+            }
 
-        @Override
-        public int compareTo(Key other) {
-            int res = LocaleUtils.caseIgnoreCompare(this.lang, other.lang);
-            if (res == 0) {
-                res = LocaleUtils.caseIgnoreCompare(this.scrt, other.scrt);
-                if (res == 0) {
-                    res = LocaleUtils.caseIgnoreCompare(this.regn, other.regn);
-                    if (res == 0) {
-                        res = this.vart.compareTo(other.vart);
+            if (obj instanceof Key && this.hash == ((Key)obj).hash) {
+                String tl = this.lang.get();
+                String ol = ((Key)obj).lang.get();
+                if (tl != null && ol != null &&
+                    LocaleUtils.caseIgnoreMatch(ol, tl)) {
+                    String ts = this.scrt.get();
+                    String os = ((Key)obj).scrt.get();
+                    if (ts != null && os != null &&
+                        LocaleUtils.caseIgnoreMatch(os, ts)) {
+                        String tr = this.regn.get();
+                        String or = ((Key)obj).regn.get();
+                        if (tr != null && or != null &&
+                            LocaleUtils.caseIgnoreMatch(or, tr)) {
+                            String tv = this.vart.get();
+                            String ov = ((Key)obj).vart.get();
+                            return (ov != null && ov.equals(tv));
+                        }
                     }
                 }
             }
-            return res;
+            return false;
         }
 
         @Override
@@ -266,10 +270,10 @@
                 return key;
             }
 
-            String lang = LocaleUtils.toLowerString(key.lang).intern();
-            String scrt = LocaleUtils.toTitleString(key.scrt).intern();
-            String regn = LocaleUtils.toUpperString(key.regn).intern();
-            String vart = key.vart.intern(); // preserve upper/lower cases
+            String lang = LocaleUtils.toLowerString(key.lang.get()).intern();
+            String scrt = LocaleUtils.toTitleString(key.scrt.get()).intern();
+            String regn = LocaleUtils.toUpperString(key.regn.get()).intern();
+            String vart = key.vart.get().intern(); // preserve upper/lower cases
 
             return new Key(lang, scrt, regn, vart, true);
         }
@@ -282,12 +286,18 @@
 
         @Override
         protected Key normalizeKey(Key key) {
+            assert key.lang.get() != null &&
+                   key.scrt.get() != null &&
+                   key.regn.get() != null &&
+                   key.vart.get() != null;
+
             return Key.normalize(key);
         }
 
         @Override
         protected BaseLocale createObject(Key key) {
-            return new BaseLocale(key.lang, key.scrt, key.regn, key.vart);
+            return new BaseLocale(key.lang.get(), key.scrt.get(),
+                                  key.regn.get(), key.vart.get());
         }
     }
 }
--- a/src/java.base/share/classes/sun/util/locale/LocaleObjectCache.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/classes/sun/util/locale/LocaleObjectCache.java	Mon Oct 20 12:04:12 2014 -0700
@@ -57,8 +57,10 @@
             value = entry.get();
         }
         if (value == null) {
+            V newVal = createObject(key);
+            // make sure key is normalized *after* the object creation
+            // so that newVal is assured to be created from a valid key.
             key = normalizeKey(key);
-            V newVal = createObject(key);
             if (key == null || newVal == null) {
                 // subclass must return non-null key/value object
                 return null;
--- a/src/java.base/share/native/include/jvm.h	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/native/include/jvm.h	Mon Oct 20 12:04:12 2014 -0700
@@ -386,6 +386,19 @@
 JVM_FindClassFromBootLoader(JNIEnv *env, const char *name);
 
 /*
+ * Find a class from a given class loader.  Throws ClassNotFoundException.
+ *  name:   name of class
+ *  init:   whether initialization is done
+ *  loader: class loader to look up the class. This may not be the same as the caller's
+ *          class loader.
+ *  caller: initiating class. The initiating class may be null when a security
+ *          manager is not installed.
+ */
+JNIEXPORT jclass JNICALL
+JVM_FindClassFromCaller(JNIEnv *env, const char *name, jboolean init,
+                        jobject loader, jclass caller);
+
+/*
  * Find a class from a given class loader. Throw ClassNotFoundException
  * or NoClassDefFoundError depending on the value of the last
  * argument.
--- a/src/java.base/share/native/libjava/Class.c	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/native/libjava/Class.c	Mon Oct 20 12:04:12 2014 -0700
@@ -93,7 +93,7 @@
 
 JNIEXPORT jclass JNICALL
 Java_java_lang_Class_forName0(JNIEnv *env, jclass this, jstring classname,
-                              jboolean initialize, jobject loader)
+                              jboolean initialize, jobject loader, jclass caller)
 {
     char *clname;
     jclass cls = 0;
@@ -131,8 +131,7 @@
         goto done;
     }
 
-    cls = JVM_FindClassFromClassLoader(env, clname, initialize,
-                                       loader, JNI_FALSE);
+    cls = JVM_FindClassFromCaller(env, clname, initialize, loader, caller);
 
  done:
     if (clname != buf) {
--- a/src/java.base/share/native/libnet/net_util.h	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/native/libnet/net_util.h	Mon Oct 20 12:04:12 2014 -0700
@@ -184,9 +184,13 @@
 JNIEXPORT int JNICALL
 NET_MapSocketOptionV6(jint cmd, int *level, int *optname);
 
+JNIEXPORT jint JNICALL
+NET_EnableFastTcpLoopback(int fd);
+
 int getScopeID (struct sockaddr *);
 
 int cmpScopeID (unsigned int, struct sockaddr *);
 
 unsigned short in_cksum(unsigned short *addr, int len);
+
 #endif /* NET_UTILS_H */
--- a/src/java.base/share/native/libzip/CRC32.c	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/native/libzip/CRC32.c	Mon Oct 20 12:04:12 2014 -0700
@@ -54,7 +54,8 @@
     return crc;
 }
 
-JNIEXPORT jint ZIP_CRC32(jint crc, const jbyte *buf, jint len)
+JNIEXPORT jint JNICALL
+ZIP_CRC32(jint crc, const jbyte *buf, jint len)
 {
     return crc32(crc, (Bytef*)buf, len);
 }
--- a/src/java.base/share/native/libzip/ZipFile.c	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/native/libzip/ZipFile.c	Mon Oct 20 12:04:12 2014 -0700
@@ -174,11 +174,7 @@
     }
     (*env)->GetByteArrayRegion(env, name, 0, ulen, (jbyte *)path);
     path[ulen] = '\0';
-    if (addSlash == JNI_FALSE) {
-        ze = ZIP_GetEntry(zip, path, 0);
-    } else {
-        ze = ZIP_GetEntry(zip, path, (jint)ulen);
-    }
+    ze = ZIP_GetEntry2(zip, path, (jint)ulen, addSlash);
     if (path != buf) {
         free(path);
     }
@@ -271,7 +267,7 @@
     switch (type) {
     case java_util_zip_ZipFile_JZENTRY_NAME:
         if (ze->name != 0) {
-            len = (int)strlen(ze->name);
+            len = (int)ze->nlen;
             // Unlike for extra and comment, we never return null for
             // an (extremely rarely seen) empty name
             if ((jba = (*env)->NewByteArray(env, len)) == NULL)
--- a/src/java.base/share/native/libzip/zip_util.c	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/native/libzip/zip_util.c	Mon Oct 20 12:04:12 2014 -0700
@@ -1021,6 +1021,7 @@
     if ((ze->name = malloc(nlen + 1)) == NULL) goto Catch;
     memcpy(ze->name, cen + CENHDR, nlen);
     ze->name[nlen] = '\0';
+    ze->nlen = nlen;
     if (elen > 0) {
         char *extra = cen + CENHDR + nlen;
 
@@ -1118,7 +1119,34 @@
 jzentry *
 ZIP_GetEntry(jzfile *zip, char *name, jint ulen)
 {
-    unsigned int hsh = hash(name);
+    if (ulen == 0) {
+        return ZIP_GetEntry2(zip, name, strlen(name), JNI_FALSE);
+    }
+    return ZIP_GetEntry2(zip, name, ulen, JNI_TRUE);
+}
+
+jboolean equals(char* name1, int len1, char* name2, int len2) {
+    if (len1 != len2) {
+        return JNI_FALSE;
+    }
+    while (len1-- > 0) {
+        if (*name1++ != *name2++) {
+            return JNI_FALSE;
+        }
+    }
+    return JNI_TRUE;
+}
+
+/*
+ * Returns the zip entry corresponding to the specified name, or
+ * NULL if not found.
+ * This method supports embedded null character in "name", use ulen
+ * for the length of "name".
+ */
+jzentry *
+ZIP_GetEntry2(jzfile *zip, char *name, jint ulen, jboolean addSlash)
+{
+    unsigned int hsh = hashN(name, ulen);
     jint idx;
     jzentry *ze = 0;
 
@@ -1139,7 +1167,7 @@
 
         /* Check the cached entry first */
         ze = zip->cache;
-        if (ze && strcmp(ze->name,name) == 0) {
+        if (ze && equals(ze->name, ze->nlen, name, ulen)) {
             /* Cache hit!  Remove and return the cached entry. */
             zip->cache = 0;
             ZIP_Unlock(zip);
@@ -1165,7 +1193,7 @@
                  * we keep searching.
                  */
                 ze = newEntry(zip, zc, ACCESS_RANDOM);
-                if (ze && strcmp(ze->name, name)==0) {
+                if (ze && equals(ze->name, ze->nlen, name, ulen)) {
                     break;
                 }
                 if (ze != 0) {
@@ -1184,8 +1212,8 @@
             break;
         }
 
-        /* If no real length was passed in, we are done */
-        if (ulen == 0) {
+        /* If no need to try appending slash, we are done */
+        if (!addSlash) {
             break;
         }
 
@@ -1195,11 +1223,11 @@
         }
 
         /* Add slash and try once more */
-        name[ulen] = '/';
-        name[ulen+1] = '\0';
+        name[ulen++] = '/';
+        name[ulen] = '\0';
         hsh = hash_append(hsh, '/');
         idx = zip->table[hsh % zip->tablelen];
-        ulen = 0;
+        addSlash = JNI_FALSE;
     }
 
 Finally:
--- a/src/java.base/share/native/libzip/zip_util.h	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/share/native/libzip/zip_util.h	Mon Oct 20 12:04:12 2014 -0700
@@ -154,6 +154,7 @@
  * - If pos <= 0 then it is the position of entry LOC header.
  *   If pos > 0 then it is the position of entry data.
  *   pos should not be accessed directly, but only by ZIP_GetEntryDataOffset.
+ * - entry name may include embedded null character, use nlen for length
  */
 
 typedef struct jzentry {  /* Zip file entry */
@@ -166,6 +167,7 @@
     jbyte *extra;         /* optional extra data */
     jlong pos;            /* position of LOC header or entry data */
     jint flag;            /* general purpose flag */
+    jint nlen;            /* length of the entry name */
 } jzentry;
 
 /*
@@ -269,5 +271,5 @@
 jint ZIP_Read(jzfile *zip, jzentry *entry, jlong pos, void *buf, jint len);
 void ZIP_FreeEntry(jzfile *zip, jzentry *ze);
 jlong ZIP_GetEntryDataOffset(jzfile *zip, jzentry *entry);
-
+jzentry * ZIP_GetEntry2(jzfile *zip, char *name, jint ulen, jboolean addSlash);
 #endif /* !_ZIP_H_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/unix/native/libnet/AbstractPlainDatagramSocketImpl.c	Mon Oct 20 12:04:12 2014 -0700
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#ifdef __solaris__
+#include <unistd.h>
+#include <stropts.h>
+
+#ifndef BSD_COMP
+#define BSD_COMP
+#endif
+
+#endif
+
+#include <sys/ioctl.h>
+
+#include "jvm.h"
+#include "jni_util.h"
+#include "net_util.h"
+
+#include "java_net_AbstractPlainDatagramSocketImpl.h"
+
+static jfieldID IO_fd_fdID;
+
+static jfieldID apdsi_fdID;
+
+
+/*
+ * Class:     java_net_AbstractPlainDatagramSocketImpl
+ * Method:    init
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL
+Java_java_net_AbstractPlainDatagramSocketImpl_init(JNIEnv *env, jclass cls) {
+
+    apdsi_fdID = (*env)->GetFieldID(env, cls, "fd",
+                                   "Ljava/io/FileDescriptor;");
+    CHECK_NULL(apdsi_fdID);
+
+    IO_fd_fdID = NET_GetFileDescriptorID(env);
+}
+
+/*
+ * Class:     java_net_AbstractPlainDatagramSocketImpl
+ * Method:    dataAvailable
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable
+(JNIEnv *env, jobject this) {
+    int fd, retval;
+
+    jobject fdObj = (*env)->GetObjectField(env, this, apdsi_fdID);
+
+    if (IS_NULL(fdObj)) {
+        JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
+                        "Socket closed");
+        return -1;
+    }
+    fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID);
+
+    if (ioctl(fd, FIONREAD, &retval) < 0) {
+        return -1;
+    }
+    return retval;
+}
--- a/src/java.base/unix/native/libnet/net_util_md.c	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/unix/native/libnet/net_util_md.c	Mon Oct 20 12:04:12 2014 -0700
@@ -790,6 +790,11 @@
 #endif
 }
 
+JNIEXPORT jint JNICALL
+NET_EnableFastTcpLoopback(int fd) {
+    return 0;
+}
+
 /* In the case of an IPv4 Inetaddress this method will return an
  * IPv4 mapped address where IPv6 is available and v4MappedAddress is TRUE.
  * Otherwise it will return a sockaddr_in structure for an IPv4 InetAddress.
--- a/src/java.base/unix/native/libnio/ch/Net.c	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/unix/native/libnio/ch/Net.c	Mon Oct 20 12:04:12 2014 -0700
@@ -188,7 +188,7 @@
 
 JNIEXPORT int JNICALL
 Java_sun_nio_ch_Net_socket0(JNIEnv *env, jclass cl, jboolean preferIPv6,
-                            jboolean stream, jboolean reuse)
+                            jboolean stream, jboolean reuse, jboolean ignored)
 {
     int fd;
     int type = (stream ? SOCK_STREAM : SOCK_DGRAM);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/windows/native/libnet/AbstractPlainDatagramSocketImpl.c	Mon Oct 20 12:04:12 2014 -0700
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include <windows.h>
+#include <winsock2.h>
+
+#include "jvm.h"
+#include "jni_util.h"
+#include "net_util.h"
+
+#include "java_net_AbstractPlainDatagramSocketImpl.h"
+
+static jfieldID IO_fd_fdID;
+
+static jfieldID apdsi_fdID;
+
+
+/*
+ * Class:     java_net_AbstractPlainDatagramSocketImpl
+ * Method:    init
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL
+Java_java_net_AbstractPlainDatagramSocketImpl_init(JNIEnv *env, jclass cls) {
+
+    apdsi_fdID = (*env)->GetFieldID(env, cls, "fd",
+                                   "Ljava/io/FileDescriptor;");
+    CHECK_NULL(apdsi_fdID);
+
+    IO_fd_fdID = NET_GetFileDescriptorID(env);
+    CHECK_NULL(IO_fd_fdID);
+
+    JNU_CHECK_EXCEPTION(env);
+}
+
+/*
+ * Class:     java_net_AbstractPlainDatagramSocketImpl
+ * Method:    dataAvailable
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable
+(JNIEnv *env, jobject this) {
+    SOCKET fd;
+    int  retval;
+
+    jobject fdObj = (*env)->GetObjectField(env, this, apdsi_fdID);
+
+    if (IS_NULL(fdObj)) {
+        JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
+                        "Socket closed");
+        return -1;
+    }
+    fd = (SOCKET)(*env)->GetIntField(env, fdObj, IO_fd_fdID);
+
+    if (ioctlsocket(fd, FIONREAD, &retval) < 0) {
+        return -1;
+    }
+    return retval;
+}
+
--- a/src/java.base/windows/native/libnet/net_util_md.c	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/windows/native/libnet/net_util_md.c	Mon Oct 20 12:04:12 2014 -0700
@@ -29,6 +29,9 @@
 #include "net_util.h"
 #include "jni.h"
 
+// Taken from mstcpip.h in Windows SDK 8.0 or newer.
+#define SIO_LOOPBACK_FAST_PATH              _WSAIOW(IOC_VENDOR,16)
+
 #ifndef IPTOS_TOS_MASK
 #define IPTOS_TOS_MASK 0x1e
 #endif
@@ -844,6 +847,25 @@
     }
 }
 
+/**
+ * Enables SIO_LOOPBACK_FAST_PATH
+ */
+JNIEXPORT jint JNICALL
+NET_EnableFastTcpLoopback(int fd) {
+    int enabled = 1;
+    DWORD result_byte_count = -1;
+    int result = WSAIoctl(fd,
+                          SIO_LOOPBACK_FAST_PATH,
+                          &enabled,
+                          sizeof(enabled),
+                          NULL,
+                          0,
+                          &result_byte_count,
+                          NULL,
+                          NULL);
+    return result == SOCKET_ERROR ? WSAGetLastError() : 0;
+}
+
 /* If address types is IPv6, then IPv6 must be available. Otherwise
  * no address can be generated. In the case of an IPv4 Inetaddress this
  * method will return an IPv4 mapped address where IPv6 is available and
--- a/src/java.base/windows/native/libnio/ch/Net.c	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.base/windows/native/libnio/ch/Net.c	Mon Oct 20 12:04:12 2014 -0700
@@ -127,7 +127,7 @@
 
 JNIEXPORT jint JNICALL
 Java_sun_nio_ch_Net_socket0(JNIEnv *env, jclass cl, jboolean preferIPv6,
-                            jboolean stream, jboolean reuse)
+                            jboolean stream, jboolean reuse, jboolean fastLoopback)
 {
     SOCKET s;
     int domain = (preferIPv6) ? AF_INET6 : AF_INET;
@@ -152,6 +152,20 @@
         NET_ThrowNew(env, WSAGetLastError(), "socket");
     }
 
+    if (stream && fastLoopback) {
+        static int loopback_available = 1;
+        if (loopback_available) {
+            int rv = NET_EnableFastTcpLoopback((jint)s);
+            if (rv) {
+                if (rv == WSAEOPNOTSUPP) {
+                    loopback_available = 0;
+                } else {
+                    NET_ThrowNew(env, rv, "fastLoopback");
+                }
+            }
+        }
+    }
+
     return (jint)s;
 }
 
--- a/src/java.desktop/share/classes/sun/awt/image/BytePackedRaster.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.desktop/share/classes/sun/awt/image/BytePackedRaster.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1408,10 +1408,10 @@
             }
         }
 
-        int lastbit = (dataBitOffset
-                       + (height-1) * scanlineStride * 8
-                       + (width-1) * pixelBitStride
-                       + pixelBitStride - 1);
+        long lastbit = (long) dataBitOffset
+                       + (long) (height - 1) * (long) scanlineStride * 8
+                       + (long) (width - 1) * (long) pixelBitStride
+                       + (long) pixelBitStride - 1;
         if (lastbit < 0 || lastbit / 8 >= data.length) {
             throw new RasterFormatException("raster dimensions overflow " +
                                             "array bounds");
--- a/src/java.desktop/share/native/libfontmanager/layout/ContextualSubstSubtables.cpp	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.desktop/share/native/libfontmanager/layout/ContextualSubstSubtables.cpp	Mon Oct 20 12:04:12 2014 -0700
@@ -243,12 +243,22 @@
         le_uint16 srSetCount = SWAPW(subRuleSetCount);
 
         if (coverageIndex < srSetCount) {
+            LEReferenceToArrayOf<Offset> subRuleSetTableOffsetArrayRef(base, success,
+                    &subRuleSetTableOffsetArray[coverageIndex], 1);
+            if (LE_FAILURE(success)) {
+                return 0;
+            }
             Offset subRuleSetTableOffset = SWAPW(subRuleSetTableOffsetArray[coverageIndex]);
             LEReferenceTo<SubRuleSetTable>
                  subRuleSetTable(base, success, (const SubRuleSetTable *) ((char *) this + subRuleSetTableOffset));
             le_uint16 subRuleCount = SWAPW(subRuleSetTable->subRuleCount);
             le_int32 position = glyphIterator->getCurrStreamPosition();
 
+            LEReferenceToArrayOf<Offset> subRuleTableOffsetArrayRef(base, success,
+                    subRuleSetTable->subRuleTableOffsetArray, subRuleCount);
+            if (LE_FAILURE(success)) {
+                return 0;
+            }
             for (le_uint16 subRule = 0; subRule < subRuleCount; subRule += 1) {
                 Offset subRuleTableOffset =
                     SWAPW(subRuleSetTable->subRuleTableOffsetArray[subRule]);
@@ -301,34 +311,44 @@
                                                                 glyphIterator->getCurrGlyphID(),
                                                                 success);
 
-        if (setClass < scSetCount && subClassSetTableOffsetArray[setClass] != 0) {
-            Offset subClassSetTableOffset = SWAPW(subClassSetTableOffsetArray[setClass]);
-            LEReferenceTo<SubClassSetTable>
-                 subClassSetTable(base, success, (const SubClassSetTable *) ((char *) this + subClassSetTableOffset));
-            le_uint16 subClassRuleCount = SWAPW(subClassSetTable->subClassRuleCount);
-            le_int32 position = glyphIterator->getCurrStreamPosition();
+        if (setClass < scSetCount) {
+            LEReferenceToArrayOf<Offset>
+                 subClassSetTableOffsetArrayRef(base, success, subClassSetTableOffsetArray, setClass);
+            if (LE_FAILURE(success)) { return 0; }
+            if (subClassSetTableOffsetArray[setClass] != 0) {
 
-            for (le_uint16 scRule = 0; scRule < subClassRuleCount; scRule += 1) {
-                Offset subClassRuleTableOffset =
-                    SWAPW(subClassSetTable->subClassRuleTableOffsetArray[scRule]);
-                LEReferenceTo<SubClassRuleTable>
-                     subClassRuleTable(subClassSetTable, success, subClassRuleTableOffset);
-                le_uint16 matchCount = SWAPW(subClassRuleTable->glyphCount) - 1;
-                le_uint16 substCount = SWAPW(subClassRuleTable->substCount);
+                Offset subClassSetTableOffset = SWAPW(subClassSetTableOffsetArray[setClass]);
+                LEReferenceTo<SubClassSetTable>
+                    subClassSetTable(base, success, (const SubClassSetTable *) ((char *) this + subClassSetTableOffset));
+                le_uint16 subClassRuleCount = SWAPW(subClassSetTable->subClassRuleCount);
+                le_int32 position = glyphIterator->getCurrStreamPosition();
+                LEReferenceToArrayOf<Offset>
+                    subClassRuleTableOffsetArrayRef(base, success, subClassSetTable->subClassRuleTableOffsetArray, subClassRuleCount);
+                if (LE_FAILURE(success)) {
+                    return 0;
+                }
+                for (le_uint16 scRule = 0; scRule < subClassRuleCount; scRule += 1) {
+                    Offset subClassRuleTableOffset =
+                        SWAPW(subClassSetTable->subClassRuleTableOffsetArray[scRule]);
+                    LEReferenceTo<SubClassRuleTable>
+                        subClassRuleTable(subClassSetTable, success, subClassRuleTableOffset);
+                    le_uint16 matchCount = SWAPW(subClassRuleTable->glyphCount) - 1;
+                    le_uint16 substCount = SWAPW(subClassRuleTable->substCount);
 
-                LEReferenceToArrayOf<le_uint16> classArray(base, success, subClassRuleTable->classArray, matchCount+1);
+                    LEReferenceToArrayOf<le_uint16> classArray(base, success, subClassRuleTable->classArray, matchCount+1);
 
-                if (LE_FAILURE(success)) { return 0; }
-                if (matchGlyphClasses(classArray, matchCount, glyphIterator, classDefinitionTable, success)) {
-                    LEReferenceToArrayOf<SubstitutionLookupRecord>
-                      substLookupRecordArray(base, success, (const SubstitutionLookupRecord *) &subClassRuleTable->classArray[matchCount], substCount);
+                    if (LE_FAILURE(success)) { return 0; }
+                    if (matchGlyphClasses(classArray, matchCount, glyphIterator, classDefinitionTable, success)) {
+                        LEReferenceToArrayOf<SubstitutionLookupRecord>
+                          substLookupRecordArray(base, success, (const SubstitutionLookupRecord *) &subClassRuleTable->classArray[matchCount], substCount);
 
-                    applySubstitutionLookups(lookupProcessor, substLookupRecordArray, substCount, glyphIterator, fontInstance, position, success);
+                        applySubstitutionLookups(lookupProcessor, substLookupRecordArray, substCount, glyphIterator, fontInstance, position, success);
 
-                    return matchCount + 1;
+                        return matchCount + 1;
+                    }
+
+                    glyphIterator->setCurrStreamPosition(position);
                 }
-
-                glyphIterator->setCurrStreamPosition(position);
             }
         }
 
@@ -442,13 +462,22 @@
         le_uint16 srSetCount = SWAPW(chainSubRuleSetCount);
 
         if (coverageIndex < srSetCount) {
+            LEReferenceToArrayOf<Offset>
+                chainSubRuleSetTableOffsetArrayRef(base, success, chainSubRuleSetTableOffsetArray, coverageIndex);
+            if (LE_FAILURE(success)) {
+                return 0;
+            }
             Offset chainSubRuleSetTableOffset = SWAPW(chainSubRuleSetTableOffsetArray[coverageIndex]);
             LEReferenceTo<ChainSubRuleSetTable>
                  chainSubRuleSetTable(base, success, (const ChainSubRuleSetTable *) ((char *) this + chainSubRuleSetTableOffset));
             le_uint16 chainSubRuleCount = SWAPW(chainSubRuleSetTable->chainSubRuleCount);
             le_int32 position = glyphIterator->getCurrStreamPosition();
             GlyphIterator tempIterator(*glyphIterator, emptyFeatureList);
-
+            LEReferenceToArrayOf<Offset>
+                chainSubRuleTableOffsetArrayRef(base, success, chainSubRuleSetTable->chainSubRuleTableOffsetArray, chainSubRuleCount);
+            if (LE_FAILURE(success)) {
+                return 0;
+            }
             for (le_uint16 subRule = 0; subRule < chainSubRuleCount; subRule += 1) {
                 Offset chainSubRuleTableOffset =
                     SWAPW(chainSubRuleSetTable->chainSubRuleTableOffsetArray[subRule]);
@@ -530,6 +559,11 @@
         le_int32 setClass = inputClassDefinitionTable->getGlyphClass(inputClassDefinitionTable,
                                                                      glyphIterator->getCurrGlyphID(),
                                                                      success);
+        LEReferenceToArrayOf<Offset>
+            chainSubClassSetTableOffsetArrayRef(base, success, chainSubClassSetTableOffsetArray, setClass);
+        if (LE_FAILURE(success)) {
+            return 0;
+        }
 
         if (setClass < scSetCount && chainSubClassSetTableOffsetArray[setClass] != 0) {
             Offset chainSubClassSetTableOffset = SWAPW(chainSubClassSetTableOffsetArray[setClass]);
@@ -538,7 +572,11 @@
             le_uint16 chainSubClassRuleCount = SWAPW(chainSubClassSetTable->chainSubClassRuleCount);
             le_int32 position = glyphIterator->getCurrStreamPosition();
             GlyphIterator tempIterator(*glyphIterator, emptyFeatureList);
-
+            LEReferenceToArrayOf<Offset>
+                chainSubClassRuleTableOffsetArrayRef(base, success, chainSubClassSetTable->chainSubClassRuleTableOffsetArray, chainSubClassRuleCount);
+            if (LE_FAILURE(success)) {
+                return 0;
+            }
             for (le_uint16 scRule = 0; scRule < chainSubClassRuleCount; scRule += 1) {
                 Offset chainSubClassRuleTableOffset =
                     SWAPW(chainSubClassSetTable->chainSubClassRuleTableOffsetArray[scRule]);
@@ -603,12 +641,14 @@
     }
 
     le_uint16 backtrkGlyphCount = SWAPW(backtrackGlyphCount);
+    LEReferenceToArrayOf<Offset> backtrackGlyphArrayRef(base, success, backtrackCoverageTableOffsetArray, backtrkGlyphCount);
+    if (LE_FAILURE(success)) {
+        return 0;
+    }
     le_uint16 inputGlyphCount = (le_uint16) SWAPW(backtrackCoverageTableOffsetArray[backtrkGlyphCount]);
     LEReferenceToArrayOf<Offset>   inputCoverageTableOffsetArray(base, success, &backtrackCoverageTableOffsetArray[backtrkGlyphCount + 1], inputGlyphCount+2); // offset
     if (LE_FAILURE(success)) { return 0; }
     const le_uint16 lookaheadGlyphCount = (le_uint16) SWAPW(inputCoverageTableOffsetArray[inputGlyphCount]);
-
-    if( LE_FAILURE(success)) { return 0; }
     LEReferenceToArrayOf<Offset>   lookaheadCoverageTableOffsetArray(base, success, inputCoverageTableOffsetArray.getAlias(inputGlyphCount + 1, success), lookaheadGlyphCount+2);
 
     if( LE_FAILURE(success) ) { return 0; }
--- a/src/java.desktop/unix/classes/sun/print/CUPSPrinter.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.desktop/unix/classes/sun/print/CUPSPrinter.java	Mon Oct 20 12:04:12 2014 -0700
@@ -136,7 +136,7 @@
     /**
      * Returns array of MediaSizeNames derived from PPD.
      */
-    public MediaSizeName[] getMediaSizeNames() {
+    MediaSizeName[] getMediaSizeNames() {
         initMedia();
         return cupsMediaSNames;
     }
@@ -145,7 +145,7 @@
     /**
      * Returns array of Custom MediaSizeNames derived from PPD.
      */
-    public CustomMediaSizeName[] getCustomMediaSizeNames() {
+    CustomMediaSizeName[] getCustomMediaSizeNames() {
         initMedia();
         return cupsCustomMediaSNames;
     }
@@ -157,7 +157,7 @@
     /**
      * Returns array of MediaPrintableArea derived from PPD.
      */
-    public MediaPrintableArea[] getMediaPrintableArea() {
+    MediaPrintableArea[] getMediaPrintableArea() {
         initMedia();
         return cupsMediaPrintables;
     }
@@ -165,7 +165,7 @@
     /**
      * Returns array of MediaTrays derived from PPD.
      */
-    public MediaTray[] getMediaTrays() {
+    MediaTray[] getMediaTrays() {
         initMedia();
         return cupsMediaTrays;
     }
--- a/src/java.desktop/unix/classes/sun/print/IPPPrintService.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.desktop/unix/classes/sun/print/IPPPrintService.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1002,7 +1002,9 @@
 
     public synchronized Class<?>[] getSupportedAttributeCategories() {
         if (supportedCats != null) {
-            return supportedCats;
+            Class<?> [] copyCats = new Class<?>[supportedCats.length];
+            System.arraycopy(supportedCats, 0, copyCats, 0, copyCats.length);
+            return copyCats;
         }
 
         initAttributes();
@@ -1065,7 +1067,9 @@
 
         supportedCats = new Class<?>[catList.size()];
         catList.toArray(supportedCats);
-        return supportedCats;
+        Class<?>[] copyCats = new Class<?>[supportedCats.length];
+        System.arraycopy(supportedCats, 0, copyCats, 0, copyCats.length);
+        return copyCats;
     }
 
 
--- a/src/java.desktop/windows/native/libsplashscreen/splashscreen_sys.c	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.desktop/windows/native/libsplashscreen/splashscreen_sys.c	Mon Oct 20 12:04:12 2014 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -213,6 +213,14 @@
 void
 SplashRedrawWindow(Splash * splash)
 {
+    if (!SplashIsStillLooping(splash)) {
+        KillTimer(splash->hWnd, 0);
+    }
+
+    if (splash->currentFrame < 0) {
+        return;
+    }
+
     SplashUpdateScreenData(splash);
     if (splash->isLayered) {
         BLENDFUNCTION bf;
@@ -303,9 +311,6 @@
             time = 0;
         SetTimer(splash->hWnd, 0, time, NULL);
     }
-    else {
-        KillTimer(splash->hWnd, 0);
-    }
 }
 
 void SplashReconfigureNow(Splash * splash) {
--- a/src/java.logging/share/classes/java/util/logging/LogRecord.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.logging/share/classes/java/util/logging/LogRecord.java	Mon Oct 20 12:04:12 2014 -0700
@@ -509,7 +509,13 @@
         // If necessary, try to regenerate the resource bundle.
         if (resourceBundleName != null) {
             try {
-                resourceBundle = ResourceBundle.getBundle(resourceBundleName);
+                // use system class loader to ensure the ResourceBundle
+                // instance is a different instance than null loader uses
+                final ResourceBundle bundle =
+                        ResourceBundle.getBundle(resourceBundleName,
+                                Locale.getDefault(),
+                                ClassLoader.getSystemClassLoader());
+                resourceBundle = bundle;
             } catch (MissingResourceException ex) {
                 // This is not a good place to throw an exception,
                 // so we simply leave the resourceBundle null.
--- a/src/java.logging/share/classes/java/util/logging/Logger.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.logging/share/classes/java/util/logging/Logger.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1937,6 +1937,9 @@
         }
 
         setCallersClassLoaderRef(callersClass);
+        if (isSystemLogger && getCallersClassLoader() != null) {
+            checkPermission();
+        }
         if (findResourceBundle(name, true) == null) {
             // We've failed to find an expected ResourceBundle.
             // unset the caller's ClassLoader since we were unable to find the
@@ -2170,11 +2173,13 @@
                 return trb;
             }
             final String rbName = isSystemLogger
-                ? trb.resourceBundleName
+                // ancestor of a system logger is expected to be a system logger.
+                // ignore resource bundle name if it's not.
+                ? (target.isSystemLogger ? trb.resourceBundleName : null)
                 : target.getResourceBundleName();
             if (rbName != null) {
                 return LoggerBundle.get(rbName,
-                            findResourceBundle(rbName, true));
+                        findResourceBundle(rbName, true));
             }
             target = isSystemLogger ? target.parent : target.getParent();
         }
--- a/src/java.naming/share/classes/javax/naming/spi/NamingManager.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.naming/share/classes/javax/naming/spi/NamingManager.java	Mon Oct 20 12:04:12 2014 -0700
@@ -25,9 +25,7 @@
 
 package javax.naming.spi;
 
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.StringTokenizer;
+import java.util.*;
 import java.net.MalformedURLException;
 
 import javax.naming.*;
@@ -625,15 +623,28 @@
     /**
      * Creates an initial context using the specified environment
      * properties.
-     *<p>
-     * If an InitialContextFactoryBuilder has been installed,
-     * it is used to create the factory for creating the initial context.
-     * Otherwise, the class specified in the
-     * <tt>Context.INITIAL_CONTEXT_FACTORY</tt> environment property is used.
-     * Note that an initial context factory (an object that implements the
-     * InitialContextFactory interface) must be public and must have a
-     * public constructor that accepts no arguments.
-     *
+     * <p>
+     * This is done as follows:
+     * <ul>
+     * <li>If an InitialContextFactoryBuilder has been installed,
+     *     it is used to create the factory for creating the initial
+     *     context</li>
+     * <li>Otherwise, the class specified in the
+     *     <tt>Context.INITIAL_CONTEXT_FACTORY</tt> environment property
+     *     is used
+     *     <ul>
+     *     <li>First, the {@linkplain java.util.ServiceLoader ServiceLoader}
+     *         mechanism tries to locate an {@code InitialContextFactory}
+     *         provider using the current thread's context class loader</li>
+     *     <li>Failing that, this implementation tries to locate a suitable
+     *         {@code InitialContextFactory} using a built-in mechanism
+     *         <br>
+     *         (Note that an initial context factory (an object that implements
+     *         the InitialContextFactory interface) must be public and must have
+     *         a public constructor that accepts no arguments)</li>
+     *     </ul>
+     * </li>
+     * </ul>
      * @param env The possibly null environment properties used when
      *                  creating the context.
      * @return A non-null initial context.
@@ -649,11 +660,11 @@
      */
     public static Context getInitialContext(Hashtable<?,?> env)
         throws NamingException {
-        InitialContextFactory factory;
+        InitialContextFactory factory = null;
 
         InitialContextFactoryBuilder builder = getInitialContextFactoryBuilder();
         if (builder == null) {
-            // No factory installed, use property
+            // No builder installed, use property
             // Get initial context factory class name
 
             String className = env != null ?
@@ -666,16 +677,39 @@
                 throw ne;
             }
 
+            ServiceLoader<InitialContextFactory> loader =
+                    ServiceLoader.load(InitialContextFactory.class);
+
+            Iterator<InitialContextFactory> iterator = loader.iterator();
             try {
-                factory = (InitialContextFactory)
-                    helper.loadClass(className).newInstance();
-            } catch(Exception e) {
+                while (iterator.hasNext()) {
+                    InitialContextFactory f = iterator.next();
+                    if (f.getClass().getName().equals(className)) {
+                        factory = f;
+                        break;
+                    }
+                }
+            } catch (ServiceConfigurationError e) {
                 NoInitialContextException ne =
-                    new NoInitialContextException(
-                        "Cannot instantiate class: " + className);
+                        new NoInitialContextException(
+                                "Cannot load initial context factory "
+                                        + "'" + className + "'");
                 ne.setRootCause(e);
                 throw ne;
             }
+
+            if (factory == null) {
+                try {
+                    factory = (InitialContextFactory)
+                            helper.loadClass(className).newInstance();
+                } catch (Exception e) {
+                    NoInitialContextException ne =
+                            new NoInitialContextException(
+                                    "Cannot instantiate class: " + className);
+                    ne.setRootCause(e);
+                    throw ne;
+                }
+            }
         } else {
             factory = builder.createInitialContextFactory(env);
         }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java	Mon Oct 20 12:04:12 2014 -0700
@@ -25,6 +25,8 @@
 import java.io.InputStream;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -35,6 +37,7 @@
 import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
 import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
+import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolver;
 import com.sun.org.apache.xml.internal.security.transforms.Transform;
 import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
@@ -118,43 +121,50 @@
             log.log(java.util.logging.Level.FINE, "Registering default algorithms");
         }
         try {
-            //
-            // Bind the default prefixes
-            //
-            ElementProxy.registerDefaultPrefixes();
+            AccessController.doPrivileged(new PrivilegedExceptionAction<Void>(){
+                @Override public Void run() throws XMLSecurityException {
+                    //
+                    // Bind the default prefixes
+                    //
+                    ElementProxy.registerDefaultPrefixes();
 
-            //
-            // Set the default Transforms
-            //
-            Transform.registerDefaultAlgorithms();
+                    //
+                    // Set the default Transforms
+                    //
+                    Transform.registerDefaultAlgorithms();
 
-            //
-            // Set the default signature algorithms
-            //
-            SignatureAlgorithm.registerDefaultAlgorithms();
+                    //
+                    // Set the default signature algorithms
+                    //
+                    SignatureAlgorithm.registerDefaultAlgorithms();
 
-            //
-            // Set the default JCE algorithms
-            //
-            JCEMapper.registerDefaultAlgorithms();
+                    //
+                    // Set the default JCE algorithms
+                    //
+                    JCEMapper.registerDefaultAlgorithms();
 
-            //
-            // Set the default c14n algorithms
-            //
-            Canonicalizer.registerDefaultAlgorithms();
+                    //
+                    // Set the default c14n algorithms
+                    //
+                    Canonicalizer.registerDefaultAlgorithms();
 
-            //
-            // Register the default resolvers
-            //
-            ResourceResolver.registerDefaultResolvers();
+                    //
+                    // Register the default resolvers
+                    //
+                    ResourceResolver.registerDefaultResolvers();
 
-            //
-            // Register the default key resolvers
-            //
-            KeyResolver.registerDefaultResolvers();
-        } catch (Exception ex) {
-            log.log(java.util.logging.Level.SEVERE, ex.getMessage(), ex);
-            ex.printStackTrace();
+                    //
+                    // Register the default key resolvers
+                    //
+                    KeyResolver.registerDefaultResolvers();
+
+                    return null;
+                }
+           });
+        } catch (PrivilegedActionException ex) {
+            XMLSecurityException xse = (XMLSecurityException)ex.getException();
+            log.log(java.util.logging.Level.SEVERE, xse.getMessage(), xse);
+            xse.printStackTrace();
         }
     }
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java	Mon Oct 20 12:04:12 2014 -0700
@@ -27,6 +27,7 @@
 
 import com.sun.org.apache.xml.internal.security.encryption.XMLCipher;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
 import org.w3c.dom.Element;
 
 
@@ -49,8 +50,11 @@
      *
      * @param id
      * @param algorithm
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register the JCE algorithm
      */
     public static void register(String id, Algorithm algorithm) {
+        JavaUtils.checkRegisterPermission();
         algorithmsMap.put(id, algorithm);
     }
 
@@ -296,8 +300,11 @@
     /**
      * Sets the default Provider for obtaining the security algorithms
      * @param provider the default providerId.
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to set the JCE provider
      */
     public static void setProviderId(String provider) {
+        JavaUtils.checkRegisterPermission();
         providerName = provider;
     }
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java	Mon Oct 20 12:04:12 2014 -0700
@@ -37,6 +37,7 @@
 import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -314,18 +315,21 @@
     }
 
     /**
-     * Registers implementing class of the Transform algorithm with algorithmURI
+     * Registers implementing class of the SignatureAlgorithm with algorithmURI
      *
-     * @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>.
+     * @param algorithmURI algorithmURI URI representation of <code>SignatureAlgorithm</code>.
      * @param implementingClass <code>implementingClass</code> the implementing class of
      * {@link SignatureAlgorithmSpi}
      * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
      * @throws XMLSignatureException
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register the signature algorithm
      */
     @SuppressWarnings("unchecked")
     public static void register(String algorithmURI, String implementingClass)
        throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
            XMLSignatureException {
+        JavaUtils.checkRegisterPermission();
         if (log.isLoggable(java.util.logging.Level.FINE)) {
             log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
         }
@@ -352,15 +356,18 @@
     /**
      * Registers implementing class of the Transform algorithm with algorithmURI
      *
-     * @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>.
+     * @param algorithmURI algorithmURI URI representation of <code>SignatureAlgorithm</code>.
      * @param implementingClass <code>implementingClass</code> the implementing class of
      * {@link SignatureAlgorithmSpi}
      * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
      * @throws XMLSignatureException
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register the signature algorithm
      */
     public static void register(String algorithmURI, Class<? extends SignatureAlgorithmSpi> implementingClass)
        throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
            XMLSignatureException {
+        JavaUtils.checkRegisterPermission();
         if (log.isLoggable(java.util.logging.Level.FINE)) {
             log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
         }
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java	Mon Oct 20 12:04:12 2014 -0700
@@ -41,6 +41,7 @@
 import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315WithComments;
 import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerPhysical;
 import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
@@ -142,10 +143,13 @@
      * @param algorithmURI
      * @param implementingClass
      * @throws AlgorithmAlreadyRegisteredException
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register the canonicalizer
      */
     @SuppressWarnings("unchecked")
     public static void register(String algorithmURI, String implementingClass)
         throws AlgorithmAlreadyRegisteredException, ClassNotFoundException {
+        JavaUtils.checkRegisterPermission();
         // check whether URI is already registered
         Class<? extends CanonicalizerSpi> registeredClass =
             canonicalizerHash.get(algorithmURI);
@@ -166,9 +170,12 @@
      * @param algorithmURI
      * @param implementingClass
      * @throws AlgorithmAlreadyRegisteredException
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register the canonicalizer
      */
-    public static void register(String algorithmURI, Class<CanonicalizerSpi> implementingClass)
+    public static void register(String algorithmURI, Class<? extends CanonicalizerSpi> implementingClass)
         throws AlgorithmAlreadyRegisteredException, ClassNotFoundException {
+        JavaUtils.checkRegisterPermission();
         // check whether URI is already registered
         Class<? extends CanonicalizerSpi> registeredClass = canonicalizerHash.get(algorithmURI);
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java	Mon Oct 20 12:04:12 2014 -0700
@@ -42,6 +42,7 @@
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SKIResolver;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SubjectNameResolver;
 import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
@@ -175,9 +176,12 @@
      * @throws InstantiationException
      * @throws IllegalAccessException
      * @throws ClassNotFoundException
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register the key resolver
      */
     public static void register(String className, boolean globalResolver)
         throws ClassNotFoundException, IllegalAccessException, InstantiationException {
+        JavaUtils.checkRegisterPermission();
         KeyResolverSpi keyResolverSpi =
             (KeyResolverSpi) Class.forName(className).newInstance();
         keyResolverSpi.setGlobalResolver(globalResolver);
@@ -195,8 +199,11 @@
      *
      * @param className
      * @param globalResolver Whether the KeyResolverSpi is a global resolver or not
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register the key resolver
      */
     public static void registerAtStart(String className, boolean globalResolver) {
+        JavaUtils.checkRegisterPermission();
         KeyResolverSpi keyResolverSpi = null;
         Exception ex = null;
         try {
@@ -228,11 +235,14 @@
      *
      * @param keyResolverSpi a KeyResolverSpi instance to register
      * @param start whether to register the KeyResolverSpi at the start of the list or not
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register the key resolver
      */
     public static void register(
         KeyResolverSpi keyResolverSpi,
         boolean start
     ) {
+        JavaUtils.checkRegisterPermission();
         KeyResolver resolver = new KeyResolver(keyResolverSpi);
         if (start) {
             resolverVector.add(0, resolver);
@@ -254,9 +264,12 @@
      * @throws InstantiationException
      * @throws IllegalAccessException
      * @throws ClassNotFoundException
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register the key resolver
      */
     public static void registerClassNames(List<String> classNames)
         throws ClassNotFoundException, IllegalAccessException, InstantiationException {
+        JavaUtils.checkRegisterPermission();
         List<KeyResolver> keyResolverList = new ArrayList<KeyResolver>(classNames.size());
         for (String className : classNames) {
             KeyResolverSpi keyResolverSpi =
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java	Mon Oct 20 12:04:12 2014 -0700
@@ -46,6 +46,7 @@
 import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXSLT;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.HelperNodeList;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Document;
@@ -181,11 +182,14 @@
      * class of {@link TransformSpi}
      * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
      * is already registered
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register the transform
      */
     @SuppressWarnings("unchecked")
     public static void register(String algorithmURI, String implementingClass)
         throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
             InvalidTransformException {
+        JavaUtils.checkRegisterPermission();
         // are we already registered?
         Class<? extends TransformSpi> transformSpi = transformSpiHash.get(algorithmURI);
         if (transformSpi != null) {
@@ -206,9 +210,12 @@
      * class of {@link TransformSpi}
      * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
      * is already registered
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register the transform
      */
     public static void register(String algorithmURI, Class<? extends TransformSpi> implementingClass)
         throws AlgorithmAlreadyRegisteredException {
+        JavaUtils.checkRegisterPermission();
         // are we already registered?
         Class<? extends TransformSpi> transformSpi = transformSpiHash.get(algorithmURI);
         if (transformSpi != null) {
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java	Mon Oct 20 12:04:12 2014 -0700
@@ -468,9 +468,12 @@
      * @param namespace
      * @param prefix
      * @throws XMLSecurityException
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to set the default prefix
      */
     public static void setDefaultPrefix(String namespace, String prefix)
         throws XMLSecurityException {
+        JavaUtils.checkRegisterPermission();
         if (prefixMappings.containsValue(prefix)) {
             String storedPrefix = prefixMappings.get(namespace);
             if (!storedPrefix.equals(prefix)) {
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java	Mon Oct 20 12:04:12 2014 -0700
@@ -28,6 +28,7 @@
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.security.SecurityPermission;
 
 /**
  * A collection of different, general-purpose methods for JAVA-specific things
@@ -39,6 +40,10 @@
     private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(JavaUtils.class.getName());
 
+    private static final SecurityPermission REGISTER_PERMISSION =
+        new SecurityPermission(
+            "com.sun.org.apache.xml.internal.security.register");
+
     private JavaUtils() {
         // we don't allow instantiation
     }
@@ -147,6 +152,23 @@
     }
 
     /**
+     * Throws a {@code SecurityException} if a security manager is installed
+     * and the caller is not allowed to register an implementation of an
+     * algorithm, transform, or other security sensitive XML Signature function.
+     *
+     * @throws SecurityException if a security manager is installed and the
+     *    caller has not been granted the
+     *    {@literal "com.sun.org.apache.xml.internal.security.register"}
+     *    {@code SecurityPermission}
+     */
+    public static void checkRegisterPermission() {
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            sm.checkPermission(REGISTER_PERMISSION);
+        }
+    }
+
+    /**
      * Converts an ASN.1 DSA value to a XML Signature DSA Value.
      *
      * The JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java	Mon Oct 20 12:04:12 2014 -0700
@@ -80,32 +80,44 @@
     /**
      * Set the prefix for the digital signature namespace
      * @param prefix the new prefix for the digital signature namespace
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to set the prefix
      */
     public static void setDsPrefix(String prefix) {
+        JavaUtils.checkRegisterPermission();
         dsPrefix = prefix;
     }
 
     /**
      * Set the prefix for the digital signature 1.1 namespace
      * @param prefix the new prefix for the digital signature 1.1 namespace
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to set the prefix
      */
     public static void setDs11Prefix(String prefix) {
+        JavaUtils.checkRegisterPermission();
         ds11Prefix = prefix;
     }
 
     /**
      * Set the prefix for the encryption namespace
      * @param prefix the new prefix for the encryption namespace
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to set the prefix
      */
     public static void setXencPrefix(String prefix) {
+        JavaUtils.checkRegisterPermission();
         xencPrefix = prefix;
     }
 
     /**
      * Set the prefix for the encryption namespace 1.1
      * @param prefix the new prefix for the encryption namespace 1.1
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to set the prefix
      */
     public static void setXenc11Prefix(String prefix) {
+        JavaUtils.checkRegisterPermission();
         xenc11Prefix = prefix;
     }
 
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java	Mon Oct 20 12:04:12 2014 -0700
@@ -27,6 +27,7 @@
 import java.util.Map;
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
+import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
 import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverDirectHTTP;
 import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverFragment;
 import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverLocalFilesystem;
@@ -199,9 +200,12 @@
      * the class cannot be registered.
      *
      * @param className the name of the ResourceResolverSpi class to be registered
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register a resource resolver
      */
     @SuppressWarnings("unchecked")
     public static void register(String className) {
+        JavaUtils.checkRegisterPermission();
         try {
             Class<ResourceResolverSpi> resourceResolverClass =
                 (Class<ResourceResolverSpi>) Class.forName(className);
@@ -216,9 +220,12 @@
      * list. This method logs a warning if the class cannot be registered.
      *
      * @param className the name of the ResourceResolverSpi class to be registered
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register a resource resolver
      */
     @SuppressWarnings("unchecked")
     public static void registerAtStart(String className) {
+        JavaUtils.checkRegisterPermission();
         try {
             Class<ResourceResolverSpi> resourceResolverClass =
                 (Class<ResourceResolverSpi>) Class.forName(className);
@@ -233,8 +240,11 @@
      * cannot be registered.
      * @param className
      * @param start
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register a resource resolver
      */
     public static void register(Class<? extends ResourceResolverSpi> className, boolean start) {
+        JavaUtils.checkRegisterPermission();
         try {
             ResourceResolverSpi resourceResolverSpi = className.newInstance();
             register(resourceResolverSpi, start);
@@ -250,8 +260,11 @@
      * cannot be registered.
      * @param resourceResolverSpi
      * @param start
+     * @throws SecurityException if a security manager is installed and the
+     *    caller does not have permission to register a resource resolver
      */
     public static void register(ResourceResolverSpi resourceResolverSpi, boolean start) {
+        JavaUtils.checkRegisterPermission();
         synchronized(resolverList) {
             if (start) {
                 resolverList.add(0, new ResourceResolver(resourceResolverSpi));
--- a/test/com/sun/tools/attach/StartManagementAgent.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/test/com/sun/tools/attach/StartManagementAgent.java	Mon Oct 20 12:04:12 2014 -0700
@@ -100,6 +100,7 @@
             ex.printStackTrace(System.err);
         } catch (Throwable t) {
             t.printStackTrace(System.err);
+            throw t;
         }
     }
 
@@ -124,6 +125,7 @@
                 try {
                     System.err.println("Trying remote agent. Try #" + i);
                     testRemoteAgent(vm);
+                    System.err.println("Successfully connected to remote agent");
                     success = true;
                 } catch(Exception ex) {
                     System.err.println("testRemoteAgent failed with exception:");
@@ -136,7 +138,9 @@
                 throw new Exception("testRemoteAgent failed after " + MAX_RETRIES + " tries");
             }
         } finally {
+            System.err.println("Detaching from VM ...");
             vm.detach();
+            System.err.println("Detached");
         }
     }
 
@@ -176,7 +180,10 @@
         mgmtProps.put("com.sun.management.jmxremote.port", port);
         mgmtProps.put("com.sun.management.jmxremote.authenticate", "false");
         mgmtProps.put("com.sun.management.jmxremote.ssl", "false");
+
+        System.err.println("Starting management agent ...");
         vm.startManagementAgent(mgmtProps);
+        System.err.println("Started");
 
         // try to connect - should work
         tryConnect(port, true);
@@ -184,9 +191,12 @@
         // try to start again - should fail
         boolean exception = false;
         try {
+            System.err.println("Starting management agent second time ...");
             vm.startManagementAgent(mgmtProps);
+            System.err.println("Started");
         } catch(AttachOperationFailedException ex) {
             // expected
+            System.err.println("Got expected exception: " + ex.getMessage());
             exception = true;
         }
         if (!exception) {
@@ -204,10 +214,14 @@
 
         boolean succeeded;
         try {
+            System.err.println("Trying to connect to " + jmxUrlStr);
             JMXConnector c = JMXConnectorFactory.connect(url, env);
+            System.err.println("Connected, getting MBeanServerConnection");
             c.getMBeanServerConnection();
+            System.err.println("Success");
             succeeded = true;
         } catch(Exception ex) {
+            ex.printStackTrace(System.err);
             succeeded = false;
         }
         if (succeeded && !shouldSucceed) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/net/ResponseCache/Test2.java	Mon Oct 20 12:04:12 2014 -0700
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8042622
+ * @summary Check for CRL results in IllegalArgumentException "white space not allowed"
+ * @run main/othervm Test2
+ */
+
+import com.sun.net.httpserver.*;
+
+import java.util.*;
+import java.util.concurrent.*;
+import java.io.*;
+import java.net.*;
+import java.security.*;
+import javax.security.auth.callback.*;
+import javax.net.ssl.*;
+
+public class Test2 {
+
+    static volatile boolean failed = false;
+
+    static class Cache extends ResponseCache {
+        public CacheResponse get(URI uri, String method, Map<String,List<String>> headers) {
+            Set<String> keys = headers.keySet();
+            for (String key : keys) {
+                if (key.indexOf(' ') != -1 || key.indexOf('\t') != -1
+                        || key.indexOf(':') != -1)
+                {
+                    failed = true;
+                }
+            }
+            return null;
+        }
+
+        public CacheRequest put(URI uri, URLConnection c) throws IOException {
+            return null;
+        }
+    }
+
+    static int port;
+
+    static String urlstring, redirstring;
+
+    public static void main (String[] args) throws Exception {
+        Handler handler = new Handler();
+        InetSocketAddress addr = new InetSocketAddress (0);
+        HttpServer server = HttpServer.create (addr, 0);
+        port = server.getAddress().getPort();
+        HttpContext ctx = server.createContext ("/test", handler);
+        System.out.println ("Server: " + server.getAddress().getPort());
+        ResponseCache.setDefault(new Cache());
+
+        ExecutorService executor = Executors.newCachedThreadPool();
+        server.setExecutor (executor);
+        server.start ();
+
+        urlstring = "http://127.0.0.1:" + Integer.toString(port)+"/test/foo";
+        redirstring = urlstring + "/redirect/bar";
+
+        URL url = new URL (urlstring);
+        HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
+        urlc.addRequestProperty("X-Foo", "bar");
+        urlc.setInstanceFollowRedirects(true);
+        System.out.println(urlc.getResponseCode());
+        InputStream i = urlc.getInputStream();
+        int count=0;
+        for (int c=i.read(); c!=-1; c=i.read()) {
+            //System.out.write(c);
+            count++;
+        }
+        System.out.println("Read " + count);
+        System.out.println("FINISHED");
+        server.stop(0);
+        executor.shutdownNow();
+        if (failed) {
+            throw new RuntimeException("Test failed");
+        }
+    }
+
+    public static boolean error = false;
+    public static int count = 0;
+
+    static class Handler implements HttpHandler {
+        int invocation = 0;
+        public void handle (HttpExchange t)
+            throws IOException
+        {
+            InputStream is = t.getRequestBody();
+            Headers map = t.getRequestHeaders();
+            Headers rmap = t.getResponseHeaders();
+            invocation ++;
+            if (invocation == 1) {
+                rmap.add("Location", redirstring);
+                while (is.read () != -1) ;
+                is.close();
+                System.out.println ("sending response");
+                t.sendResponseHeaders (301, 0);
+            } else {
+                byte[] buf = "Hello world".getBytes();
+                t.sendResponseHeaders (200, buf.length);
+                OutputStream os = t.getResponseBody();
+                try {
+                        os.write(buf);
+                } catch (IOException e) {
+                        System.out.println ("EX 1 " + e);
+                }
+            }
+            System.out.println ("Closing");
+            t.close();
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/net/SocketPermission/SocketPermissionTest.java	Mon Oct 20 12:04:12 2014 -0700
@@ -0,0 +1,236 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 8047031
+ * @summary SocketPermission tests for legacy socket types
+ * @library ../../../lib/testlibrary
+ * @run testng/othervm/policy=policy SocketPermissionTest
+ */
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+import java.net.MulticastSocket;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketPermission;
+import java.security.AccessControlContext;
+import java.security.AccessController;
+import java.security.Permission;
+import java.security.Permissions;
+import java.security.PrivilegedAction;
+import java.security.ProtectionDomain;
+import java.util.Arrays;
+import java.util.function.Function;
+import java.util.function.IntConsumer;
+import static jdk.testlibrary.Utils.getFreePort;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class SocketPermissionTest {
+    private int freePort = -1;
+
+    //positive tests
+    @Test(dataProvider = "positiveProvider")
+    public void testPositive(Function<String, AccessControlContext> genAcc, IntConsumer func) {
+        String addr = "localhost:" + freePort;
+        AccessControlContext acc = genAcc.apply(addr);
+        AccessController.doPrivileged((PrivilegedAction) () -> {
+            func.accept(freePort);
+            return null;
+        }, acc);
+    }
+
+    //negative tests
+    @Test(dataProvider = "negativeProvider", expectedExceptions = SecurityException.class)
+    public void testNegative(AccessControlContext acc, IntConsumer func) {
+        AccessController.doPrivileged((PrivilegedAction) () -> {
+            func.accept(freePort);
+            return null;
+        }, acc);
+    }
+
+    @BeforeMethod
+    public void setFreePort() throws Exception {
+        freePort = getFreePort();
+    }
+
+    @DataProvider
+    public Object[][] positiveProvider() {
+        //test for SocketPermission "host:port","connect,resolve";
+        Function<String, AccessControlContext> generateAcc1 = (addr) -> getAccessControlContext(
+                new SocketPermission(addr, "listen, connect,resolve"));
+        IntConsumer func1 = (i) -> connectSocketTest(i);
+        IntConsumer func2 = (i) -> connectDatagramSocketTest(i);
+
+        //test for SocketPermission "localhost:1024-","accept";
+        Function<String, AccessControlContext> generateAcc2 = (addr) -> getAccessControlContext(
+                new SocketPermission(addr, "listen,connect,resolve"),
+                new SocketPermission("localhost:1024-", "accept"));
+        IntConsumer func3 = (i) -> acceptServerSocketTest(i);
+
+        //test for SocketPermission "229.227.226.221", "connect,accept"
+        Function<String, AccessControlContext> generateAcc3 = (addr) -> getAccessControlContext(
+                new SocketPermission(addr, "listen,resolve"),
+                new SocketPermission("229.227.226.221", "connect,accept"));
+        IntConsumer func4 = (i) -> sendDatagramPacketTest(i);
+        IntConsumer func5 = (i) -> joinGroupMulticastTest(i);
+
+        //test for SocketPermission "host:port", "listen"
+        Function<String, AccessControlContext> generateAcc4 = (addr) -> getAccessControlContext(
+                new SocketPermission(addr, "listen"));
+        IntConsumer func6 = (i) -> listenDatagramSocketTest(i);
+        IntConsumer func7 = (i) -> listenMulticastSocketTest(i);
+        IntConsumer func8 = (i) -> listenServerSocketTest(i);
+
+        return new Object[][]{
+            {generateAcc1, func1},
+            {generateAcc1, func2},
+            {generateAcc2, func3},
+            {generateAcc3, func4},
+            {generateAcc3, func5},
+            {generateAcc4, func6},
+            {generateAcc4, func7},
+            {generateAcc4, func8}
+        };
+    }
+
+    @DataProvider
+    public Object[][] negativeProvider() {
+        IntConsumer[] funcs = {i -> connectSocketTest(i),
+            i -> connectDatagramSocketTest(i), i -> acceptServerSocketTest(i),
+            i -> sendDatagramPacketTest(i), i -> joinGroupMulticastTest(i),
+            i -> listenDatagramSocketTest(i), i -> listenMulticastSocketTest(i),
+            i -> listenServerSocketTest(i)};
+        return Arrays.stream(funcs).map(f -> {
+            //Construct an AccessControlContext without SocketPermission
+            AccessControlContext acc = getAccessControlContext(
+                    new java.io.FilePermission("<<ALL FILES>>", "read,write,execute,delete"),
+                    new java.net.NetPermission("*"),
+                    new java.util.PropertyPermission("*", "read,write"),
+                    new java.lang.reflect.ReflectPermission("*"),
+                    new java.lang.RuntimePermission("*"),
+                    new java.security.SecurityPermission("*"),
+                    new java.io.SerializablePermission("*"));
+            return new Object[]{acc, f};
+        }).toArray(Object[][]::new);
+    }
+
+    public void connectSocketTest(int port) {
+        try (ServerSocket server = new ServerSocket(port);
+                Socket client = new Socket(InetAddress.getLocalHost(), port);) {
+        } catch (IOException ex) {
+            throw new RuntimeException(ex);
+        }
+    }
+
+    public void connectDatagramSocketTest(int port) {
+        String msg = "Hello";
+        try {
+            InetAddress me = InetAddress.getLocalHost();
+            try (DatagramSocket ds = new DatagramSocket(port, me)) {
+                DatagramPacket dp = new DatagramPacket(msg.getBytes(),
+                        msg.length(), me, port);
+                ds.send(dp);
+            }
+        } catch (IOException ex) {
+            throw new RuntimeException(ex);
+        }
+    }
+
+    public void acceptServerSocketTest(int port) {
+        try {
+            InetAddress me = InetAddress.getLocalHost();
+            try (ServerSocket server = new ServerSocket(port)) {
+                Socket client = new Socket(me, port);
+                server.accept();
+            }
+        } catch (IOException ex) {
+            throw new RuntimeException(ex);
+        }
+    }
+
+    public static void sendDatagramPacketTest(int port) {
+        String msg = "Hello";
+        try {
+            InetAddress group = InetAddress.getByName("229.227.226.221");
+            try (DatagramSocket s = new DatagramSocket(port)) {
+                DatagramPacket hi = new DatagramPacket(msg.getBytes(),
+                        msg.length(), group, port);
+                s.send(hi);
+            }
+        } catch (IOException ex) {
+            throw new RuntimeException(ex);
+        }
+    }
+
+    public void joinGroupMulticastTest(int port) {
+        try {
+            InetAddress group = InetAddress.getByName("229.227.226.221");
+            try (MulticastSocket s = new MulticastSocket(port)) {
+                s.joinGroup(group);
+                s.leaveGroup(group);
+            }
+        } catch (IOException ex) {
+            throw new RuntimeException(ex);
+        }
+    }
+
+    public void listenDatagramSocketTest(int port) {
+        try (DatagramSocket ds = new DatagramSocket(port)) {
+        } catch (IOException ex) {
+            throw new RuntimeException(ex);
+        }
+    }
+
+    public void listenMulticastSocketTest(int port) {
+        try (MulticastSocket ms = new MulticastSocket(port)) {
+        } catch (IOException ex) {
+            throw new RuntimeException(ex);
+        }
+    }
+
+    public void listenServerSocketTest(int port) {
+        try (ServerSocket ms = new ServerSocket(port)) {
+        } catch (IOException ex) {
+            throw new RuntimeException(ex);
+        }
+    }
+
+    private static AccessControlContext getAccessControlContext(Permission... ps) {
+        Permissions perms = new Permissions();
+        for (Permission p : ps) {
+            perms.add(p);
+        }
+        /*
+         *Create an AccessControlContext that consist a single protection domain
+         * with only the permissions calculated above
+         */
+        ProtectionDomain pd = new ProtectionDomain(null, perms);
+        return new AccessControlContext(new ProtectionDomain[]{pd});
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/net/SocketPermission/policy	Mon Oct 20 12:04:12 2014 -0700
@@ -0,0 +1,3 @@
+grant {
+ permission java.security.AllPermission;
+};
\ No newline at end of file
--- a/test/java/nio/channels/AsynchronousSocketChannel/StressLoopback.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/test/java/nio/channels/AsynchronousSocketChannel/StressLoopback.java	Mon Oct 20 12:04:12 2014 -0700
@@ -24,6 +24,8 @@
 /* @test
  * @bug 6834246 6842687
  * @summary Stress test connections through the loopback interface
+ * @run main StressLoopback
+ * @run main/othervm -Djdk.net.useFastTcpLoopback StressLoopback
  */
 
 import java.nio.ByteBuffer;
--- a/test/java/security/cert/CertificateFactory/invalidEncodedCerts/DetectInvalidEncoding.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/test/java/security/cert/CertificateFactory/invalidEncodedCerts/DetectInvalidEncoding.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,27 +23,548 @@
 
 /**
  * @test
- * @bug 4776466
+ * @bug 4776466 8032573
  * @summary check that CertificateFactory rejects invalid encoded X.509 certs
  */
 
 import java.io.*;
+import java.util.Collection;
+import java.util.List;
+import java.util.LinkedList;
+import javax.security.auth.x500.X500Principal;
+import java.security.GeneralSecurityException;
 import java.security.cert.*;
 
 public class DetectInvalidEncoding {
 
+    // Originally found in the test file:
+    // java/security/cert/CertificateFactory/invalidEncodedCerts/invalidcert.pem
+    // The first character of the PEM encoding has been changed from "M" to
+    // "X" to force a failure during decoding.
+    private static final String INVALID_CERT =
+        "-----BEGIN CERTIFICATE-----\n" +
+        "XIICJjCCAdCgAwIBAgIBITANBgkqhkiG9w0BAQQFADCBqTELMAkGA1UEBhMCVVMx\n" +
+        "EzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBGcmFuY2lzY28xFTAT\n" +
+        "BgNVBAoTDEJFQSBXZWJMb2dpYzERMA8GA1UECxMIU2VjdXJpdHkxIzAhBgNVBAMT\n" +
+        "GkRlbW8gQ2VydGlmaWNhdGUgQXV0aG9yaXR5MR4wHAYJKoZIhvcNAQkBFg9zdXBw\n" +
+        "b3J0QGJlYS5jb20wHhcNMDAwNTMwMjEzODAxWhcNMDQwNTEzMjEzODAxWjCBjDEL\n" +
+        "MAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG\n" +
+        "cmFuY2lzY28xFTATBgNVBAoTDEJFQSBXZWJMb2dpYzEZMBcGA1UEAxMQd2VibG9n\n" +
+        "aWMuYmVhLmNvbTEeMBwGCSqGSIb3DQEJARYPc3VwcG9ydEBiZWEuY29tMFwwDQYJ\n" +
+        "KoZIhvcNAQEBBQADSwAwSAJBALdsXEHqKHgs6zj0hU5sXMAUHzoT8kgWXmNkKHXH\n" +
+        "79qbPh6EfdlriW9G/AbRF/pKrCQu7hhllAxREbqTuSlf2EMCAwEAATANBgkqhkiG\n" +
+        "9w0BAQQFAANBACgmqflL5m5LNeJGpWx9aIoABCiuDcpw1fFyegsqGX7CBhffcruS\n" +
+        "1p8h5vkHVbMu1frD1UgGnPlOO/K7Ig/KrsU=\n" +
+        "-----END CERTIFICATE-----";
+
+    // Created with keytool:
+    // keytool -genkeypair -keyalg rsa -keysize 2048 -keystore <KS_FILE>
+    //      -alias root -sigalg SHA256withRSA -dname "CN=Root, O=SomeCompany"
+    //      -validity 730 -ext bc:critical=ca:true
+    //      -ext ku:critical=keyCertSign,cRLSign
+    private static final String SINGLE_ROOT_CERT =
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIIDCjCCAfKgAwIBAgIEDUiw+DANBgkqhkiG9w0BAQsFADAlMRQwEgYDVQQKEwtT\n" +
+        "b21lQ29tcGFueTENMAsGA1UEAxMEUm9vdDAeFw0xNDA4MjgyMTI5MjZaFw0xNjA4\n" +
+        "MjcyMTI5MjZaMCUxFDASBgNVBAoTC1NvbWVDb21wYW55MQ0wCwYDVQQDEwRSb290\n" +
+        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0VFecSNdH6CJhPOSG127\n" +
+        "tuvld4y7GGJ0kQf3Q0b8qgprsXAmn0/bQR+YX7PfS408cFW+q2SWXeY2kC/3chvi\n" +
+        "2syMsGdUJrDzuMbYsbvKPKyuJ2GJskX3mSbLMJj5Tzhg4qmwbzDTFIJ51yGa1Wmh\n" +
+        "i2+4PhltqT0TohvSVJlBrOWNhmvwv5UWsF4e2i04rebDZQoWkmD3MpImZXF/HYre\n" +
+        "9P8NP97vN0xZmh5PySHy2ILXN3ZhTn3tq0YxNSQTaMUfhgoyzWFvZKAnm/tZIh/1\n" +
+        "oswwEQPIZJ25AUTm9r3YPQXl1hsNdLU0asEVYRsgzGSTX5gCuUY+KzhStzisOcUY\n" +
+        "uQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNV\n" +
+        "HQ4EFgQUz1FBNixG/KCgcn6FOWzxP1hujG0wDQYJKoZIhvcNAQELBQADggEBAL60\n" +
+        "ZaNc6eIMbKntGVE/pdxxyKwPdDyAAeEevX23KRWoLbQjHXo5jrfDPhI5k45ztlyU\n" +
+        "+tIQbc81LlCl88I4dIx0fvEbxjNaAYhFNXwwSQBs2CuEAdRK8hodXbRcEeI+G10F\n" +
+        "ARIVs2C7JNm/RhxskCWgj6tFIOGaTZ9gHyvlQUEM18sr5fXZlXTqspZCmz3t5XPi\n" +
+        "5/wYLv6vk7k3G8WzMHbBE0bYI+61cCc8rbMHldtymbwSwiqfKC9y7oPEfRCbzVUe\n" +
+        "fgrKcOyVWDuw0y0hhsQL/oONjPp4uK/bl9B7T84t4+ihxdocWKx6eyhFvOvZH9t2\n" +
+        "kUylb9yBUYStwGExMHg=\n" +
+        "-----END CERTIFICATE-----";
+
+    // Created with keytool:
+    // keytool -genkeypair -keyalg rsa -keysize 2048 -keystore <KS_FILE>
+    //      -alias root -sigalg SHA256withRSA
+    //      -dname "CN=Intermed, O=SomeCompany" -validity 730
+    //      -ext bc:critical=ca:true -ext ku:critical=keyCertSign,cRLSign
+    // keytool -certreq -keystore <KS_FILE> -sigalg SHA256withRSA
+    //      -alias intermed -dname "CN=Intermed, O=SomeCompany"
+    // keytool -gencert -keystore <KS_FILE> -alias intermed
+    //      -sigalg SHA256withRSA -validity 730
+    //      -ext bc:critical=ca:true -ext ku:critical=keyCertSign,cRLSign
+    private static final String INTERMED_CA_CERT =
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIIDLzCCAhegAwIBAgIEIIgOyDANBgkqhkiG9w0BAQsFADAlMRQwEgYDVQQKEwtT\n" +
+        "b21lQ29tcGFueTENMAsGA1UEAxMEUm9vdDAeFw0xNDA4MjgyMjUyNDJaFw0xNjA4\n" +
+        "MDcyMjUyNDJaMCkxFDASBgNVBAoTC1NvbWVDb21wYW55MREwDwYDVQQDEwhJbnRl\n" +
+        "cm1lZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJEecvTWla8kdWx+\n" +
+        "HHu5ryfBpJ95I7V4MEajnmzJVZcwvKhDjlDgABDMuVwFEUUSyeOdbWJF3DLKnyMD\n" +
+        "KTx6/58kuVak3NX2TJ8cmmIlKf1upFbdrEtjYViSnNrApprfO8B3ORdBbO6QDYza\n" +
+        "IkAWdI5GllFnVkb4yhMUBg3zfhglF+bl3D3lVRlp9bCrUZoNRs+mZjhVbcMn22ej\n" +
+        "TfG5Y3VpNM4SN8dFIxPQLLk/aao+cmWEQdbQ0R6ydemRukqrw170olSVLeoGGala\n" +
+        "3D4oJckde8EgNPcghcsdQ6tpGhkpFhmoyzEsuToR7Gq9UT5V2kkqJneiKXqQg4wz\n" +
+        "vMAlUGECAwEAAaNjMGEwHwYDVR0jBBgwFoAUOw+92bevFoJz96pR1DrAkPPUKb0w\n" +
+        "DwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFLbnErBs\n" +
+        "q/Mhci5XElfjjLZp3GRyMA0GCSqGSIb3DQEBCwUAA4IBAQAq8y2DpkSV31IXZ1vr\n" +
+        "/Ye+Nj/2NvBydFeHVRGMAN1LJv6/Q42TCSXbr6cDQ4NWQUtPm90yZBYJSznkbShx\n" +
+        "HOJEE6R8PRJvoUtMm7fJrNtkybTt6jX4j50Lw8gdYB/rgZb4z8ZQZVEo/0zpW4HV\n" +
+        "Gs+q4z8TkdmLR18hl39sUEsxt99AOBk8NtKKVNfBWq9b0QDhRkXfmqhyeXdDsHOV\n" +
+        "8ksulsa7hseheHhdjziEOpQugh8qzSea2kFPrLB53VjWfa4qDzEPaNhahho9piCu\n" +
+        "82XDnOrcEk9KyHWM7sa7vtK7++W+0MXD/p9nkZ6NHrJXweLriU0DXO6ZY3mzNKJK\n" +
+        "435M\n" +
+        "-----END CERTIFICATE-----";
+
+    // Subordinate cert created using keytool, both certs exported to
+    // files individually, then use openssl to place in a PKCS#7:
+    // openssl crl2pkcs7 -nocrl -certfile <INTERMED-CERT-PEM>
+    //      -certfile <ROOT-CERT-PEM> -out <P7-DEST-PEM-FILE>
+    private static final String PKCS7_INTERMED_ROOT_CERTS =
+        "-----BEGIN PKCS7-----\n" +
+        "MIIGbgYJKoZIhvcNAQcCoIIGXzCCBlsCAQExADALBgkqhkiG9w0BBwGgggZBMIID\n" +
+        "LzCCAhegAwIBAgIEIIgOyDANBgkqhkiG9w0BAQsFADAlMRQwEgYDVQQKEwtTb21l\n" +
+        "Q29tcGFueTENMAsGA1UEAxMEUm9vdDAeFw0xNDA4MjgyMjUyNDJaFw0xNjA4MDcy\n" +
+        "MjUyNDJaMCkxFDASBgNVBAoTC1NvbWVDb21wYW55MREwDwYDVQQDEwhJbnRlcm1l\n" +
+        "ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJEecvTWla8kdWx+HHu5\n" +
+        "ryfBpJ95I7V4MEajnmzJVZcwvKhDjlDgABDMuVwFEUUSyeOdbWJF3DLKnyMDKTx6\n" +
+        "/58kuVak3NX2TJ8cmmIlKf1upFbdrEtjYViSnNrApprfO8B3ORdBbO6QDYzaIkAW\n" +
+        "dI5GllFnVkb4yhMUBg3zfhglF+bl3D3lVRlp9bCrUZoNRs+mZjhVbcMn22ejTfG5\n" +
+        "Y3VpNM4SN8dFIxPQLLk/aao+cmWEQdbQ0R6ydemRukqrw170olSVLeoGGala3D4o\n" +
+        "Jckde8EgNPcghcsdQ6tpGhkpFhmoyzEsuToR7Gq9UT5V2kkqJneiKXqQg4wzvMAl\n" +
+        "UGECAwEAAaNjMGEwHwYDVR0jBBgwFoAUOw+92bevFoJz96pR1DrAkPPUKb0wDwYD\n" +
+        "VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFLbnErBsq/Mh\n" +
+        "ci5XElfjjLZp3GRyMA0GCSqGSIb3DQEBCwUAA4IBAQAq8y2DpkSV31IXZ1vr/Ye+\n" +
+        "Nj/2NvBydFeHVRGMAN1LJv6/Q42TCSXbr6cDQ4NWQUtPm90yZBYJSznkbShxHOJE\n" +
+        "E6R8PRJvoUtMm7fJrNtkybTt6jX4j50Lw8gdYB/rgZb4z8ZQZVEo/0zpW4HVGs+q\n" +
+        "4z8TkdmLR18hl39sUEsxt99AOBk8NtKKVNfBWq9b0QDhRkXfmqhyeXdDsHOV8ksu\n" +
+        "lsa7hseheHhdjziEOpQugh8qzSea2kFPrLB53VjWfa4qDzEPaNhahho9piCu82XD\n" +
+        "nOrcEk9KyHWM7sa7vtK7++W+0MXD/p9nkZ6NHrJXweLriU0DXO6ZY3mzNKJK435M\n" +
+        "MIIDCjCCAfKgAwIBAgIEdffjKTANBgkqhkiG9w0BAQsFADAlMRQwEgYDVQQKEwtT\n" +
+        "b21lQ29tcGFueTENMAsGA1UEAxMEUm9vdDAeFw0xNDA4MjgyMjQ2MzZaFw0xNjA4\n" +
+        "MjcyMjQ2MzZaMCUxFDASBgNVBAoTC1NvbWVDb21wYW55MQ0wCwYDVQQDEwRSb290\n" +
+        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhnXc8Avv54Gk2xjVa2yA\n" +
+        "lBL/Cug1nyvKl5wqmN+foT6cMOX6bneCkJOJ4lSbch3gvl4ctlX/9hm3pB/+HhSr\n" +
+        "em2NcLQrLEq8l9Ar4RnqfoXQR4Uy+4P6wj9OcVV7e/v/+ZPnStOoEAtb5nAwsR2b\n" +
+        "hOC/tIFNwflrsmsmtMSoOiNftpYLFF4eOAdpDrXYMrqNu6ZxZsOQ7WZl4SsVOx1N\n" +
+        "/IINXwBLyoHJDzLZ0iJEV0O6mh846s0n6QXeK1P5d0uLcoZaZ1k8Q4sRcdoLA6rS\n" +
+        "e1WffipBFMvIuoDIigkHZIKVYRLG828rO+PFnRah0ybybkVsN6s3oLxfhswZDvut\n" +
+        "OwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNV\n" +
+        "HQ4EFgQUOw+92bevFoJz96pR1DrAkPPUKb0wDQYJKoZIhvcNAQELBQADggEBACBN\n" +
+        "wEaV70FKKBINHtNwesd7TB6fgSaVgDZOO08aseHbXnm7AUhtDV3P5rQR2AsKtbg4\n" +
+        "COhlKw2/Ki18D4DfdCccFKFTRZBjqj2PxNmn6C68l1/bT4PuUXuM7rW++53RcOA7\n" +
+        "TbgLuzA25kSz7XinRvR8L4VwHtppu5tSYEthMIMgLZLGGV9r7kBfpY8lXdxQM8vb\n" +
+        "xZUIysasvVtVUFPOTV6g2dfn8QCoqLOmxyzTLdXe4M6acP6f7lmhgr3LMqDtB6K9\n" +
+        "pN+OImr77zNdZ+jTB+5e9a8gAvc5ZfG7Nk5RfwUatYTAFZ6Uggy2cKmIRpXCia18\n" +
+        "If78mc7goS1+lHkGCs2hADEA\n" +
+        "-----END PKCS7-----";
+
+    // Empty PKCS#7 in DER form can be created with openssl:
+    // openssl crl2pkcs7 -nocrl -outform DER
+    private static final byte[] PKCS7_BER_EMPTY = {
+          48,   39,    6,    9,   42, -122,   72, -122,
+          -9,   13,    1,    7,    2,  -96,   26,   48,
+          24,    2,    1,    1,   49,    0,   48,   11,
+           6,    9,   42, -122,   72, -122,   -9,   13,
+           1,    7,    1,  -96,    0,  -95,    0,   49,
+           0
+    };
+
+    private static final String JTEST_ROOT_CRL =
+        "-----BEGIN X509 CRL-----\n" +
+        "MIICoTCBigIBATANBgkqhkiG9w0BAQsFADA1MQ4wDAYDVQQKEwVKVGVzdDELMAkG\n" +
+        "A1UECxMCSVQxFjAUBgNVBAMTDUpUZXN0IFJvb3QgQ0EXDTE0MDkwNDE4NDIyMVqg\n" +
+        "MDAuMB8GA1UdIwQYMBaAFO6bllCV6kctH77MfqAtefNeRdsmMAsGA1UdFAQEAgIA\n" +
+        "jjANBgkqhkiG9w0BAQsFAAOCAgEAmp8ihtiRthknDC+VzehmlQw5u8MftMZYQYk5\n" +
+        "EI04SwyzY9JTL8QHb4u7fXjnZAyN89aYPypI5OSyDsyyGP/JDNsBt2Um/fl0aaCl\n" +
+        "Z4Np6x+dB9+oIU1XY7y2+uyQUC5MHivQ5ddbGPoAvK/msbugTGAjHvZpM+l0okiV\n" +
+        "3SofDrii5BSosFEkXfkf2oG9ZLO3YamsFMEZaOj/eWDyGhTyJMGsq2/8NeTF21Tp\n" +
+        "YkeDcTHqR5KHoYXjOIaS7NjmErm+uDpKH9Lq+JUcYrbUhmjnq5z04EsPF2F2L7Vb\n" +
+        "THI+awQAUQit16lXGuz7fFRZi2vPyiaRP5n2QT5D+ac1dAs+oWLDJw6Tf2v9KVTe\n" +
+        "OmW62yd6zQqCwBg+n57UcNu3sv/Sq3t7iRuN0AmWlIhu659POPQv7Np6bEo6dIpp\n" +
+        "u7Ze6D2KPtM177ETHYlCx2a3g9VEZYKrVhQ2749St0Cp5szVq691jFZAWYOzcfEO\n" +
+        "XfK1y25pmlBjvhNIIVRlU+T5rjNb8GaleYKVYnKOcv700K32QxFzcPf7nbNKwW99\n" +
+        "tcaNHFNP+LW/XP8I3CJ8toXLLcOITKVwMA+0GlO5eL7eX5POc+vE9+7IzGuybmU4\n" +
+        "uslxoLdJ0NSZWpYmf6a6qrJ67cj5i3706H+eBsWQcShfSYreh+TyWQaGk+fkEiUV\n" +
+        "iy4QdJ0=\n" +
+        "-----END X509 CRL-----";
+
+    private static final String JTEST_INTERMED_CRL =
+        "-----BEGIN X509 CRL-----\n" +
+        "MIICzzCBuAIBATANBgkqhkiG9w0BAQsFADA/MQ4wDAYDVQQKEwVKVGVzdDELMAkG\n" +
+        "A1UECxMCSVQxIDAeBgNVBAMTF0pUZXN0IEludGVybWVkaWF0ZSBDQSAxFw0xNDA5\n" +
+        "MDQyMjE2NTRaMCIwIAIBBhcNMTQwOTA0MjIxNjU0WjAMMAoGA1UdFQQDCgEFoDAw\n" +
+        "LjAfBgNVHSMEGDAWgBSvRdjbkSMJ3A7s5H6EWghQ+lkw/zALBgNVHRQEBAICAJsw\n" +
+        "DQYJKoZIhvcNAQELBQADggIBALJmikMwil8oywhenoO8o9xxCOIU0xrt3KdfiSXw\n" +
+        "8MtQXZHT9d1C6tlLAsYkWAfmfTvM2OU6wquFCLLsFmDZszbbCqmn4JhYBSKQMqlm\n" +
+        "IHnsiOFPvITW2FU08fWNLM+FtQzPnTFmx/CJo+wfGpq5tZMIbsccsCJ5uvZVAWGh\n" +
+        "0KbPmYcJG/O384+kzr/2H2IaoZoMMABec5c5FEF/tpp8jawzY+0VFyaVrumKWdan\n" +
+        "+3OvRQxT1wLxfNi2vdxB2rmNPo423qanXZAoVv260um3LYlmXBNK1jwQ9lp78jkT\n" +
+        "B7zMVa4hOUWVxdWc/LE6fUYgPsNqZd+hWy/PolIRp5TS21B5hkc5K87LT59GkexK\n" +
+        "vNVKQennOLGtH+Q7htK4UeY4Gm/W7UydOQ0k7hZzyfMDkCfLfNfK0l63qKwUku36\n" +
+        "UdeI1LXqulPEvb/d7rRAAM9p5Sm+RsECj2bcrZBMdIGXcSo26A5tzZpTEC79i4S1\n" +
+        "yxYIooeBnouUkDJ9+VBsJTSKY5fpU8JSkQPRyHKt+trGAkBt2Ka5MqrHtITzQ1vP\n" +
+        "5q4tNr45JGEXllH83NlBpWURfsdtkDHa3lxTD/pkrywOCyzz7wQ22D8Kul7EN8nT\n" +
+        "7LDbN+O3G9GHICxvWlJHp6HMsqGTuH1MIUR+5uZFOJa1S0IzorUIEieLncDUPgzO\n" +
+        "M4JA\n" +
+        "-----END X509 CRL-----";
+
+    // PKCS#7 CRL Set containing JTEST root and intermediate CRLs
+    private static final String PKCS7_CRL_SET =
+        "-----BEGIN PKCS7-----\n" +
+        "MIIFpQYJKoZIhvcNAQcCoIIFljCCBZICAQExADALBgkqhkiG9w0BBwGgAKGCBXgw\n" +
+        "ggKhMIGKAgEBMA0GCSqGSIb3DQEBCwUAMDUxDjAMBgNVBAoTBUpUZXN0MQswCQYD\n" +
+        "VQQLEwJJVDEWMBQGA1UEAxMNSlRlc3QgUm9vdCBDQRcNMTQwOTA0MTg0MjIxWqAw\n" +
+        "MC4wHwYDVR0jBBgwFoAU7puWUJXqRy0fvsx+oC15815F2yYwCwYDVR0UBAQCAgCO\n" +
+        "MA0GCSqGSIb3DQEBCwUAA4ICAQCanyKG2JG2GScML5XN6GaVDDm7wx+0xlhBiTkQ\n" +
+        "jThLDLNj0lMvxAdvi7t9eOdkDI3z1pg/Kkjk5LIOzLIY/8kM2wG3ZSb9+XRpoKVn\n" +
+        "g2nrH50H36ghTVdjvLb67JBQLkweK9Dl11sY+gC8r+axu6BMYCMe9mkz6XSiSJXd\n" +
+        "Kh8OuKLkFKiwUSRd+R/agb1ks7dhqawUwRlo6P95YPIaFPIkwayrb/w15MXbVOli\n" +
+        "R4NxMepHkoehheM4hpLs2OYSub64Okof0ur4lRxittSGaOernPTgSw8XYXYvtVtM\n" +
+        "cj5rBABRCK3XqVca7Pt8VFmLa8/KJpE/mfZBPkP5pzV0Cz6hYsMnDpN/a/0pVN46\n" +
+        "ZbrbJ3rNCoLAGD6fntRw27ey/9Kre3uJG43QCZaUiG7rn0849C/s2npsSjp0imm7\n" +
+        "tl7oPYo+0zXvsRMdiULHZreD1URlgqtWFDbvj1K3QKnmzNWrr3WMVkBZg7Nx8Q5d\n" +
+        "8rXLbmmaUGO+E0ghVGVT5PmuM1vwZqV5gpVico5y/vTQrfZDEXNw9/uds0rBb321\n" +
+        "xo0cU0/4tb9c/wjcIny2hcstw4hMpXAwD7QaU7l4vt5fk85z68T37sjMa7JuZTi6\n" +
+        "yXGgt0nQ1JlaliZ/prqqsnrtyPmLfvTof54GxZBxKF9Jit6H5PJZBoaT5+QSJRWL\n" +
+        "LhB0nTCCAs8wgbgCAQEwDQYJKoZIhvcNAQELBQAwPzEOMAwGA1UEChMFSlRlc3Qx\n" +
+        "CzAJBgNVBAsTAklUMSAwHgYDVQQDExdKVGVzdCBJbnRlcm1lZGlhdGUgQ0EgMRcN\n" +
+        "MTQwOTA0MjIxNjU0WjAiMCACAQYXDTE0MDkwNDIyMTY1NFowDDAKBgNVHRUEAwoB\n" +
+        "BaAwMC4wHwYDVR0jBBgwFoAUr0XY25EjCdwO7OR+hFoIUPpZMP8wCwYDVR0UBAQC\n" +
+        "AgCbMA0GCSqGSIb3DQEBCwUAA4ICAQCyZopDMIpfKMsIXp6DvKPccQjiFNMa7dyn\n" +
+        "X4kl8PDLUF2R0/XdQurZSwLGJFgH5n07zNjlOsKrhQiy7BZg2bM22wqpp+CYWAUi\n" +
+        "kDKpZiB57IjhT7yE1thVNPH1jSzPhbUMz50xZsfwiaPsHxqaubWTCG7HHLAiebr2\n" +
+        "VQFhodCmz5mHCRvzt/OPpM6/9h9iGqGaDDAAXnOXORRBf7aafI2sM2PtFRcmla7p\n" +
+        "ilnWp/tzr0UMU9cC8XzYtr3cQdq5jT6ONt6mp12QKFb9utLpty2JZlwTStY8EPZa\n" +
+        "e/I5Ewe8zFWuITlFlcXVnPyxOn1GID7DamXfoVsvz6JSEaeU0ttQeYZHOSvOy0+f\n" +
+        "RpHsSrzVSkHp5zixrR/kO4bSuFHmOBpv1u1MnTkNJO4Wc8nzA5Any3zXytJet6is\n" +
+        "FJLt+lHXiNS16rpTxL2/3e60QADPaeUpvkbBAo9m3K2QTHSBl3EqNugObc2aUxAu\n" +
+        "/YuEtcsWCKKHgZ6LlJAyfflQbCU0imOX6VPCUpED0chyrfraxgJAbdimuTKqx7SE\n" +
+        "80Nbz+auLTa+OSRhF5ZR/NzZQaVlEX7HbZAx2t5cUw/6ZK8sDgss8+8ENtg/Crpe\n" +
+        "xDfJ0+yw2zfjtxvRhyAsb1pSR6ehzLKhk7h9TCFEfubmRTiWtUtCM6K1CBIni53A\n" +
+        "1D4MzjOCQDEA\n" +
+        "-----END PKCS7-----";
+
     public static void main(String[] args) throws Exception {
         CertificateFactory cf = CertificateFactory.getInstance("X.509");
-        File f = new File
-            (System.getProperty("test.src", "."), "invalidcert.pem");
-        InputStream inStream = new FileInputStream(f);
-        try {
-            X509Certificate cert =
-                (X509Certificate) cf.generateCertificate(inStream);
-        } catch (CertificateParsingException ce) {
-            return;
+        List<DecodeTest> validTests = new LinkedList<>();
+        List<DecodeTest> invalidTests = new LinkedList<>();
+
+        // Load up positive test cases (for sanity checks)
+        StringBuilder sb = new StringBuilder();
+
+        validTests.add(new GenMultiCertTest("Single, valid certificate",
+                    SINGLE_ROOT_CERT.getBytes(), null,
+                    new X500Principal("CN=Root, O=SomeCompany")));
+        validTests.add(new GenMultiCertTest("PEM-encoded PKCS#7 chain",
+                    PKCS7_INTERMED_ROOT_CERTS.getBytes(), null,
+                    new X500Principal("CN=Intermed, O=SomeCompany"),
+                    new X500Principal("CN=Root, O=SomeCompany")));
+        validTests.add(new GenMultiCertTest("Two PEM-encoded X509 certs",
+                    (INTERMED_CA_CERT + "\n" + SINGLE_ROOT_CERT).getBytes(),
+                    null,
+                    new X500Principal("CN=Intermed, O=SomeCompany"),
+                    new X500Principal("CN=Root, O=SomeCompany")));
+        validTests.add(new GenMultiCertTest("Empty data", new byte[0], null));
+
+        sb.append("Certificate 1: CN=Root, O=SomeCompany\n");
+        sb.append(SINGLE_ROOT_CERT).append("\n");
+        sb.append("Certificate 2: CN=Intermed, O=SomeCompany\n");
+        sb.append(INTERMED_CA_CERT).append("\n");
+        sb.append("Extra trailing data\n");
+        validTests.add(new GenMultiCertTest(
+                    "Two PEM-encoded certs with leading/trailing " +
+                    "text data around each.", sb.toString().getBytes(), null,
+                    new X500Principal("CN=Root, O=SomeCompany"),
+                    new X500Principal("CN=Intermed, O=SomeCompany")));
+        validTests.add(new GenMultiCertTest(
+                    "BER-encoded PKCS#7 with empty certificates segment",
+                    PKCS7_BER_EMPTY, null));
+        validTests.add(new GenMultiCRLTest(
+                    "CRL with leading and trailing text data",
+                    ("This is a CRL\n" + JTEST_ROOT_CRL +
+                     "\nSee? Told you so\n\n").getBytes(), null,
+                    new X500Principal("CN=JTest Root CA,OU=IT,O=JTest")));
+        validTests.add(new GenMultiCRLTest(
+                    "Two CRLs, one after the other with leading/trailing text",
+                    ("This is a CRL\n" + JTEST_ROOT_CRL +
+                     "\nAnd this is another CRL\n" + JTEST_INTERMED_CRL +
+                     "\nAnd this is trailing text\n").getBytes(), null,
+                    new X500Principal("CN=JTest Root CA,OU=IT,O=JTest"),
+                    new X500Principal(
+                        "CN=JTest Intermediate CA 1,OU=IT,O=JTest")));
+        validTests.add(new GenMultiCRLTest("Two CRLs in a PKCS#7 CRL set",
+                PKCS7_CRL_SET.getBytes(), null,
+                new X500Principal("CN=JTest Root CA,OU=IT,O=JTest"),
+                new X500Principal("CN=JTest Intermediate CA 1,OU=IT,O=JTest")));
+
+        // Load up all test cases where we expect failures
+        invalidTests.add(new GenSingleCertTest("Invalid PEM encoding",
+                    INVALID_CERT.getBytes(),
+                    new CertificateParsingException()));
+        invalidTests.add(new GenMultiCertTest("Invalid PEM encoding",
+                    INVALID_CERT.getBytes(),
+                    new CertificateParsingException()));
+        invalidTests.add(new GenMultiCertTest(
+                    "Two cert sequence, one valid and one invalid",
+                    (INTERMED_CA_CERT + "\n" + INVALID_CERT).getBytes(),
+                    new CertificateParsingException()));
+        invalidTests.add(new GenMultiCertTest("Non-certificate text",
+                    "This is not a certificate".getBytes(),
+                    new CertificateException()));
+        invalidTests.add(new GenMultiCertTest(
+                    "Non-certificate text with partial PEM header (4 hyphens)",
+                    "----This is not a valid x509 certificate".getBytes(),
+                    new CertificateException()));
+        invalidTests.add(new GenMultiCertTest(
+                    "Leading non-certificate text plus valid PEM header, " +
+                    "but not on new line",
+                    "This is not valid -----BEGIN CERTIFICATE-----".getBytes(),
+                    new CertificateException()));
+        byte[] emptyCString = {0};
+        invalidTests.add(new GenMultiCertTest("Empty C-style string",
+                    emptyCString, new CertificateException()));
+        invalidTests.add(new GenMultiCRLTest("Non-CRL text",
+                    "This is not a CRL".getBytes(), new CRLException()));
+        invalidTests.add(new GenMultiCRLTest("Valid headers, but not a CRL",
+                    INTERMED_CA_CERT.getBytes(), new CRLException()));
+
+        System.out.println("===== Valid Tests =====");
+        for (DecodeTest dt : validTests) {
+            dt.passTest();
         }
-        throw new Exception("CertificateFactory.generateCertificate() did not "
-            + "throw CertificateParsingException on invalid X.509 cert data");
+        System.out.print("\n");
+
+        System.out.println("===== Invalid Tests =====");
+        for (DecodeTest dt : invalidTests) {
+            dt.failTest();
+        }
+    }
+
+    public static abstract class DecodeTest {
+        protected String testName;
+        protected byte[] testData;
+        protected Throwable expectedException;
+        protected X500Principal[] principals;
+        protected CertificateFactory cf;
+
+        /**
+         * Construct a DecodeTest
+         *
+         * @param name The test name
+         * @param input A byte array consisting of the input for this test
+         * @param failType An exception whose class should match the expected
+         *        exception that will be thrown when this test is run
+         * @param princs Zero of more X500Principals which will be used
+         *        to compare the output in a success case.
+         */
+        DecodeTest(String name, byte[] input, Throwable failType,
+                X500Principal... princs) throws CertificateException {
+            testName = name;
+            testData = input.clone();
+            expectedException = failType;
+            principals = princs;
+            cf = CertificateFactory.getInstance("X.509");
+        }
+
+        public abstract void passTest() throws GeneralSecurityException;
+
+        public abstract void failTest() throws GeneralSecurityException;
+    }
+
+    public static class GenMultiCertTest extends DecodeTest {
+        public GenMultiCertTest(String name, byte[] input, Throwable failType,
+                X500Principal... princs) throws CertificateException {
+            super(name, input, failType, princs);
+        }
+
+        @Override
+        public void passTest() throws GeneralSecurityException {
+            Collection<? extends Certificate> certs;
+
+            System.out.println("generateCertificates(): " + testName);
+            certs = cf.generateCertificates(new ByteArrayInputStream(testData));
+
+            // Walk the certs Collection and do a comparison of subject names
+            int i = 0;
+            if (certs.size() == principals.length) {
+                for (Certificate crt : certs) {
+                    X509Certificate xc = (X509Certificate)crt;
+                    if (!xc.getSubjectX500Principal().equals(
+                                principals[i])) {
+                        throw new RuntimeException("Name mismatch: " +
+                                "cert: " + xc.getSubjectX500Principal() +
+                                ", expected: " + principals[i]);
+                    }
+                    i++;
+                }
+            } else {
+                throw new RuntimeException("Size mismatch: certs = " +
+                        certs.size() + ", expected = " +
+                        principals.length);
+            }
+        }
+
+        @Override
+        public void failTest() throws GeneralSecurityException {
+            Throwable caughtException = null;
+            Collection<? extends Certificate> certs = null;
+
+            System.out.println("generateCertificates(): " + testName);
+            if (expectedException == null) {
+                throw new RuntimeException("failTest requires non-null " +
+                        "expectedException");
+            }
+
+            try {
+                certs =
+                    cf.generateCertificates(new ByteArrayInputStream(testData));
+            } catch (CertificateException ce) {
+                caughtException = ce;
+            }
+
+            if (caughtException != null) {
+                // It has to be the right kind of exception though...
+                if (!caughtException.getClass().equals(
+                        expectedException.getClass())) {
+                    System.err.println("Unexpected exception thrown. " +
+                            "Received: " + caughtException + ", Expected: " +
+                            expectedException.getClass());
+                    throw new RuntimeException(caughtException);
+                }
+            } else {
+                // For a failure test, we'd expect some kind of exception
+                // to be thrown.
+                throw new RuntimeException("Failed to catch expected " +
+                        "exception " + expectedException.getClass());
+            }
+        }
+    }
+
+    public static class GenSingleCertTest extends DecodeTest {
+        public GenSingleCertTest(String name, byte[] input, Throwable failType,
+                X500Principal... princs) throws CertificateException {
+            super(name, input, failType, princs);
+        }
+
+        @Override
+        public void passTest() throws GeneralSecurityException {
+            X509Certificate cert;
+
+            System.out.println("generateCertificate(): " + testName);
+            cert = (X509Certificate)cf.generateCertificate(
+                    new ByteArrayInputStream(testData));
+
+            // Compare the cert's subject name against the expected value
+            // provided in the test.  If multiple X500Principals were provided
+            // just use the first one as the expected value.
+            if (!cert.getSubjectX500Principal().equals(principals[0])) {
+                throw new RuntimeException("Name mismatch: " +
+                        "cert: " + cert.getSubjectX500Principal() +
+                        ", expected: " + principals[0]);
+            }
+        }
+
+        @Override
+        public void failTest() throws GeneralSecurityException {
+            Throwable caughtException = null;
+            X509Certificate cert = null;
+            System.out.println("generateCertificate(): " + testName);
+
+            if (expectedException == null) {
+                throw new RuntimeException("failTest requires non-null " +
+                        "expectedException");
+            }
+
+            try {
+                cert = (X509Certificate)cf.generateCertificate(
+                        new ByteArrayInputStream(testData));
+            } catch (CertificateException e) {
+                caughtException = e;
+            }
+
+            if (caughtException != null) {
+                // It has to be the right kind of exception though...
+                if (!caughtException.getClass().equals(
+                        expectedException.getClass())) {
+                    System.err.println("Unexpected exception thrown. " +
+                            "Received: " + caughtException + ", Expected: " +
+                            expectedException.getClass());
+                    throw new RuntimeException(caughtException);
+                }
+            } else {
+                // For a failure test, we'd expect some kind of exception
+                // to be thrown.
+                throw new RuntimeException("Failed to catch expected " +
+                        "exception " + expectedException.getClass());
+            }
+        }
+    }
+
+    public static class GenMultiCRLTest extends DecodeTest {
+        public GenMultiCRLTest(String name, byte[] input, Throwable failType,
+                X500Principal... princs) throws CertificateException {
+            super(name, input, failType, princs);
+        }
+
+        @Override
+        public void passTest() throws GeneralSecurityException {
+            Collection<? extends CRL> crls;
+
+            System.out.println("generateCRLs(): " + testName);
+            crls = cf.generateCRLs(new ByteArrayInputStream(testData));
+
+            // Walk the crls Collection and do a comparison of issuer names
+            int i = 0;
+            if (crls.size() == principals.length) {
+                for (CRL revlist : crls) {
+                    X509CRL xc = (X509CRL)revlist;
+                    if (!xc.getIssuerX500Principal().equals(principals[i])) {
+                        throw new RuntimeException("Name mismatch: " +
+                                "CRL: " + xc.getIssuerX500Principal() +
+                                ", expected: " + principals[i]);
+                    }
+                    i++;
+                }
+            } else {
+                throw new RuntimeException("Size mismatch: crls = " +
+                        crls.size() + ", expected = " +
+                        principals.length);
+            }
+        }
+
+        @Override
+        public void failTest() throws GeneralSecurityException {
+            Throwable caughtException = null;
+            Collection<? extends CRL> crls = null;
+
+            System.out.println("generateCRLs(): " + testName);
+            if (expectedException == null) {
+                throw new RuntimeException("failTest requires non-null " +
+                        "expectedException");
+            }
+
+            try {
+                crls =
+                    cf.generateCRLs(new ByteArrayInputStream(testData));
+            } catch (CRLException e) {
+                caughtException = e;
+            }
+
+            if (caughtException != null) {
+                // It has to be the right kind of exception though...
+                if (!caughtException.getClass().equals(
+                        expectedException.getClass())) {
+                    System.err.println("Unexpected exception thrown. " +
+                            "Received: " + caughtException + ", Expected: " +
+                            expectedException.getClass());
+                    throw new RuntimeException(caughtException);
+                }
+            } else {
+                // For a failure test, we'd expect some kind of exception
+                // to be thrown.
+                throw new RuntimeException("Failed to catch expected " +
+                        "exception " + expectedException.getClass());
+            }
+        }
     }
 }
--- a/test/java/security/cert/CertificateFactory/invalidEncodedCerts/invalidcert.pem	Mon Oct 20 11:22:58 2014 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,14 +0,0 @@
------BEGIN CERTIFICATE-----
-XIICJjCCAdCgAwIBAgIBITANBgkqhkiG9w0BAQQFADCBqTELMAkGA1UEBhMCVVMx
-EzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBGcmFuY2lzY28xFTAT
-BgNVBAoTDEJFQSBXZWJMb2dpYzERMA8GA1UECxMIU2VjdXJpdHkxIzAhBgNVBAMT
-GkRlbW8gQ2VydGlmaWNhdGUgQXV0aG9yaXR5MR4wHAYJKoZIhvcNAQkBFg9zdXBw
-b3J0QGJlYS5jb20wHhcNMDAwNTMwMjEzODAxWhcNMDQwNTEzMjEzODAxWjCBjDEL
-MAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG
-cmFuY2lzY28xFTATBgNVBAoTDEJFQSBXZWJMb2dpYzEZMBcGA1UEAxMQd2VibG9n
-aWMuYmVhLmNvbTEeMBwGCSqGSIb3DQEJARYPc3VwcG9ydEBiZWEuY29tMFwwDQYJ
-KoZIhvcNAQEBBQADSwAwSAJBALdsXEHqKHgs6zj0hU5sXMAUHzoT8kgWXmNkKHXH
-79qbPh6EfdlriW9G/AbRF/pKrCQu7hhllAxREbqTuSlf2EMCAwEAATANBgkqhkiG
-9w0BAQQFAANBACgmqflL5m5LNeJGpWx9aIoABCiuDcpw1fFyegsqGX7CBhffcruS
-1p8h5vkHVbMu1frD1UgGnPlOO/K7Ig/KrsU=
------END CERTIFICATE-----
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/naming/spi/providers/InitialContextTest.java	Mon Oct 20 12:04:12 2014 -0700
@@ -0,0 +1,372 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import javax.naming.Context;
+import java.io.*;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.*;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static java.lang.String.format;
+import static java.util.Arrays.asList;
+import static java.util.Collections.singleton;
+import static java.util.Collections.singletonMap;
+
+/*
+ * @test
+ * @bug 8044627
+ * @summary Examines different ways JNDI providers can hook up themselves and
+ *          become available. Each case mimics the most straightforward way of
+ *          executing scenarios.
+ */
+public class InitialContextTest {
+
+    public static void main(String[] args) throws Throwable {
+        unknownInitialContextFactory();
+        initialContextFactoryInAJar();
+        initialContextFactoryAsService();
+    }
+
+    private static void unknownInitialContextFactory() throws Throwable {
+
+        // This is a parameter of this test case, it should work for any value
+        // of it, provided a class with this FQN is not available in a runtime.
+        // So pick any name you like.
+        String factoryClassFqn =
+                "net.java.openjdk.test.UnknownInitialContextFactory";
+
+        Path tmp = Files.createDirectory(Paths.get("InitialContextTest-1"));
+
+        Path src = templatesHome().resolve("test.template");
+        Path dst = tmp.resolve("Test.java");
+        Files.copy(src, dst);
+
+        javac(tmp, dst);
+
+        Path build = Files.createDirectory(tmp.resolve("build"));
+        Files.copy(tmp.resolve("Test.class"), build.resolve("Test.class"));
+
+        Map<String, String> props
+                = singletonMap(Context.INITIAL_CONTEXT_FACTORY, factoryClassFqn);
+
+        Result r = java(props, singleton(build), "Test");
+
+        if (r.exitValue == 0 || !r.output.startsWith(
+                stackTraceStringForClassNotFound(factoryClassFqn))) {
+            throw new RuntimeException(
+                    "Expected a different kind of failure: " + r.output);
+        }
+    }
+
+    private static String stackTraceStringForClassNotFound(String fqn) {
+        return String.format(
+                "Exception in thread \"main\" javax.naming.NoInitialContextException: "
+                        + "Cannot instantiate class: %s "
+                        + "[Root exception is java.lang.ClassNotFoundException: %s]",
+                fqn, fqn);
+    }
+
+    private static void initialContextFactoryInAJar() throws Throwable {
+
+        String factoryClassFqn =
+                "net.java.openjdk.test.DummyInitialContextFactory";
+
+        Path tmp = Files.createDirectory(Paths.get("InitialContextTest-2"));
+
+        Path src = templatesHome().resolve("test.template");
+        Path dst = tmp.resolve("Test.java");
+        Files.copy(src, dst);
+
+        Path dst1 = createFactoryFrom(templatesHome().resolve("factory.template"),
+                factoryClassFqn, tmp);
+
+        javac(tmp, dst);
+        Path explodedJar = Files.createDirectory(tmp.resolve("exploded-jar"));
+        javac(explodedJar, dst1);
+        jar(tmp.resolve("test.jar"), explodedJar);
+
+        Path build = Files.createDirectory(tmp.resolve("build"));
+        Files.copy(tmp.resolve("Test.class"), build.resolve("Test.class"));
+        Files.copy(tmp.resolve("test.jar"), build.resolve("test.jar"));
+
+        Map<String, String> props
+                = singletonMap(Context.INITIAL_CONTEXT_FACTORY, factoryClassFqn);
+
+        Result r = java(props, asList(build.resolve("test.jar"), build), "Test");
+
+        if (r.exitValue != 0 || !r.output.isEmpty())
+            throw new RuntimeException(r.output);
+    }
+
+
+    private static Path createFactoryFrom(Path srcTemplate,
+                                          String factoryFqn,
+                                          Path dstFolder) throws IOException {
+
+        String factorySimpleName, packageName;
+        int i = factoryFqn.lastIndexOf('.');
+        if (i < 0) {
+            packageName = "";
+            factorySimpleName = factoryFqn;
+        } else {
+            packageName = factoryFqn.substring(0, i);
+            factorySimpleName = factoryFqn.substring(i + 1);
+        }
+
+        Path result = dstFolder.resolve(factorySimpleName + ".java");
+        File dst = result.toFile();
+        File src = srcTemplate.toFile();
+        try (BufferedReader r = new BufferedReader(new FileReader(src));
+             BufferedWriter w = new BufferedWriter(new FileWriter(dst))) {
+
+            List<String> lines = processTemplate(packageName, factorySimpleName,
+                    r.lines()).collect(Collectors.toList());
+
+            Iterator<String> it = lines.iterator();
+            if (it.hasNext())
+                w.write(it.next());
+            while (it.hasNext()) {
+                w.newLine();
+                w.write(it.next());
+            }
+        }
+        return result;
+    }
+
+    private static Stream<String> processTemplate(String packageName,
+                                                  String factorySimpleName,
+                                                  Stream<String> lines) {
+        Function<String, String> pckg;
+
+        if (packageName.isEmpty()) {
+            pckg = s -> s.contains("$package") ? "" : s;
+        } else {
+            pckg = s -> s.replaceAll("\\$package", packageName);
+        }
+
+        Function<String, String> factory
+                = s -> s.replaceAll("\\$factoryName", factorySimpleName);
+
+        return lines.map(pckg).map(factory);
+    }
+
+    private static void initialContextFactoryAsService() throws Throwable {
+
+        String factoryClassFqn =
+                "net.java.openjdk.test.BrokenInitialContextFactory";
+
+        Path tmp = Files.createDirectory(Paths.get("InitialContextTest-3"));
+
+        Path src = templatesHome().resolve("test.template");
+        Path dst = tmp.resolve("Test.java");
+        Files.copy(src, dst);
+
+        Path dst1 = createFactoryFrom(templatesHome().resolve("broken_factory.template"),
+                factoryClassFqn, tmp);
+
+        javac(tmp, dst);
+
+        Path explodedJar = Files.createDirectory(tmp.resolve("exploded-jar"));
+        Path services = Files.createDirectories(explodedJar.resolve("META-INF")
+                .resolve("services"));
+
+        Path s = services.resolve("javax.naming.spi.InitialContextFactory");
+        FileWriter fw = new FileWriter(s.toFile());
+        try {
+            fw.write(factoryClassFqn);
+        } finally {
+            fw.close();
+        }
+
+        javac(explodedJar, dst1);
+        jar(tmp.resolve("test.jar"), explodedJar);
+
+        Path build = Files.createDirectory(tmp.resolve("build"));
+        Files.copy(tmp.resolve("Test.class"), build.resolve("Test.class"));
+        Files.copy(tmp.resolve("test.jar"), build.resolve("test.jar"));
+
+        Map<String, String> props = new HashMap<>();
+        props.put("java.ext.dirs", build.toString());
+        props.put(Context.INITIAL_CONTEXT_FACTORY, factoryClassFqn);
+
+        Result r = java(props, singleton(build), "Test");
+
+        if (r.exitValue == 0 || !verifyOutput(r.output, factoryClassFqn))
+            throw new RuntimeException(r.output);
+    }
+
+    // IMO, that's the easiest way that gives you a fair amount of confidence in
+    // that j.u.ServiceLoader is loading a factory rather than Class.forName
+    private static boolean verifyOutput(String output, String fqn) {
+        String s1 = String.format(
+                "Exception in thread \"main\" javax.naming.NoInitialContextException: "
+                        + "Cannot load initial context factory '%s' "
+                        + "[Root exception is java.util.ServiceConfigurationError: "
+                        + "javax.naming.spi.InitialContextFactory: "
+                        + "Provider %s could not be instantiated]", fqn, fqn);
+
+        String s2 = String.format("Caused by: java.util.ServiceConfigurationError: "
+                + "javax.naming.spi.InitialContextFactory: "
+                + "Provider %s could not be instantiated", fqn);
+
+        String s3 = "Caused by: java.lang.RuntimeException: "
+                + "This is a broken factory. It is supposed to throw this exception.";
+
+        return output.startsWith(s1) && output.contains(s2)
+                && output.contains(s1);
+    }
+
+    private static void jar(Path jarName, Path jarRoot) {
+        String jar = getJDKTool("jar");
+        ProcessBuilder p = new ProcessBuilder(jar, "cf", jarName.toString(),
+                "-C", jarRoot.toString(), ".");
+        quickFail(run(p));
+    }
+
+    private static void javac(Path compilationOutput, Path... sourceFiles) {
+        String javac = getJDKTool("javac");
+        List<String> commands = new ArrayList<>();
+        commands.addAll(asList(javac, "-d", compilationOutput.toString()));
+        List<Path> paths = asList(sourceFiles);
+        commands.addAll(paths.stream()
+                .map(Path::toString)
+                .collect(Collectors.toList()));
+        quickFail(run(new ProcessBuilder(commands)));
+    }
+
+    private static void quickFail(Result r) {
+        if (r.exitValue != 0)
+            throw new RuntimeException(r.output);
+    }
+
+    private static Result java(Map<String, String> properties,
+                               Collection<Path> classpath,
+                               String classname) {
+
+        String java = getJDKTool("java");
+
+        List<String> commands = new ArrayList<>();
+        commands.add(java);
+        commands.addAll(properties.entrySet()
+                .stream()
+                .map(e -> "-D" + e.getKey() + "=" + e.getValue())
+                .collect(Collectors.toList()));
+
+        String cp = classpath.stream()
+                .map(Path::toString)
+                .collect(Collectors.joining(File.pathSeparator));
+        commands.add("-cp");
+        commands.add(cp);
+        commands.add(classname);
+
+        return run(new ProcessBuilder(commands));
+    }
+
+    private static Result run(ProcessBuilder b) {
+        Process p = null;
+        try {
+            p = b.start();
+        } catch (IOException e) {
+            throw new RuntimeException(
+                    format("Couldn't start process '%s'", b.command()), e);
+        }
+
+        String output;
+        try {
+            output = toString(p.getInputStream(), p.getErrorStream());
+        } catch (IOException e) {
+            throw new RuntimeException(
+                    format("Couldn't read process output '%s'", b.command()), e);
+        }
+
+        try {
+            p.waitFor();
+        } catch (InterruptedException e) {
+            throw new RuntimeException(
+                    format("Process hasn't finished '%s'", b.command()), e);
+        }
+
+        return new Result(p.exitValue(), output);
+    }
+
+    private static String getJDKTool(String name) {
+        String testJdk = System.getProperty("test.jdk");
+        if (testJdk == null)
+            throw new RuntimeException("Please provide test.jdk property at a startup");
+        return testJdk + File.separator + "bin" + File.separator + name;
+    }
+
+    private static Path templatesHome() {
+        String testSrc = System.getProperty("test.src");
+        if (testSrc == null)
+            throw new RuntimeException("Please provide test.src property at a startup");
+        return Paths.get(testSrc);
+    }
+
+    private static String toString(InputStream... src) throws IOException {
+        StringWriter dst = new StringWriter();
+        Reader concatenated =
+                new InputStreamReader(
+                        new SequenceInputStream(
+                                Collections.enumeration(asList(src))));
+        copy(concatenated, dst);
+        return dst.toString();
+    }
+
+    private static void copy(Reader src, Writer dst) throws IOException {
+        int len;
+        char[] buf = new char[1024];
+        try {
+            while ((len = src.read(buf)) != -1)
+                dst.write(buf, 0, len);
+        } finally {
+            try {
+                src.close();
+            } catch (IOException ignored1) {
+            } finally {
+                try {
+                    dst.close();
+                } catch (IOException ignored2) {
+                }
+            }
+        }
+    }
+
+    private static class Result {
+
+        final int exitValue;
+        final String output;
+
+        private Result(int exitValue, String output) {
+            this.exitValue = exitValue;
+            this.output = output;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/naming/spi/providers/broken_factory.template	Mon Oct 20 12:04:12 2014 -0700
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 $package;
+
+import javax.naming.*;
+import javax.naming.spi.InitialContextFactory;
+import java.util.Hashtable;
+
+public class $factoryName implements InitialContextFactory {
+
+    public $factoryName() {
+        throw new RuntimeException(
+                "This is a broken factory. It is supposed to throw this exception.");
+    }
+
+    @Override
+    public Context getInitialContext(Hashtable<?, ?> env) throws NamingException {
+        return new DummyInitialContext();
+    }
+
+    private class DummyInitialContext implements Context {
+
+        @Override
+        public Object lookup(Name name) {
+            return null;
+        }
+
+        @Override
+        public Object lookup(String name) {
+            return null;
+        }
+
+        @Override
+        public void bind(Name name, Object obj) {
+        }
+
+        @Override
+        public void bind(String name, Object obj) {
+        }
+
+        @Override
+        public void rebind(Name name, Object obj) {
+        }
+
+        @Override
+        public void rebind(String name, Object obj) {
+        }
+
+        @Override
+        public void unbind(Name name) {
+        }
+
+        @Override
+        public void unbind(String name) {
+        }
+
+        @Override
+        public void rename(Name oldName, Name newName) {
+        }
+
+        @Override
+        public void rename(String oldName, String newName) {
+        }
+
+        @Override
+        public NamingEnumeration<NameClassPair> list(Name name) {
+            return null;
+        }
+
+        @Override
+        public NamingEnumeration<NameClassPair> list(String name) {
+            return null;
+        }
+
+        @Override
+        public NamingEnumeration<Binding> listBindings(Name name) {
+            return null;
+        }
+
+        @Override
+        public NamingEnumeration<Binding> listBindings(String name) {
+            return null;
+        }
+
+        @Override
+        public void destroySubcontext(Name name) {
+        }
+
+        @Override
+        public void destroySubcontext(String name) {
+        }
+
+        @Override
+        public Context createSubcontext(Name name) {
+            return null;
+        }
+
+        @Override
+        public Context createSubcontext(String name) {
+            return null;
+        }
+
+        @Override
+        public Object lookupLink(Name name) {
+            return null;
+        }
+
+        @Override
+        public Object lookupLink(String name) {
+            return null;
+        }
+
+        @Override
+        public NameParser getNameParser(Name name) {
+            return null;
+        }
+
+        @Override
+        public NameParser getNameParser(String name) {
+            return null;
+        }
+
+        @Override
+        public Name composeName(Name name, Name prefix) {
+            return null;
+        }
+
+        @Override
+        public String composeName(String name, String prefix) {
+            return null;
+        }
+
+        @Override
+        public Object addToEnvironment(String propName, Object propVal) {
+            return null;
+        }
+
+        @Override
+        public Object removeFromEnvironment(String propName) {
+            return null;
+        }
+
+        @Override
+        public Hashtable<?, ?> getEnvironment() {
+            return null;
+        }
+
+        @Override
+        public void close() {
+        }
+
+        @Override
+        public String getNameInNamespace() {
+            return null;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/naming/spi/providers/factory.template	Mon Oct 20 12:04:12 2014 -0700
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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 $package;
+
+import javax.naming.*;
+import javax.naming.spi.InitialContextFactory;
+import java.util.Hashtable;
+
+public class $factoryName implements InitialContextFactory {
+
+    @Override
+    public Context getInitialContext(Hashtable<?, ?> env) throws NamingException {
+        return new DummyInitialContext();
+    }
+
+    private class DummyInitialContext implements Context {
+
+        @Override
+        public Object lookup(Name name) {
+            return null;
+        }
+
+        @Override
+        public Object lookup(String name) {
+            return null;
+        }
+
+        @Override
+        public void bind(Name name, Object obj) {
+        }
+
+        @Override
+        public void bind(String name, Object obj) {
+        }
+
+        @Override
+        public void rebind(Name name, Object obj) {
+        }
+
+        @Override
+        public void rebind(String name, Object obj) {
+        }
+
+        @Override
+        public void unbind(Name name) {
+        }
+
+        @Override
+        public void unbind(String name) {
+        }
+
+        @Override
+        public void rename(Name oldName, Name newName) {
+        }
+
+        @Override
+        public void rename(String oldName, String newName) {
+        }
+
+        @Override
+        public NamingEnumeration<NameClassPair> list(Name name) {
+            return null;
+        }
+
+        @Override
+        public NamingEnumeration<NameClassPair> list(String name) {
+            return null;
+        }
+
+        @Override
+        public NamingEnumeration<Binding> listBindings(Name name) {
+            return null;
+        }
+
+        @Override
+        public NamingEnumeration<Binding> listBindings(String name) {
+            return null;
+        }
+
+        @Override
+        public void destroySubcontext(Name name) {
+        }
+
+        @Override
+        public void destroySubcontext(String name) {
+        }
+
+        @Override
+        public Context createSubcontext(Name name) {
+            return null;
+        }
+
+        @Override
+        public Context createSubcontext(String name) {
+            return null;
+        }
+
+        @Override
+        public Object lookupLink(Name name) {
+            return null;
+        }
+
+        @Override
+        public Object lookupLink(String name) {
+            return null;
+        }
+
+        @Override
+        public NameParser getNameParser(Name name) {
+            return null;
+        }
+
+        @Override
+        public NameParser getNameParser(String name) {
+            return null;
+        }
+
+        @Override
+        public Name composeName(Name name, Name prefix) {
+            return null;
+        }
+
+        @Override
+        public String composeName(String name, String prefix) {
+            return null;
+        }
+
+        @Override
+        public Object addToEnvironment(String propName, Object propVal) {
+            return null;
+        }
+
+        @Override
+        public Object removeFromEnvironment(String propName) {
+            return null;
+        }
+
+        @Override
+        public Hashtable<?, ?> getEnvironment() {
+            return null;
+        }
+
+        @Override
+        public void close() {
+        }
+
+        @Override
+        public String getNameInNamespace() {
+            return null;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/naming/spi/providers/test.template	Mon Oct 20 12:04:12 2014 -0700
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import java.util.Properties;
+
+public class Test {
+
+    public static void main(String[] args) throws NamingException {
+        Properties env = System.getProperties();
+        Context ctx = new InitialContext(env);
+        try {
+            ctx.lookup("");
+        } finally {
+            ctx.close();
+        }
+    }
+}
--- a/test/javax/net/ssl/TLS/CipherTestUtils.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/test/javax/net/ssl/TLS/CipherTestUtils.java	Mon Oct 20 12:04:12 2014 -0700
@@ -261,20 +261,20 @@
         }
     }
 
-    private static volatile CipherTestUtils instnace = null;
+    private static volatile CipherTestUtils instance = null;
 
     public static CipherTestUtils getInstance() throws IOException,
             FileNotFoundException, KeyStoreException,
             NoSuchAlgorithmException, CertificateException,
             UnrecoverableKeyException, InvalidKeySpecException {
-        if (instnace == null) {
+        if (instance == null) {
             synchronized (CipherTestUtils.class) {
-                if (instnace == null) {
-                    instnace = new CipherTestUtils();
+                if (instance == null) {
+                    instance = new CipherTestUtils();
                 }
             }
         }
-        return instnace;
+        return instance;
     }
 
     public static void setTestedArguments(String testedProtocol,
--- a/test/tools/pack200/TestNormal.java	Mon Oct 20 11:22:58 2014 -0700
+++ b/test/tools/pack200/TestNormal.java	Mon Oct 20 12:04:12 2014 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,23 +42,15 @@
     public static void main(String args[]) throws Exception {
         Properties p = System.getProperties();
         String java_home = p.getProperty("test.jdk");
-        File testJar = new File("test.jar");
-        Utils.jar("cvf", testJar.getName(), Utils.TEST_CLS_DIR.getAbsolutePath());
-
-        File folder = new File("testdir");
-        if (folder.exists()) {
-            delete(folder);
-        }
-        folder.mkdir();
+        String testdir = Utils.TEST_CLS_DIR.getAbsolutePath();
 
         try {
-            extractJar(new JarFile(testJar), folder);
-            execJavaCommand(java_home, "jar cnf normalized.jar -C testdir .");
-            execJavaCommand(java_home, "jar cf original.jar -C testdir .");
+            execJavaCommand(java_home, "jar cnf normalized.jar -C " + testdir + " .");
+            execJavaCommand(java_home, "jar cf original.jar -C " + testdir + " .");
             execJavaCommand(java_home, "pack200 -r repacked.jar original.jar");
             compareJars(new JarFile("normalized.jar"), new JarFile("repacked.jar"));
         } finally {
-            String[] cleanupList = {"testdir", "normalized.jar", "original.jar", "repacked.jar"};
+            String[] cleanupList = {"normalized.jar", "original.jar", "repacked.jar"};
             for (String s : cleanupList) {
                 delete(new File(s));
             }
@@ -101,36 +93,6 @@
         }
     }
 
-    public static void extractJar(JarFile jf, File where) throws Exception {
-        for (JarEntry file : Collections.list(jf.entries())) {
-            File out = new File(where, file.getName());
-            if (file.isDirectory()) {
-                out.mkdirs();
-                continue;
-            }
-            File parent = out.getParentFile();
-            if (parent != null && !parent.exists()) {
-                parent.mkdirs();
-            }
-            InputStream is = null;
-            OutputStream os = null;
-            try {
-                is = jf.getInputStream(file);
-                os = new FileOutputStream(out);
-                while (is.available() > 0) {
-                    os.write(is.read());
-                }
-            } finally {
-                if (is != null) {
-                    is.close();
-                }
-                if (os != null) {
-                    os.close();
-                }
-            }
-        }
-    }
-
     static void delete(File f) throws IOException {
         if (!f.exists()) {
             return;