diff --git a/.hgtags b/.hgtags index ef7ee162e19..8f99216cf55 100644 --- a/.hgtags +++ b/.hgtags @@ -298,3 +298,10 @@ d6224d6021459ac8b3832e822f5acc849fa944af jdk9-b52 874d76e4699dfcd61ae1826c9fe0ddc1610ad598 jdk9-b53 82cd31c5d6ca8d4c1653f4eb1c09eb2d9a3b2813 jdk9-b54 c97e2d1bad9708d379793ba2a4c848eda14c741e jdk9-b55 +47544495db2d3d2edf0f85862d8715592fdb919f jdk9-b56 +ddb95d8f169b09544cc17e72a6baaff2400092f5 jdk9-b57 +f40752db7773ca0c737f2ad88371e35c57fdfed7 jdk9-b58 +da950f343762a856d69751570a4c07cfa68a415b jdk9-b59 +38f98cb6b33562a926ec3b79c7b34128be37647d jdk9-b60 +ac3f5a39d4ff14d70c365e12cf5ec8f2abd52a04 jdk9-b61 +e7dbbef69d12b6a74dfad331b7188e7f893e8d29 jdk9-b62 diff --git a/.hgtags-top-repo b/.hgtags-top-repo index 289a8ebab69..ecdc65b6c89 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -298,3 +298,10 @@ d1f37d39ff2421f956a6ddf316cf763807bc3363 jdk9-b50 d6ed47125a76cd1cf8a100568507bfb5e9669d9f jdk9-b53 cb7367141e910e265b8344a8facee740bd1e5467 jdk9-b54 0c37a832458f0e0b7d2a3f1a6f69aeae311aeb18 jdk9-b55 +eb7febe45865ba6b81f2ea68082262d0708a0b22 jdk9-b56 +f25ee9f62427a9ba27418e5531a89754791a305b jdk9-b57 +6e78dd9b121037719a065fe8fb25b936babdfecb jdk9-b58 +39e8a131289e8386aa4c3e4b184faa812a7c0421 jdk9-b59 +9fa2185bee17462d1014538bff60af6e6f0b01e7 jdk9-b60 +ea38728b4f4bdd8fd0d7a89b18069f521cf05013 jdk9-b61 +105d045a69174d870b69bfe471b3f2d05a9f8ecc jdk9-b62 diff --git a/Makefile b/Makefile index 825bad1fcb7..2460cd414d8 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ # -# Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. # 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,200 +23,42 @@ # questions. # -# This must be the first rule -default: +### +### This file is just a very small wrapper needed to run the real make/Init.gmk. +### It also performs some sanity checks on make. +### -# Inclusion of this pseudo-target will cause make to execute this file -# serially, regardless of -j. Recursively called makefiles will not be -# affected, however. This is required for correct dependency management. -.NOTPARALLEL: - -# The shell code below will be executed on /usr/ccs/bin/make on Solaris, but not in GNU make. +# The shell code below will be executed on /usr/ccs/bin/make on Solaris, but not in GNU Make. # /usr/ccs/bin/make lacks basically every other flow control mechanism. -.TEST_FOR_NON_GNUMAKE:sh=echo You are not using GNU make/gmake, this is a requirement. Check your path. 1>&2 && exit 1 +.TEST_FOR_NON_GNUMAKE:sh=echo You are not using GNU Make/gmake, this is a requirement. Check your path. 1>&2 && exit 1 -# Assume we have GNU make, but check version. +# The .FEATURES variable is likely to be unique for GNU Make. +ifeq ($(.FEATURES), ) + $(info Error: '$(MAKE)' does not seem to be GNU Make, which is a requirement.) + $(info Check your path, or upgrade to GNU Make 3.81 or newer.) + $(error Cannot continue) +endif + +# Assume we have GNU Make, but check version. ifeq ($(strip $(foreach v, 3.81% 3.82% 4.%, $(filter $v, $(MAKE_VERSION)))), ) - $(error This version of GNU Make is too low ($(MAKE_VERSION)). Check your path, or upgrade to 3.81 or newer.) + $(info Error: This version of GNU Make is too low ($(MAKE_VERSION)).) + $(info Check your path, or upgrade to GNU Make 3.81 or newer.) + $(error Cannot continue) +endif + +# In Cygwin, the MAKE variable gets prepended with the current directory if the +# make executable is called using a Windows mixed path (c:/cygwin/bin/make.exe). +ifneq ($(findstring :, $(MAKE)), ) + MAKE := $(patsubst $(CURDIR)%, %, $(patsubst $(CURDIR)/%, %, $(MAKE))) endif # Locate this Makefile -ifeq ($(filter /%,$(lastword $(MAKEFILE_LIST))),) - makefile_path:=$(CURDIR)/$(lastword $(MAKEFILE_LIST)) +ifeq ($(filter /%, $(lastword $(MAKEFILE_LIST))),) + makefile_path := $(CURDIR)/$(strip $(lastword $(MAKEFILE_LIST))) else - makefile_path:=$(lastword $(MAKEFILE_LIST)) + makefile_path := $(lastword $(MAKEFILE_LIST)) endif -root_dir:=$(patsubst %/,%,$(dir $(makefile_path))) +topdir := $(strip $(patsubst %/, %, $(dir $(makefile_path)))) -ifeq ($(MAIN_TARGETS), ) - COMMAND_LINE_VARIABLES:=$(subst =command,,$(filter %=command,$(foreach var,$(.VARIABLES),$(var)=$(firstword $(origin $(var)))))) - MAKE_CONTROL_VARIABLES:=LOG CONF SPEC JOBS TEST IGNORE_OLD_CONFIG - UNKNOWN_COMMAND_LINE_VARIABLES:=$(strip $(filter-out $(MAKE_CONTROL_VARIABLES), $(COMMAND_LINE_VARIABLES))) - ifneq ($(UNKNOWN_COMMAND_LINE_VARIABLES), ) - $(info Note: Command line contains non-control variables: $(UNKNOWN_COMMAND_LINE_VARIABLES).) - $(info Make sure it is not mistyped, and that you intend to override this variable.) - $(info 'make help' will list known control variables) - endif -endif - -ifneq ($(findstring qp,$(MAKEFLAGS)),) - # When called with -qp, assume an external part (e.g. bash completion) is trying - # to understand our targets. - # Duplication of global targets, needed before ParseConfAndSpec in case we have - # no configurations. - help: - # If both CONF and SPEC are unset, look for all available configurations by - # setting CONF to the empty string. - ifeq ($(SPEC), ) - CONF?= - endif -endif - -# ... and then we can include our helper functions -include $(root_dir)/make/MakeHelpers.gmk - -$(eval $(call ParseLogLevel)) -$(eval $(call ParseConfAndSpec)) - -# Now determine if we have zero, one or several configurations to build. -ifeq ($(SPEC),) - # Since we got past ParseConfAndSpec, we must be building a global target. Do nothing. -else - # In Cygwin, the MAKE variable gets messed up if the make executable is called with - # a Windows mixed path (c:/cygwin/bin/make.exe). If that's the case, fix it by removing - # the prepended root_dir. - ifneq ($(findstring :, $(MAKE)), ) - MAKE := $(patsubst $(root_dir)%, %, $(MAKE)) - endif - - # We are potentially building multiple configurations. - # First, find out the valid targets - # Run the makefile with an arbitrary SPEC using -p -q (quiet dry-run and dump rules) to find - # available PHONY targets. Use this list as valid targets to pass on to the repeated calls. - all_phony_targets := $(sort $(filter-out $(global_targets), $(strip $(shell \ - cd $(root_dir)/make && $(MAKE) -f Main.gmk -p -q FRC SPEC=$(firstword $(SPEC)) \ - -I $(root_dir)/make/common | grep "^.PHONY:" | head -n 1 | cut -d " " -f 2-)))) - - # Loop through the configurations and call the main-wrapper for each one. The wrapper - # target will execute with a single configuration loaded. - $(all_phony_targets): - @$(if $(TARGET_RUN),,\ - $(foreach spec,$(SPEC),\ - (cd $(root_dir) && $(MAKE) SPEC=$(spec) MAIN_TARGETS="$(call GetRealTarget)" \ - $(VERBOSE) VERBOSE=$(VERBOSE) LOG_LEVEL=$(LOG_LEVEL) main-wrapper) &&) true) - @echo > /dev/null - $(eval TARGET_RUN=true) - - .PHONY: $(all_phony_targets) - - ifneq ($(MAIN_TARGETS), ) - # The wrapper target was called so we now have a single configuration. Load the spec file - # and call the real Main.gmk. - include $(SPEC) - include $(SRC_ROOT)/make/common/MakeBase.gmk - - ### Clean up from previous run - # Remove any build.log from a previous run, if they exist - ifneq (,$(BUILD_LOG)) - ifneq (,$(BUILD_LOG_PREVIOUS)) - # Rotate old log - $(shell $(RM) $(BUILD_LOG_PREVIOUS) 2> /dev/null) - $(shell $(MV) $(BUILD_LOG) $(BUILD_LOG_PREVIOUS) 2> /dev/null) - else - $(shell $(RM) $(BUILD_LOG) 2> /dev/null) - endif - $(shell $(RM) $(OUTPUT_ROOT)/build-trace-time.log 2> /dev/null) - endif - # Remove any javac server logs and port files. This - # prevents a new make run to reuse the previous servers. - ifneq (,$(SJAVAC_SERVER_DIR)) - $(shell $(MKDIR) -p $(SJAVAC_SERVER_DIR) && $(RM) -rf $(SJAVAC_SERVER_DIR)/*) - endif - - # Split out the targets requiring sequential execution. Run these targets separately - # from the rest so that the rest may still enjoy full parallel execution. - SEQUENTIAL_TARGETS := $(filter dist-clean clean% reconfigure, $(MAIN_TARGETS)) - PARALLEL_TARGETS := $(filter-out $(SEQUENTIAL_TARGETS), $(MAIN_TARGETS)) - - main-wrapper: - ifneq ($(SEQUENTIAL_TARGETS), ) - (cd $(SRC_ROOT)/make && $(MAKE) -f Main.gmk SPEC=$(SPEC) -j 1 \ - $(VERBOSE) VERBOSE=$(VERBOSE) LOG_LEVEL=$(LOG_LEVEL) $(SEQUENTIAL_TARGETS)) - endif - ifneq ($(PARALLEL_TARGETS), ) - @$(call AtMakeStart) - (cd $(SRC_ROOT)/make && $(BUILD_LOG_WRAPPER) $(MAKE) -f Main.gmk SPEC=$(SPEC) -j $(JOBS) \ - $(VERBOSE) VERBOSE=$(VERBOSE) LOG_LEVEL=$(LOG_LEVEL) $(PARALLEL_TARGETS) \ - $(if $(filter true, $(OUTPUT_SYNC_SUPPORTED)), -O$(OUTPUT_SYNC))) - @$(call AtMakeEnd) - endif - - .PHONY: main-wrapper - - endif -endif - -# Here are "global" targets, i.e. targets that can be executed without specifying a single configuration. -# If you add more global targets, please update the variable global_targets in MakeHelpers. - -# Helper macro to allow $(info) to properly print strings beginning with spaces. -_:= - -help: - $(info ) - $(info OpenJDK Makefile help) - $(info =====================) - $(info ) - $(info Common make targets) - $(info $(_) make [default] # Compile all modules in langtools, hotspot, jdk, jaxws,) - $(info $(_) # jaxp and corba, and create a runnable "exploded" image) - $(info $(_) make all # Compile everything, all repos, docs and images) - $(info $(_) make images # Create complete j2sdk and j2re images) - $(info $(_) make # Build the specified phase and everything it depends on) - $(info $(_) # (gensrc, java, copy, libs, launchers, gendata, rmic)) - $(info $(_) make *-only # Applies to most targets and disables compling the) - $(info $(_) # dependencies for the target. This is faster but may) - $(info $(_) # result in incorrect build results!) - $(info $(_) make docs # Create all docs) - $(info $(_) make docs-javadoc # Create just javadocs, depends on less than full docs) - $(info $(_) make profiles # Create complete j2re compact profile images) - $(info $(_) make bootcycle-images # Build images twice, second time with newly built JDK) - $(info $(_) make install # Install the generated images locally) - $(info $(_) make reconfigure # Rerun configure with the same arguments as last time) - $(info $(_) make help # Give some help on using make) - $(info $(_) make test # Run tests, default is all tests (see TEST below)) - $(info ) - $(info Targets for cleaning) - $(info $(_) make clean # Remove all files generated by make, but not those) - $(info $(_) # generated by configure) - $(info $(_) make dist-clean # Remove all files, including configuration) - $(info $(_) make clean- # Remove the subdir in the output dir with the name) - $(info $(_) make clean- # Remove all build results related to a certain build) - $(info $(_) # phase (gensrc, java, libs, launchers)) - $(info $(_) make clean- # Remove all build results related to a certain module) - $(info $(_) make clean-- # Remove all build results related to a certain) - $(info $(_) # module and phase) - $(info ) - $(info Targets for specific modules) - $(info $(_) make # Build and everything it depends on.) - $(info $(_) make - # Compile the specified phase for the specified module) - $(info $(_) # and everything it depends on) - $(info $(_) # (gensrc, java, copy, libs, launchers, gendata, rmic)) - $(info ) - $(info Make control variables) - $(info $(_) CONF= # Build all configurations (note, assignment is empty)) - $(info $(_) CONF= # Build the configuration(s) with a name matching) - $(info $(_) # ) - $(info $(_) SPEC= # Build the configuration given by the spec file) - $(info $(_) LOG= # Change the log level from warn to ) - $(info $(_) # Available log levels are:) - $(info $(_) # 'warn' (default), 'info', 'debug' and 'trace') - $(info $(_) # To see executed command lines, use LOG=debug) - $(info $(_) JOBS= # Run parallel make jobs) - $(info $(_) # Note that -jN does not work as expected!) - $(info $(_) IGNORE_OLD_CONFIG=true # Skip tests if spec file is up to date) - $(info $(_) make test TEST= # Only run the given test or tests, e.g.) - $(info $(_) # make test TEST="jdk_lang jdk_net") - $(info ) - -.PHONY: help +# ... and then we can include the real makefile +include $(topdir)/make/Init.gmk diff --git a/README-builds.html b/README-builds.html index 85a1040db38..b0cc892f9c4 100644 --- a/README-builds.html +++ b/README-builds.html @@ -41,7 +41,8 @@ The build is now a "configure && make" style build
  • - Any GNU make 3.81 or newer should work + Any GNU make 3.81 or newer should work, except on + Windows where 4.0 or newer is recommended.
  • The build should scale, i.e. more processors should @@ -358,8 +359,8 @@ For all systems:
    • - Be sure the GNU make utility is version 3.81 or newer, - e.g. run "make -version" + Be sure the GNU make utility is version 3.81 (4.0 on + windows) or newer, e.g. run "make -version"
    • Install a @@ -441,7 +442,7 @@
    • Install - Visual Studio 2010 + Visual Studio 2013
    @@ -750,23 +751,23 @@ -
    Visual Studio 2010 Compilers
    +
    Visual Studio 2013 Compilers

    The 32-bit and 64-bit OpenJDK Windows build requires - Microsoft Visual Studio C++ 2010 (VS2010) Professional + Microsoft Visual Studio C++ 2013 (VS2013) Professional Edition or Express compiler. The compiler and other tools are expected to reside in the location defined by the variable - VS100COMNTOOLS which + VS120COMNTOOLS which is set by the Microsoft Visual Studio installer.

    - Only the C++ part of VS2010 is needed. + Only the C++ part of VS2013 is needed. Try to let the installation go to the default install directory. - Always reboot your system after installing VS2010. - The system environment variable VS100COMNTOOLS + Always reboot your system after installing VS2013. + The system environment variable VS120COMNTOOLS should be set in your environment.

    @@ -1040,7 +1041,7 @@
    This is usually picked up automatically from the redist - directories of Visual Studio 2010. + directories of Visual Studio 2013. @@ -1726,10 +1727,10 @@ A few notes about using GNU make:
    • - You need GNU make version 3.81 or newer. - If the GNU make utility on your systems is not - 3.81 or newer, - see "Building GNU make". + You need GNU make version 3.81 or newer. On Windows 4.0 or + newer is recommended. + If the GNU make utility on your systems is not of a suitable + version see "Building GNU make".
    • Place the location of the GNU make binary in the @@ -1854,54 +1855,54 @@ Linux X86 (32-bit) and X64 (64-bit) - Fedora 9 - gcc 4.3 - JDK 7u7 + Oracle Enterprise Linux 6.4 + gcc 4.8.2 + JDK 8 2 or more 1 GB 6 GB - Solaris SPARC (32-bit) and SPARCV9 (64-bit) - Solaris 10 Update 6 - Studio 12 Update 1 + patches - JDK 7u7 + Solaris SPARCV9 (64-bit) + Solaris 10 Update 10 + Studio 12 Update 3 + patches + JDK 8 4 or more 4 GB 8 GB - Solaris X86 (32-bit) and X64 (64-bit) - Solaris 10 Update 6 - Studio 12 Update 1 + patches - JDK 7u7 + Solaris X64 (64-bit) + Solaris 10 Update 10 + Studio 12 Update 3 + patches + JDK 8 4 or more 4 GB 8 GB Windows X86 (32-bit) - Windows XP - Microsoft Visual Studio C++ 2010 Professional Edition - JDK 7u7 + Windows Server 2012 R2 x64 + Microsoft Visual Studio C++ 2013 Professional Edition + JDK 8 2 or more 2 GB 6 GB Windows X64 (64-bit) - Windows Server 2003 - Enterprise x64 Edition - Microsoft Visual Studio C++ 2010 Professional Edition - JDK 7u7 + Windows Server 2012 R2 x64 + Microsoft Visual Studio C++ 2013 Professional Edition + JDK 8 2 or more 2 GB 6 GB Mac OS X X64 (64-bit) - Mac OS X 10.7 "Lion" - XCode 4.5.2 or newer - JDK 7u7 + Mac OS X 10.9 "Mavericks" + XCode 5.1.1 or newer + JDK 8 2 or more 4 GB 6 GB @@ -2009,7 +2010,7 @@

    Ubuntu 12.04

    -
    +
    After installing Ubuntu 12.04 you need to install several build dependencies. The simplest way to do it is to execute the following commands: diff --git a/common/autoconf/basics.m4 b/common/autoconf/basics.m4 index 422837aae88..f78c2d88279 100644 --- a/common/autoconf/basics.m4 +++ b/common/autoconf/basics.m4 @@ -78,7 +78,7 @@ AC_DEFUN([BASIC_PREPEND_TO_PATH], AC_DEFUN([BASIC_FIXUP_PATH], [ # Only process if variable expands to non-empty - + if test "x[$]$1" != x; then if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then BASIC_FIXUP_PATH_CYGWIN($1) @@ -118,7 +118,7 @@ AC_DEFUN([BASIC_FIXUP_PATH], AC_DEFUN([BASIC_FIXUP_EXECUTABLE], [ # Only process if variable expands to non-empty - + if test "x[$]$1" != x; then if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then BASIC_FIXUP_EXECUTABLE_CYGWIN($1) @@ -459,16 +459,34 @@ AC_DEFUN_ONCE([BASIC_SETUP_PATHS], AC_MSG_RESULT([$TOPDIR]) AC_SUBST(TOPDIR) + # Save the original version of TOPDIR for string comparisons + ORIGINAL_TOPDIR="$TOPDIR" + AC_SUBST(ORIGINAL_TOPDIR) + # We can only call BASIC_FIXUP_PATH after BASIC_CHECK_PATHS_WINDOWS. BASIC_FIXUP_PATH(CURDIR) BASIC_FIXUP_PATH(TOPDIR) # SRC_ROOT is a traditional alias for TOPDIR. SRC_ROOT=$TOPDIR + # Calculate a canonical version of TOPDIR for string comparisons + CANONICAL_TOPDIR=$TOPDIR + BASIC_REMOVE_SYMBOLIC_LINKS([CANONICAL_TOPDIR]) + AC_SUBST(CANONICAL_TOPDIR) + # Locate the directory of this script. AUTOCONF_DIR=$TOPDIR/common/autoconf ]) +# Evaluates platform specific overrides for devkit variables. +# $1: Name of variable +AC_DEFUN([BASIC_EVAL_DEVKIT_VARIABLE], +[ + if test "x[$]$1" = x; then + eval $1="\${$1_${OPENJDK_TARGET_CPU}}" + fi +]) + AC_DEFUN_ONCE([BASIC_SETUP_DEVKIT], [ AC_ARG_WITH([devkit], [AS_HELP_STRING([--with-devkit], @@ -478,12 +496,27 @@ AC_DEFUN_ONCE([BASIC_SETUP_DEVKIT], DEVKIT_ROOT="$with_devkit" # Check for a meta data info file in the root of the devkit if test -f "$DEVKIT_ROOT/devkit.info"; then - # This potentially sets the following: - # DEVKIT_NAME: A descriptive name of the devkit - # DEVKIT_TOOLCHAIN_PATH: Corresponds to --with-toolchain-path - # DEVKIT_EXTRA_PATH: Corresponds to --with-extra-path - # DEVKIT_SYSROOT: Corresponds to --with-sysroot . $DEVKIT_ROOT/devkit.info + # This potentially sets the following: + # A descriptive name of the devkit + BASIC_EVAL_DEVKIT_VARIABLE([DEVKIT_NAME]) + # Corresponds to --with-extra-path + BASIC_EVAL_DEVKIT_VARIABLE([DEVKIT_EXTRA_PATH]) + # Corresponds to --with-toolchain-path + BASIC_EVAL_DEVKIT_VARIABLE([DEVKIT_TOOLCHAIN_PATH]) + # Corresponds to --with-sysroot + BASIC_EVAL_DEVKIT_VARIABLE([DEVKIT_SYSROOT]) + + # Identifies the Visual Studio version in the devkit + BASIC_EVAL_DEVKIT_VARIABLE([DEVKIT_VS_VERSION]) + # The Visual Studio include environment variable + BASIC_EVAL_DEVKIT_VARIABLE([DEVKIT_VS_INCLUDE]) + # The Visual Studio lib environment variable + BASIC_EVAL_DEVKIT_VARIABLE([DEVKIT_VS_LIB]) + # Corresponds to --with-msvcr-dll + BASIC_EVAL_DEVKIT_VARIABLE([DEVKIT_MSVCR_DLL]) + # Corresponds to --with-msvcp-dll + BASIC_EVAL_DEVKIT_VARIABLE([DEVKIT_MSVCP_DLL]) fi AC_MSG_CHECKING([for devkit]) @@ -493,9 +526,7 @@ AC_DEFUN_ONCE([BASIC_SETUP_DEVKIT], AC_MSG_RESULT([$DEVKIT_ROOT]) fi - if test "x$DEVKIT_EXTRA_PATH" != x; then - BASIC_PREPEND_TO_PATH([EXTRA_PATH],$DEVKIT_EXTRA_PATH) - fi + BASIC_PREPEND_TO_PATH([EXTRA_PATH],$DEVKIT_EXTRA_PATH) # Fallback default of just /bin if DEVKIT_PATH is not defined if test "x$DEVKIT_TOOLCHAIN_PATH" = x; then @@ -672,8 +703,12 @@ AC_DEFUN_ONCE([BASIC_SETUP_OUTPUT_DIR], files_present=`$LS $OUTPUT_ROOT` # Configure has already touched config.log and confdefs.h in the current dir when this check # is performed. - filtered_files=`$ECHO "$files_present" | $SED -e 's/config.log//g' -e 's/confdefs.h//g' -e 's/ //g' \ - | $TR -d '\n'` + filtered_files=`$ECHO "$files_present" \ + | $SED -e 's/config.log//g' \ + -e 's/confdefs.h//g' \ + -e 's/fixpath.exe//g' \ + -e 's/ //g' \ + | $TR -d '\n'` if test "x$filtered_files" != x; then AC_MSG_NOTICE([Current directory is $CURDIR.]) AC_MSG_NOTICE([Since this is not the source root, configure will output the configuration here]) @@ -691,9 +726,13 @@ AC_DEFUN_ONCE([BASIC_SETUP_OUTPUT_DIR], BASIC_FIXUP_PATH(OUTPUT_ROOT) + CONFIGURESUPPORT_OUTPUTDIR="$OUTPUT_ROOT/configure-support" + $MKDIR -p "$CONFIGURESUPPORT_OUTPUTDIR" + AC_SUBST(SPEC, $OUTPUT_ROOT/spec.gmk) AC_SUBST(CONF_NAME, $CONF_NAME) AC_SUBST(OUTPUT_ROOT, $OUTPUT_ROOT) + AC_SUBST(CONFIGURESUPPORT_OUTPUTDIR) # The spec.gmk file contains all variables for the make system. AC_CONFIG_FILES([$OUTPUT_ROOT/spec.gmk:$AUTOCONF_DIR/spec.gmk.in]) @@ -709,18 +748,6 @@ AC_DEFUN_ONCE([BASIC_SETUP_OUTPUT_DIR], AC_CONFIG_FILES([$OUTPUT_ROOT/Makefile:$AUTOCONF_DIR/Makefile.in]) ]) -AC_DEFUN_ONCE([BASIC_SETUP_LOGGING], -[ - # Setup default logging of stdout and stderr to build.log in the output root. - BUILD_LOG='$(OUTPUT_ROOT)/build.log' - BUILD_LOG_PREVIOUS='$(OUTPUT_ROOT)/build.log.old' - BUILD_LOG_WRAPPER='$(BASH) $(SRC_ROOT)/common/bin/logger.sh $(BUILD_LOG)' - AC_SUBST(BUILD_LOG) - AC_SUBST(BUILD_LOG_PREVIOUS) - AC_SUBST(BUILD_LOG_WRAPPER) -]) - - #%%% Simple tools %%% # Check if we have found a usable version of make @@ -730,6 +757,16 @@ AC_DEFUN([BASIC_CHECK_MAKE_VERSION], [ MAKE_CANDIDATE="$1" DESCRIPTION="$2" + + # On Cygwin, we require a newer version of make than on other platforms + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + MAKE_VERSION_EXPR="-e 4\." + MAKE_REQUIRED_VERSION="4.0" + else + MAKE_VERSION_EXPR="-e 3\.8[[12]] -e 4\." + MAKE_REQUIRED_VERSION="3.81" + fi + if test "x$MAKE_CANDIDATE" != x; then AC_MSG_NOTICE([Testing potential make at $MAKE_CANDIDATE, found using $DESCRIPTION]) MAKE_VERSION_STRING=`$MAKE_CANDIDATE --version | $HEAD -n 1` @@ -737,9 +774,9 @@ AC_DEFUN([BASIC_CHECK_MAKE_VERSION], if test "x$IS_GNU_MAKE" = x; then AC_MSG_NOTICE([Found potential make at $MAKE_CANDIDATE, however, this is not GNU Make. Ignoring.]) else - IS_MODERN_MAKE=`$ECHO $MAKE_VERSION_STRING | $GREP -e '3\.8[[12]]' -e '4\.'` + IS_MODERN_MAKE=`$ECHO $MAKE_VERSION_STRING | $GREP $MAKE_VERSION_EXPR` if test "x$IS_MODERN_MAKE" = x; then - AC_MSG_NOTICE([Found GNU make at $MAKE_CANDIDATE, however this is not version 3.81 or later. (it is: $MAKE_VERSION_STRING). Ignoring.]) + AC_MSG_NOTICE([Found GNU make at $MAKE_CANDIDATE, however this is not version $MAKE_REQUIRED_VERSION or later. (it is: $MAKE_VERSION_STRING). Ignoring.]) else if test "x$OPENJDK_BUILD_OS" = "xwindows"; then if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then @@ -803,7 +840,7 @@ AC_DEFUN([BASIC_CHECK_GNU_MAKE], fi BASIC_CHECK_MAKE_VERSION("$MAKE", [user supplied MAKE=$MAKE]) if test "x$FOUND_MAKE" = x; then - AC_MSG_ERROR([The specified make (by MAKE=$MAKE) is not GNU make 3.81 or newer.]) + AC_MSG_ERROR([The specified make (by MAKE=$MAKE) is not GNU make $MAKE_REQUIRED_VERSION or newer.]) fi else # Try our hardest to locate a correct version of GNU make @@ -831,13 +868,13 @@ AC_DEFUN([BASIC_CHECK_GNU_MAKE], fi if test "x$FOUND_MAKE" = x; then - AC_MSG_ERROR([Cannot find GNU make 3.81 or newer! Please put it in the path, or add e.g. MAKE=/opt/gmake3.81/make as argument to configure.]) + AC_MSG_ERROR([Cannot find GNU make $MAKE_REQUIRED_VERSION or newer! Please put it in the path, or add e.g. MAKE=/opt/gmake3.81/make as argument to configure.]) fi fi MAKE=$FOUND_MAKE AC_SUBST(MAKE) - AC_MSG_NOTICE([Using GNU make 3.81 (or later) at $FOUND_MAKE (version: $MAKE_VERSION_STRING)]) + AC_MSG_NOTICE([Using GNU make at $FOUND_MAKE (version: $MAKE_VERSION_STRING)]) BASIC_CHECK_MAKE_OUTPUT_SYNC ]) diff --git a/common/autoconf/basics_windows.m4 b/common/autoconf/basics_windows.m4 index 1bcb6151486..210cc455047 100644 --- a/common/autoconf/basics_windows.m4 +++ b/common/autoconf/basics_windows.m4 @@ -66,7 +66,7 @@ AC_DEFUN([BASIC_MAKE_WINDOWS_SPACE_SAFE_CYGWIN], # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -383,45 +383,46 @@ AC_DEFUN_ONCE([BASIC_COMPILE_FIXPATH], if test "x$OPENJDK_BUILD_OS" = xwindows; then AC_MSG_CHECKING([if fixpath can be created]) FIXPATH_SRC="$SRC_ROOT/common/src/fixpath.c" - FIXPATH_BIN="$OUTPUT_ROOT/fixpath.exe" + FIXPATH_BIN="$CONFIGURESUPPORT_OUTPUTDIR/bin/fixpath.exe" + FIXPATH_DIR="$CONFIGURESUPPORT_OUTPUTDIR/fixpath" if test "x$OPENJDK_BUILD_OS_ENV" = xwindows.cygwin; then - FIXPATH_SRC=`$CYGPATH -m $FIXPATH_SRC` - FIXPATH_BIN=`$CYGPATH -m $FIXPATH_BIN` # Important to keep the .exe suffix on Cygwin for Hotspot makefiles - FIXPATH="$OUTPUT_ROOT/fixpath.exe -c" + FIXPATH="$FIXPATH_BIN -c" elif test "x$OPENJDK_BUILD_OS_ENV" = xwindows.msys; then - FIXPATH_SRC=`cmd //c echo $FIXPATH_SRC` - FIXPATH_BIN=`cmd //c echo $FIXPATH_BIN` - # Take all collected prefixes and turn them into a -m/c/foo@/c/bar@... command line # @ was chosen as separator to minimize risk of other tools messing around with it - all_unique_prefixes=`echo "${all_fixpath_prefixes@<:@@@:>@}" | tr ' ' '\n' | grep '^/./' | sort | uniq` + all_unique_prefixes=`echo "${all_fixpath_prefixes@<:@@@:>@}" \ + | tr ' ' '\n' | grep '^/./' | sort | uniq` fixpath_argument_list=`echo $all_unique_prefixes | tr ' ' '@'` - - FIXPATH="$OUTPUT_ROOT/fixpath -m$fixpath_argument_list" + FIXPATH="$FIXPATH_BIN -m$fixpath_argument_list" fi - rm -f $OUTPUT_ROOT/fixpath* - cd $OUTPUT_ROOT - $CC $FIXPATH_SRC -Fe$FIXPATH_BIN > $OUTPUT_ROOT/fixpath1.log 2>&1 + FIXPATH_SRC_W="$FIXPATH_SRC" + FIXPATH_BIN_W="$FIXPATH_BIN" + BASIC_WINDOWS_REWRITE_AS_WINDOWS_MIXED_PATH([FIXPATH_SRC_W]) + BASIC_WINDOWS_REWRITE_AS_WINDOWS_MIXED_PATH([FIXPATH_BIN_W]) + $RM -rf $FIXPATH_BIN $FIXPATH_DIR + $MKDIR -p $FIXPATH_DIR $CONFIGURESUPPORT_OUTPUTDIR/bin + cd $FIXPATH_DIR + $CC $FIXPATH_SRC_W -Fe$FIXPATH_BIN_W > $FIXPATH_DIR/fixpath1.log 2>&1 cd $CURDIR - if test ! -x $OUTPUT_ROOT/fixpath.exe; then + if test ! -x $FIXPATH_BIN; then AC_MSG_RESULT([no]) - cat $OUTPUT_ROOT/fixpath1.log - AC_MSG_ERROR([Could not create $OUTPUT_ROOT/fixpath.exe]) + cat $FIXPATH_DIR/fixpath1.log + AC_MSG_ERROR([Could not create $FIXPATH_BIN]) fi AC_MSG_RESULT([yes]) AC_MSG_CHECKING([if fixpath.exe works]) - cd $OUTPUT_ROOT - $FIXPATH $CC $SRC_ROOT/common/src/fixpath.c -Fe$OUTPUT_ROOT/fixpath2.exe > $OUTPUT_ROOT/fixpath2.log 2>&1 + cd $FIXPATH_DIR + $FIXPATH $CC $FIXPATH_SRC -Fe$FIXPATH_DIR/fixpath2.exe \ + > $FIXPATH_DIR/fixpath2.log 2>&1 cd $CURDIR - if test ! -x $OUTPUT_ROOT/fixpath2.exe; then + if test ! -x $FIXPATH_DIR/fixpath2.exe; then AC_MSG_RESULT([no]) - cat $OUTPUT_ROOT/fixpath2.log + cat $FIXPATH_DIR/fixpath2.log AC_MSG_ERROR([fixpath did not work!]) fi AC_MSG_RESULT([yes]) - rm -f $OUTPUT_ROOT/fixpath?.??? $OUTPUT_ROOT/fixpath.obj fi AC_SUBST(FIXPATH) diff --git a/common/autoconf/build-performance.m4 b/common/autoconf/build-performance.m4 index 5b3dbdd1fe4..b5911b789a7 100644 --- a/common/autoconf/build-performance.m4 +++ b/common/autoconf/build-performance.m4 @@ -336,11 +336,4 @@ AC_DEFUN_ONCE([BPERF_SETUP_SMART_JAVAC], AC_MSG_CHECKING([whether to use sjavac]) AC_MSG_RESULT([$ENABLE_SJAVAC]) AC_SUBST(ENABLE_SJAVAC) - - if test "x$ENABLE_SJAVAC" = xyes; then - SJAVAC_SERVER_DIR="$OUTPUT_ROOT/javacservers" - else - SJAVAC_SERVER_DIR= - fi - AC_SUBST(SJAVAC_SERVER_DIR) ]) diff --git a/common/autoconf/configure.ac b/common/autoconf/configure.ac index 14497a039ad..560f4525b6a 100644 --- a/common/autoconf/configure.ac +++ b/common/autoconf/configure.ac @@ -1,5 +1,5 @@ # -# Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -88,7 +88,6 @@ PLATFORM_SETUP_OPENJDK_BUILD_AND_TARGET # Continue setting up basic stuff. Most remaining code require fundamental tools. BASIC_SETUP_PATHS -BASIC_SETUP_LOGGING # Check if it's a pure open build or if custom sources are to be used. JDKOPT_SETUP_OPEN_OR_CUSTOM @@ -262,7 +261,7 @@ CUSTOM_LATE_HOOK # We're messing a bit with internal autoconf variables to put the config.status # in the output directory instead of the current directory. -CONFIG_STATUS="$OUTPUT_ROOT/config.status" +CONFIG_STATUS="$CONFIGURESUPPORT_OUTPUTDIR/config.status" # Create the actual output files. Now the main work of configure is done. AC_OUTPUT @@ -270,7 +269,7 @@ CUSTOM_CONFIG_OUTPUT_GENERATED_HOOK # Try to move the config.log file to the output directory. if test -e ./config.log; then - $MV -f ./config.log "$OUTPUT_ROOT/config.log" 2> /dev/null + $MV -f ./config.log "$CONFIGURESUPPORT_OUTPUTDIR/config.log" 2> /dev/null fi # Make the compare script executable diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index d7648b21e96..bc5063b9662 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -632,7 +632,6 @@ LIBOBJS CFLAGS_CCACHE CCACHE USE_PRECOMPILED_HEADER -SJAVAC_SERVER_DIR ENABLE_SJAVAC SJAVAC_SERVER_JAVA_FLAGS SJAVAC_SERVER_JAVA @@ -746,8 +745,6 @@ JT_HOME JTREGEXE USING_BROKEN_SUSE_LD PACKAGE_PATH -LDEXECXX -LDEXE USE_CLANG HOTSPOT_LD HOTSPOT_CXX @@ -884,6 +881,7 @@ CHECK_TOOLSDIR_GMAKE CHECK_MAKE CHECK_GMAKE PKGHANDLER +CONFIGURESUPPORT_OUTPUTDIR OUTPUT_ROOT CONF_NAME SPEC @@ -907,9 +905,8 @@ JVM_VARIANTS JVM_INTERPRETER JDK_VARIANT SET_OPENJDK -BUILD_LOG_WRAPPER -BUILD_LOG_PREVIOUS -BUILD_LOG +CANONICAL_TOPDIR +ORIGINAL_TOPDIR TOPDIR PATH_SEP ZERO_ARCHDEF @@ -3467,7 +3464,8 @@ ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. # Setup basic configuration paths, and platform-specific stuff related to PATHs. - +# Evaluates platform specific overrides for devkit variables. +# $1: Name of variable @@ -4294,8 +4292,8 @@ TOOLCHAIN_DESCRIPTION_xlc="IBM XL C/C++" # ################################################################################ - -VALID_VS_VERSIONS="2010 2012 2013" +# The order of these defines the priority by which we try to find them. +VALID_VS_VERSIONS="2013 2012 2010" VS_DESCRIPTION_2010="Microsoft Visual Studio 2010" VS_VERSION_INTERNAL_2010=100 @@ -4369,7 +4367,7 @@ VS_SDK_PLATFORM_NAME_2013= #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1426774983 +DATE_WHEN_GENERATED=1430331133 ############################################################################### # @@ -14141,6 +14139,10 @@ $as_echo_n "checking for top-level directory... " >&6; } $as_echo "$TOPDIR" >&6; } + # Save the original version of TOPDIR for string comparisons + ORIGINAL_TOPDIR="$TOPDIR" + + # We can only call BASIC_FIXUP_PATH after BASIC_CHECK_PATHS_WINDOWS. # Only process if variable expands to non-empty @@ -14184,7 +14186,7 @@ $as_echo "$as_me: The path of CURDIR, which resolves as \"$path\", is invalid." # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -14310,7 +14312,7 @@ $as_echo "$as_me: The path of TOPDIR, which resolves as \"$path\", is invalid." # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -14397,19 +14399,62 @@ $as_echo "$as_me: The path of TOPDIR, which resolves as \"$path\", is invalid." # SRC_ROOT is a traditional alias for TOPDIR. SRC_ROOT=$TOPDIR + # Calculate a canonical version of TOPDIR for string comparisons + CANONICAL_TOPDIR=$TOPDIR + + if test "x$OPENJDK_BUILD_OS" != xwindows; then + # Follow a chain of symbolic links. Use readlink + # where it exists, else fall back to horribly + # complicated shell code. + if test "x$READLINK_TESTED" != yes; then + # On MacOSX there is a readlink tool with a different + # purpose than the GNU readlink tool. Check the found readlink. + ISGNU=`$READLINK --version 2>&1 | $GREP GNU` + if test "x$ISGNU" = x; then + # A readlink that we do not know how to use. + # Are there other non-GNU readlinks out there? + READLINK_TESTED=yes + READLINK= + fi + fi + + if test "x$READLINK" != x; then + CANONICAL_TOPDIR=`$READLINK -f $CANONICAL_TOPDIR` + else + # Save the current directory for restoring afterwards + STARTDIR=$PWD + COUNTER=0 + sym_link_dir=`$DIRNAME $CANONICAL_TOPDIR` + sym_link_file=`$BASENAME $CANONICAL_TOPDIR` + cd $sym_link_dir + # Use -P flag to resolve symlinks in directories. + cd `$THEPWDCMD -P` + sym_link_dir=`$THEPWDCMD -P` + # Resolve file symlinks + while test $COUNTER -lt 20; do + ISLINK=`$LS -l $sym_link_dir/$sym_link_file | $GREP '\->' | $SED -e 's/.*-> \(.*\)/\1/'` + if test "x$ISLINK" == x; then + # This is not a symbolic link! We are done! + break + fi + # Again resolve directory symlinks since the target of the just found + # link could be in a different directory + cd `$DIRNAME $ISLINK` + sym_link_dir=`$THEPWDCMD -P` + sym_link_file=`$BASENAME $ISLINK` + let COUNTER=COUNTER+1 + done + cd $STARTDIR + CANONICAL_TOPDIR=$sym_link_dir/$sym_link_file + fi + fi + + + # Locate the directory of this script. AUTOCONF_DIR=$TOPDIR/common/autoconf - # Setup default logging of stdout and stderr to build.log in the output root. - BUILD_LOG='$(OUTPUT_ROOT)/build.log' - BUILD_LOG_PREVIOUS='$(OUTPUT_ROOT)/build.log.old' - BUILD_LOG_WRAPPER='$(BASH) $(SRC_ROOT)/common/bin/logger.sh $(BUILD_LOG)' - - - - - # Check if it's a pure open build or if custom sources are to be used. # Check whether --enable-openjdk-only was given. @@ -14837,7 +14882,7 @@ $as_echo "$as_me: The path of with_devkit, which resolves as \"$path\", is inval # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -14924,12 +14969,63 @@ $as_echo "$as_me: The path of with_devkit, which resolves as \"$path\", is inval DEVKIT_ROOT="$with_devkit" # Check for a meta data info file in the root of the devkit if test -f "$DEVKIT_ROOT/devkit.info"; then - # This potentially sets the following: - # DEVKIT_NAME: A descriptive name of the devkit - # DEVKIT_TOOLCHAIN_PATH: Corresponds to --with-toolchain-path - # DEVKIT_EXTRA_PATH: Corresponds to --with-extra-path - # DEVKIT_SYSROOT: Corresponds to --with-sysroot . $DEVKIT_ROOT/devkit.info + # This potentially sets the following: + # A descriptive name of the devkit + + if test "x$DEVKIT_NAME" = x; then + eval DEVKIT_NAME="\${DEVKIT_NAME_${OPENJDK_TARGET_CPU}}" + fi + + # Corresponds to --with-extra-path + + if test "x$DEVKIT_EXTRA_PATH" = x; then + eval DEVKIT_EXTRA_PATH="\${DEVKIT_EXTRA_PATH_${OPENJDK_TARGET_CPU}}" + fi + + # Corresponds to --with-toolchain-path + + if test "x$DEVKIT_TOOLCHAIN_PATH" = x; then + eval DEVKIT_TOOLCHAIN_PATH="\${DEVKIT_TOOLCHAIN_PATH_${OPENJDK_TARGET_CPU}}" + fi + + # Corresponds to --with-sysroot + + if test "x$DEVKIT_SYSROOT" = x; then + eval DEVKIT_SYSROOT="\${DEVKIT_SYSROOT_${OPENJDK_TARGET_CPU}}" + fi + + + # Identifies the Visual Studio version in the devkit + + if test "x$DEVKIT_VS_VERSION" = x; then + eval DEVKIT_VS_VERSION="\${DEVKIT_VS_VERSION_${OPENJDK_TARGET_CPU}}" + fi + + # The Visual Studio include environment variable + + if test "x$DEVKIT_VS_INCLUDE" = x; then + eval DEVKIT_VS_INCLUDE="\${DEVKIT_VS_INCLUDE_${OPENJDK_TARGET_CPU}}" + fi + + # The Visual Studio lib environment variable + + if test "x$DEVKIT_VS_LIB" = x; then + eval DEVKIT_VS_LIB="\${DEVKIT_VS_LIB_${OPENJDK_TARGET_CPU}}" + fi + + # Corresponds to --with-msvcr-dll + + if test "x$DEVKIT_MSVCR_DLL" = x; then + eval DEVKIT_MSVCR_DLL="\${DEVKIT_MSVCR_DLL_${OPENJDK_TARGET_CPU}}" + fi + + # Corresponds to --with-msvcp-dll + + if test "x$DEVKIT_MSVCP_DLL" = x; then + eval DEVKIT_MSVCP_DLL="\${DEVKIT_MSVCP_DLL_${OPENJDK_TARGET_CPU}}" + fi + fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for devkit" >&5 @@ -14942,7 +15038,6 @@ $as_echo "$DEVKIT_NAME in $DEVKIT_ROOT" >&6; } $as_echo "$DEVKIT_ROOT" >&6; } fi - if test "x$DEVKIT_EXTRA_PATH" != x; then if test "x$DEVKIT_EXTRA_PATH" != x; then if test "x$EXTRA_PATH" = x; then @@ -14952,7 +15047,6 @@ $as_echo "$DEVKIT_ROOT" >&6; } fi fi - fi # Fallback default of just /bin if DEVKIT_PATH is not defined if test "x$DEVKIT_TOOLCHAIN_PATH" = x; then @@ -15247,8 +15341,12 @@ $as_echo "in current directory" >&6; } files_present=`$LS $OUTPUT_ROOT` # Configure has already touched config.log and confdefs.h in the current dir when this check # is performed. - filtered_files=`$ECHO "$files_present" | $SED -e 's/config.log//g' -e 's/confdefs.h//g' -e 's/ //g' \ - | $TR -d '\n'` + filtered_files=`$ECHO "$files_present" \ + | $SED -e 's/config.log//g' \ + -e 's/confdefs.h//g' \ + -e 's/fixpath.exe//g' \ + -e 's/ //g' \ + | $TR -d '\n'` if test "x$filtered_files" != x; then { $as_echo "$as_me:${as_lineno-$LINENO}: Current directory is $CURDIR." >&5 $as_echo "$as_me: Current directory is $CURDIR." >&6;} @@ -15315,7 +15413,7 @@ $as_echo "$as_me: The path of OUTPUT_ROOT, which resolves as \"$path\", is inval # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -15400,6 +15498,9 @@ $as_echo "$as_me: The path of OUTPUT_ROOT, which resolves as \"$path\", is inval fi + CONFIGURESUPPORT_OUTPUTDIR="$OUTPUT_ROOT/configure-support" + $MKDIR -p "$CONFIGURESUPPORT_OUTPUTDIR" + SPEC=$OUTPUT_ROOT/spec.gmk CONF_NAME=$CONF_NAME @@ -15407,6 +15508,7 @@ $as_echo "$as_me: The path of OUTPUT_ROOT, which resolves as \"$path\", is inval OUTPUT_ROOT=$OUTPUT_ROOT + # The spec.gmk file contains all variables for the make system. ac_config_files="$ac_config_files $OUTPUT_ROOT/spec.gmk:$AUTOCONF_DIR/spec.gmk.in" @@ -15484,6 +15586,16 @@ done MAKE_CANDIDATE=""$MAKE"" DESCRIPTION="user supplied MAKE=$MAKE" + + # On Cygwin, we require a newer version of make than on other platforms + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + MAKE_VERSION_EXPR="-e 4\." + MAKE_REQUIRED_VERSION="4.0" + else + MAKE_VERSION_EXPR="-e 3\.8[12] -e 4\." + MAKE_REQUIRED_VERSION="3.81" + fi + if test "x$MAKE_CANDIDATE" != x; then { $as_echo "$as_me:${as_lineno-$LINENO}: Testing potential make at $MAKE_CANDIDATE, found using $DESCRIPTION" >&5 $as_echo "$as_me: Testing potential make at $MAKE_CANDIDATE, found using $DESCRIPTION" >&6;} @@ -15493,10 +15605,10 @@ $as_echo "$as_me: Testing potential make at $MAKE_CANDIDATE, found using $DESCRI { $as_echo "$as_me:${as_lineno-$LINENO}: Found potential make at $MAKE_CANDIDATE, however, this is not GNU Make. Ignoring." >&5 $as_echo "$as_me: Found potential make at $MAKE_CANDIDATE, however, this is not GNU Make. Ignoring." >&6;} else - IS_MODERN_MAKE=`$ECHO $MAKE_VERSION_STRING | $GREP -e '3\.8[12]' -e '4\.'` + IS_MODERN_MAKE=`$ECHO $MAKE_VERSION_STRING | $GREP $MAKE_VERSION_EXPR` if test "x$IS_MODERN_MAKE" = x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: Found GNU make at $MAKE_CANDIDATE, however this is not version 3.81 or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&5 -$as_echo "$as_me: Found GNU make at $MAKE_CANDIDATE, however this is not version 3.81 or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: Found GNU make at $MAKE_CANDIDATE, however this is not version $MAKE_REQUIRED_VERSION or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&5 +$as_echo "$as_me: Found GNU make at $MAKE_CANDIDATE, however this is not version $MAKE_REQUIRED_VERSION or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&6;} else if test "x$OPENJDK_BUILD_OS" = "xwindows"; then if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then @@ -15616,7 +15728,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -15809,7 +15921,7 @@ $as_echo "$as_me: Rewriting FOUND_MAKE to \"$new_complete\"" >&6;} fi if test "x$FOUND_MAKE" = x; then - as_fn_error $? "The specified make (by MAKE=$MAKE) is not GNU make 3.81 or newer." "$LINENO" 5 + as_fn_error $? "The specified make (by MAKE=$MAKE) is not GNU make $MAKE_REQUIRED_VERSION or newer." "$LINENO" 5 fi else # Try our hardest to locate a correct version of GNU make @@ -15861,6 +15973,16 @@ done MAKE_CANDIDATE=""$CHECK_GMAKE"" DESCRIPTION="gmake in PATH" + + # On Cygwin, we require a newer version of make than on other platforms + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + MAKE_VERSION_EXPR="-e 4\." + MAKE_REQUIRED_VERSION="4.0" + else + MAKE_VERSION_EXPR="-e 3\.8[12] -e 4\." + MAKE_REQUIRED_VERSION="3.81" + fi + if test "x$MAKE_CANDIDATE" != x; then { $as_echo "$as_me:${as_lineno-$LINENO}: Testing potential make at $MAKE_CANDIDATE, found using $DESCRIPTION" >&5 $as_echo "$as_me: Testing potential make at $MAKE_CANDIDATE, found using $DESCRIPTION" >&6;} @@ -15870,10 +15992,10 @@ $as_echo "$as_me: Testing potential make at $MAKE_CANDIDATE, found using $DESCRI { $as_echo "$as_me:${as_lineno-$LINENO}: Found potential make at $MAKE_CANDIDATE, however, this is not GNU Make. Ignoring." >&5 $as_echo "$as_me: Found potential make at $MAKE_CANDIDATE, however, this is not GNU Make. Ignoring." >&6;} else - IS_MODERN_MAKE=`$ECHO $MAKE_VERSION_STRING | $GREP -e '3\.8[12]' -e '4\.'` + IS_MODERN_MAKE=`$ECHO $MAKE_VERSION_STRING | $GREP $MAKE_VERSION_EXPR` if test "x$IS_MODERN_MAKE" = x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: Found GNU make at $MAKE_CANDIDATE, however this is not version 3.81 or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&5 -$as_echo "$as_me: Found GNU make at $MAKE_CANDIDATE, however this is not version 3.81 or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: Found GNU make at $MAKE_CANDIDATE, however this is not version $MAKE_REQUIRED_VERSION or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&5 +$as_echo "$as_me: Found GNU make at $MAKE_CANDIDATE, however this is not version $MAKE_REQUIRED_VERSION or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&6;} else if test "x$OPENJDK_BUILD_OS" = "xwindows"; then if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then @@ -15993,7 +16115,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -16235,6 +16357,16 @@ done MAKE_CANDIDATE=""$CHECK_MAKE"" DESCRIPTION="make in PATH" + + # On Cygwin, we require a newer version of make than on other platforms + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + MAKE_VERSION_EXPR="-e 4\." + MAKE_REQUIRED_VERSION="4.0" + else + MAKE_VERSION_EXPR="-e 3\.8[12] -e 4\." + MAKE_REQUIRED_VERSION="3.81" + fi + if test "x$MAKE_CANDIDATE" != x; then { $as_echo "$as_me:${as_lineno-$LINENO}: Testing potential make at $MAKE_CANDIDATE, found using $DESCRIPTION" >&5 $as_echo "$as_me: Testing potential make at $MAKE_CANDIDATE, found using $DESCRIPTION" >&6;} @@ -16244,10 +16376,10 @@ $as_echo "$as_me: Testing potential make at $MAKE_CANDIDATE, found using $DESCRI { $as_echo "$as_me:${as_lineno-$LINENO}: Found potential make at $MAKE_CANDIDATE, however, this is not GNU Make. Ignoring." >&5 $as_echo "$as_me: Found potential make at $MAKE_CANDIDATE, however, this is not GNU Make. Ignoring." >&6;} else - IS_MODERN_MAKE=`$ECHO $MAKE_VERSION_STRING | $GREP -e '3\.8[12]' -e '4\.'` + IS_MODERN_MAKE=`$ECHO $MAKE_VERSION_STRING | $GREP $MAKE_VERSION_EXPR` if test "x$IS_MODERN_MAKE" = x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: Found GNU make at $MAKE_CANDIDATE, however this is not version 3.81 or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&5 -$as_echo "$as_me: Found GNU make at $MAKE_CANDIDATE, however this is not version 3.81 or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: Found GNU make at $MAKE_CANDIDATE, however this is not version $MAKE_REQUIRED_VERSION or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&5 +$as_echo "$as_me: Found GNU make at $MAKE_CANDIDATE, however this is not version $MAKE_REQUIRED_VERSION or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&6;} else if test "x$OPENJDK_BUILD_OS" = "xwindows"; then if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then @@ -16367,7 +16499,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -16614,6 +16746,16 @@ done MAKE_CANDIDATE=""$CHECK_TOOLSDIR_GMAKE"" DESCRIPTION="gmake in tools-dir" + + # On Cygwin, we require a newer version of make than on other platforms + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + MAKE_VERSION_EXPR="-e 4\." + MAKE_REQUIRED_VERSION="4.0" + else + MAKE_VERSION_EXPR="-e 3\.8[12] -e 4\." + MAKE_REQUIRED_VERSION="3.81" + fi + if test "x$MAKE_CANDIDATE" != x; then { $as_echo "$as_me:${as_lineno-$LINENO}: Testing potential make at $MAKE_CANDIDATE, found using $DESCRIPTION" >&5 $as_echo "$as_me: Testing potential make at $MAKE_CANDIDATE, found using $DESCRIPTION" >&6;} @@ -16623,10 +16765,10 @@ $as_echo "$as_me: Testing potential make at $MAKE_CANDIDATE, found using $DESCRI { $as_echo "$as_me:${as_lineno-$LINENO}: Found potential make at $MAKE_CANDIDATE, however, this is not GNU Make. Ignoring." >&5 $as_echo "$as_me: Found potential make at $MAKE_CANDIDATE, however, this is not GNU Make. Ignoring." >&6;} else - IS_MODERN_MAKE=`$ECHO $MAKE_VERSION_STRING | $GREP -e '3\.8[12]' -e '4\.'` + IS_MODERN_MAKE=`$ECHO $MAKE_VERSION_STRING | $GREP $MAKE_VERSION_EXPR` if test "x$IS_MODERN_MAKE" = x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: Found GNU make at $MAKE_CANDIDATE, however this is not version 3.81 or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&5 -$as_echo "$as_me: Found GNU make at $MAKE_CANDIDATE, however this is not version 3.81 or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: Found GNU make at $MAKE_CANDIDATE, however this is not version $MAKE_REQUIRED_VERSION or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&5 +$as_echo "$as_me: Found GNU make at $MAKE_CANDIDATE, however this is not version $MAKE_REQUIRED_VERSION or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&6;} else if test "x$OPENJDK_BUILD_OS" = "xwindows"; then if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then @@ -16746,7 +16888,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -16987,6 +17129,16 @@ done MAKE_CANDIDATE=""$CHECK_TOOLSDIR_MAKE"" DESCRIPTION="make in tools-dir" + + # On Cygwin, we require a newer version of make than on other platforms + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + MAKE_VERSION_EXPR="-e 4\." + MAKE_REQUIRED_VERSION="4.0" + else + MAKE_VERSION_EXPR="-e 3\.8[12] -e 4\." + MAKE_REQUIRED_VERSION="3.81" + fi + if test "x$MAKE_CANDIDATE" != x; then { $as_echo "$as_me:${as_lineno-$LINENO}: Testing potential make at $MAKE_CANDIDATE, found using $DESCRIPTION" >&5 $as_echo "$as_me: Testing potential make at $MAKE_CANDIDATE, found using $DESCRIPTION" >&6;} @@ -16996,10 +17148,10 @@ $as_echo "$as_me: Testing potential make at $MAKE_CANDIDATE, found using $DESCRI { $as_echo "$as_me:${as_lineno-$LINENO}: Found potential make at $MAKE_CANDIDATE, however, this is not GNU Make. Ignoring." >&5 $as_echo "$as_me: Found potential make at $MAKE_CANDIDATE, however, this is not GNU Make. Ignoring." >&6;} else - IS_MODERN_MAKE=`$ECHO $MAKE_VERSION_STRING | $GREP -e '3\.8[12]' -e '4\.'` + IS_MODERN_MAKE=`$ECHO $MAKE_VERSION_STRING | $GREP $MAKE_VERSION_EXPR` if test "x$IS_MODERN_MAKE" = x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: Found GNU make at $MAKE_CANDIDATE, however this is not version 3.81 or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&5 -$as_echo "$as_me: Found GNU make at $MAKE_CANDIDATE, however this is not version 3.81 or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: Found GNU make at $MAKE_CANDIDATE, however this is not version $MAKE_REQUIRED_VERSION or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&5 +$as_echo "$as_me: Found GNU make at $MAKE_CANDIDATE, however this is not version $MAKE_REQUIRED_VERSION or later. (it is: $MAKE_VERSION_STRING). Ignoring." >&6;} else if test "x$OPENJDK_BUILD_OS" = "xwindows"; then if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then @@ -17119,7 +17271,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -17317,14 +17469,14 @@ $as_echo "$as_me: Rewriting FOUND_MAKE to \"$new_complete\"" >&6;} fi if test "x$FOUND_MAKE" = x; then - as_fn_error $? "Cannot find GNU make 3.81 or newer! Please put it in the path, or add e.g. MAKE=/opt/gmake3.81/make as argument to configure." "$LINENO" 5 + as_fn_error $? "Cannot find GNU make $MAKE_REQUIRED_VERSION or newer! Please put it in the path, or add e.g. MAKE=/opt/gmake3.81/make as argument to configure." "$LINENO" 5 fi fi MAKE=$FOUND_MAKE - { $as_echo "$as_me:${as_lineno-$LINENO}: Using GNU make 3.81 (or later) at $FOUND_MAKE (version: $MAKE_VERSION_STRING)" >&5 -$as_echo "$as_me: Using GNU make 3.81 (or later) at $FOUND_MAKE (version: $MAKE_VERSION_STRING)" >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: Using GNU make at $FOUND_MAKE (version: $MAKE_VERSION_STRING)" >&5 +$as_echo "$as_me: Using GNU make at $FOUND_MAKE (version: $MAKE_VERSION_STRING)" >&6;} # Check if make supports the output sync option and if so, setup using it. @@ -20184,7 +20336,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -20513,7 +20665,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -20704,7 +20856,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -20888,7 +21040,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -21071,7 +21223,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -21254,7 +21406,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -21428,7 +21580,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -21577,7 +21729,7 @@ $as_echo "$as_me: The path of JAVA_HOME_PROCESSED, which resolves as \"$path\", # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -21747,7 +21899,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -22072,7 +22224,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -22284,7 +22436,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -22461,7 +22613,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -22666,7 +22818,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -22843,7 +22995,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -23048,7 +23200,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -23225,7 +23377,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -23430,7 +23582,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -23607,7 +23759,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -23799,7 +23951,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -23974,7 +24126,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -24167,7 +24319,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -24342,7 +24494,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -24534,7 +24686,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -24709,7 +24861,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -24902,7 +25054,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -25077,7 +25229,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -25251,7 +25403,7 @@ $as_echo "$as_me: The path of BOOT_JDK, which resolves as \"$path\", is invalid. # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -26631,11 +26783,15 @@ ac_compiler_gnu=$ac_cv_cxx_compiler_gnu ORG_CFLAGS="$CFLAGS" ORG_CXXFLAGS="$CXXFLAGS" + # autoconf magic only relies on PATH, so update it if tools dir is specified + OLD_PATH="$PATH" + # On Windows, we need to detect the visual studio installation first. # This will change the PATH, but we need to keep that new PATH even # after toolchain detection is done, since the compiler (on x86) uses # it for DLL resolution in runtime. - if test "x$OPENJDK_BUILD_OS" = "xwindows" && test "x$TOOLCHAIN_TYPE" = "xmicrosoft"; then + if test "x$OPENJDK_BUILD_OS" = "xwindows" \ + && test "x$TOOLCHAIN_TYPE" = "xmicrosoft"; then # Store path to cygwin link.exe to help excluding it when searching for # VS linker. This must be done before changing the PATH when looking for VS. @@ -26713,6 +26869,56 @@ $as_echo "$as_me: The following toolchain versions are valid on this platform:" done exit 0 + elif test "x$DEVKIT_VS_VERSION" != x; then + VS_VERSION=$DEVKIT_VS_VERSION + TOOLCHAIN_VERSION=$VS_VERSION + eval VS_DESCRIPTION="\${VS_DESCRIPTION_${VS_VERSION}}" + eval VS_VERSION_INTERNAL="\${VS_VERSION_INTERNAL_${VS_VERSION}}" + eval MSVCR_NAME="\${VS_MSVCR_${VS_VERSION}}" + eval MSVCP_NAME="\${VS_MSVCP_${VS_VERSION}}" + eval PLATFORM_TOOLSET="\${VS_VS_PLATFORM_NAME_${VS_VERSION}}" + VS_PATH="$TOOLCHAIN_PATH:$PATH" + + # Convert DEVKIT_VS_INCLUDE into windows style VS_INCLUDE so that it + # can still be exported as INCLUDE for compiler invocations without + # SYSROOT_CFLAGS + OLDIFS="$IFS" + IFS=";" + for i in $DEVKIT_VS_INCLUDE; do + ipath=$i + + unix_path="$ipath" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + windows_path=`$CYGPATH -m "$unix_path"` + ipath="$windows_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + windows_path=`cmd //c echo $unix_path` + ipath="$windows_path" + fi + + VS_INCLUDE="$VS_INCLUDE;$ipath" + done + # Convert DEVKIT_VS_LIB into VS_LIB so that it can still be exported + # as LIB for compiler invocations without SYSROOT_LDFLAGS + for i in $DEVKIT_VS_LIB; do + libpath=$i + + unix_path="$libpath" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + windows_path=`$CYGPATH -m "$unix_path"` + libpath="$windows_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + windows_path=`cmd //c echo $unix_path` + libpath="$windows_path" + fi + + VS_LIB="$VS_LIB;$libpath" + done + IFS="$OLDIFS" + + { $as_echo "$as_me:${as_lineno-$LINENO}: Found devkit $VS_DESCRIPTION" >&5 +$as_echo "$as_me: Found devkit $VS_DESCRIPTION" >&6;} + elif test "x$with_toolchain_version" != x; then # User override; check that it is valid if test "x${VALID_VS_VERSIONS/$with_toolchain_version/}" = "x${VALID_VS_VERSIONS}"; then @@ -27285,8 +27491,10 @@ $as_echo "$as_me: Found $VS_DESCRIPTION" >&6;} done - if test "x$VS_ENV_CMD" != x; then - # We have found a Visual Studio environment on disk, let's extract variables from the vsvars bat file. + # If we have a devkit, skip all of the below. + if test "x$DEVKIT_VS_VERSION" = x; then + if test "x$VS_ENV_CMD" != x; then + # We have found a Visual Studio environment on disk, let's extract variables from the vsvars bat file. # Only process if variable expands to non-empty @@ -27386,7 +27594,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -27574,17 +27782,17 @@ $as_echo "$as_me: Rewriting VS_ENV_CMD to \"$new_complete\"" >&6;} fi - # Lets extract the variables that are set by vcvarsall.bat/vsvars32.bat/vsvars64.bat - { $as_echo "$as_me:${as_lineno-$LINENO}: Trying to extract Visual Studio environment variables" >&5 + # Lets extract the variables that are set by vcvarsall.bat/vsvars32.bat/vsvars64.bat + { $as_echo "$as_me:${as_lineno-$LINENO}: Trying to extract Visual Studio environment variables" >&5 $as_echo "$as_me: Trying to extract Visual Studio environment variables" >&6;} - # We need to create a couple of temporary files. - VS_ENV_TMP_DIR="$OUTPUT_ROOT/vs-env" - $MKDIR -p $VS_ENV_TMP_DIR + # We need to create a couple of temporary files. + VS_ENV_TMP_DIR="$CONFIGURESUPPORT_OUTPUTDIR/vs-env" + $MKDIR -p $VS_ENV_TMP_DIR - # Cannot use the VS10 setup script directly (since it only updates the DOS subshell environment). - # Instead create a shell script which will set the relevant variables when run. - WINPATH_VS_ENV_CMD="$VS_ENV_CMD" + # Cannot use the VS10 setup script directly (since it only updates the DOS subshell environment). + # Instead create a shell script which will set the relevant variables when run. + WINPATH_VS_ENV_CMD="$VS_ENV_CMD" unix_path="$WINPATH_VS_ENV_CMD" if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then @@ -27595,7 +27803,7 @@ $as_echo "$as_me: Trying to extract Visual Studio environment variables" >&6;} WINPATH_VS_ENV_CMD="$windows_path" fi - WINPATH_BASH="$BASH" + WINPATH_BASH="$BASH" unix_path="$WINPATH_BASH" if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then @@ -27607,59 +27815,67 @@ $as_echo "$as_me: Trying to extract Visual Studio environment variables" >&6;} fi - # Generate a DOS batch file which runs $VS_ENV_CMD, and then creates a shell - # script (executable by bash) that will setup the important variables. - EXTRACT_VC_ENV_BAT_FILE="$VS_ENV_TMP_DIR/extract-vs-env.bat" - $ECHO "@echo off" > $EXTRACT_VC_ENV_BAT_FILE - # This will end up something like: - # call C:/progra~2/micros~2.0/vc/bin/amd64/vcvars64.bat - $ECHO "call $WINPATH_VS_ENV_CMD $VS_ENV_ARGS" >> $EXTRACT_VC_ENV_BAT_FILE - # These will end up something like: - # C:/CygWin/bin/bash -c 'echo VS_PATH=\"$PATH\" > localdevenv.sh - # The trailing space for everyone except PATH is no typo, but is needed due - # to trailing \ in the Windows paths. These will be stripped later. - $ECHO "$WINPATH_BASH -c 'echo VS_PATH="'\"$PATH\" > set-vs-env.sh' >> $EXTRACT_VC_ENV_BAT_FILE - $ECHO "$WINPATH_BASH -c 'echo VS_INCLUDE="'\"$INCLUDE\;$include \" >> set-vs-env.sh' >> $EXTRACT_VC_ENV_BAT_FILE - $ECHO "$WINPATH_BASH -c 'echo VS_LIB="'\"$LIB\;$lib \" >> set-vs-env.sh' >> $EXTRACT_VC_ENV_BAT_FILE - $ECHO "$WINPATH_BASH -c 'echo VCINSTALLDIR="'\"$VCINSTALLDIR \" >> set-vs-env.sh' >> $EXTRACT_VC_ENV_BAT_FILE - $ECHO "$WINPATH_BASH -c 'echo WindowsSdkDir="'\"$WindowsSdkDir \" >> set-vs-env.sh' >> $EXTRACT_VC_ENV_BAT_FILE - $ECHO "$WINPATH_BASH -c 'echo WINDOWSSDKDIR="'\"$WINDOWSSDKDIR \" >> set-vs-env.sh' >> $EXTRACT_VC_ENV_BAT_FILE + # Generate a DOS batch file which runs $VS_ENV_CMD, and then creates a shell + # script (executable by bash) that will setup the important variables. + EXTRACT_VC_ENV_BAT_FILE="$VS_ENV_TMP_DIR/extract-vs-env.bat" + $ECHO "@echo off" > $EXTRACT_VC_ENV_BAT_FILE + # This will end up something like: + # call C:/progra~2/micros~2.0/vc/bin/amd64/vcvars64.bat + $ECHO "call $WINPATH_VS_ENV_CMD $VS_ENV_ARGS" >> $EXTRACT_VC_ENV_BAT_FILE + # These will end up something like: + # C:/CygWin/bin/bash -c 'echo VS_PATH=\"$PATH\" > localdevenv.sh + # The trailing space for everyone except PATH is no typo, but is needed due + # to trailing \ in the Windows paths. These will be stripped later. + $ECHO "$WINPATH_BASH -c 'echo VS_PATH="'\"$PATH\" > set-vs-env.sh' \ + >> $EXTRACT_VC_ENV_BAT_FILE + $ECHO "$WINPATH_BASH -c 'echo VS_INCLUDE="'\"$INCLUDE\;$include \" >> set-vs-env.sh' \ + >> $EXTRACT_VC_ENV_BAT_FILE + $ECHO "$WINPATH_BASH -c 'echo VS_LIB="'\"$LIB\;$lib \" >> set-vs-env.sh' \ + >> $EXTRACT_VC_ENV_BAT_FILE + $ECHO "$WINPATH_BASH -c 'echo VCINSTALLDIR="'\"$VCINSTALLDIR \" >> set-vs-env.sh' \ + >> $EXTRACT_VC_ENV_BAT_FILE + $ECHO "$WINPATH_BASH -c 'echo WindowsSdkDir="'\"$WindowsSdkDir \" >> set-vs-env.sh' \ + >> $EXTRACT_VC_ENV_BAT_FILE + $ECHO "$WINPATH_BASH -c 'echo WINDOWSSDKDIR="'\"$WINDOWSSDKDIR \" >> set-vs-env.sh' \ + >> $EXTRACT_VC_ENV_BAT_FILE - # Now execute the newly created bat file. - # The | cat is to stop SetEnv.Cmd to mess with system colors on msys. - # Change directory so we don't need to mess with Windows paths in redirects. - cd $VS_ENV_TMP_DIR - cmd /c extract-vs-env.bat | $CAT - cd $CURDIR + # Now execute the newly created bat file. + # The | cat is to stop SetEnv.Cmd to mess with system colors on msys. + # Change directory so we don't need to mess with Windows paths in redirects. + cd $VS_ENV_TMP_DIR + cmd /c extract-vs-env.bat | $CAT + cd $CURDIR - if test ! -s $VS_ENV_TMP_DIR/set-vs-env.sh; then - { $as_echo "$as_me:${as_lineno-$LINENO}: Could not succesfully extract the envionment variables needed for the VS setup." >&5 + if test ! -s $VS_ENV_TMP_DIR/set-vs-env.sh; then + { $as_echo "$as_me:${as_lineno-$LINENO}: Could not succesfully extract the envionment variables needed for the VS setup." >&5 $as_echo "$as_me: Could not succesfully extract the envionment variables needed for the VS setup." >&6;} - { $as_echo "$as_me:${as_lineno-$LINENO}: Try setting --with-tools-dir to the VC/bin directory within the VS installation" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: Try setting --with-tools-dir to the VC/bin directory within the VS installation" >&5 $as_echo "$as_me: Try setting --with-tools-dir to the VC/bin directory within the VS installation" >&6;} - { $as_echo "$as_me:${as_lineno-$LINENO}: or run \"bash.exe -l\" from a VS command prompt and then run configure from there." >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: or run \"bash.exe -l\" from a VS command prompt and then run configure from there." >&5 $as_echo "$as_me: or run \"bash.exe -l\" from a VS command prompt and then run configure from there." >&6;} - as_fn_error $? "Cannot continue" "$LINENO" 5 - fi + as_fn_error $? "Cannot continue" "$LINENO" 5 + fi - # Now set all paths and other env variables. This will allow the rest of - # the configure script to find and run the compiler in the proper way. - { $as_echo "$as_me:${as_lineno-$LINENO}: Setting extracted environment variables" >&5 + # Now set all paths and other env variables. This will allow the rest of + # the configure script to find and run the compiler in the proper way. + { $as_echo "$as_me:${as_lineno-$LINENO}: Setting extracted environment variables" >&5 $as_echo "$as_me: Setting extracted environment variables" >&6;} - . $VS_ENV_TMP_DIR/set-vs-env.sh - # Now we have VS_PATH, VS_INCLUDE, VS_LIB. For further checking, we - # also define VCINSTALLDIR, WindowsSdkDir and WINDOWSSDKDIR. - else - # We did not find a vsvars bat file, let's hope we are run from a VS command prompt. - { $as_echo "$as_me:${as_lineno-$LINENO}: Cannot locate a valid Visual Studio installation, checking current environment" >&5 + . $VS_ENV_TMP_DIR/set-vs-env.sh + # Now we have VS_PATH, VS_INCLUDE, VS_LIB. For further checking, we + # also define VCINSTALLDIR, WindowsSdkDir and WINDOWSSDKDIR. + else + # We did not find a vsvars bat file, let's hope we are run from a VS command prompt. + { $as_echo "$as_me:${as_lineno-$LINENO}: Cannot locate a valid Visual Studio installation, checking current environment" >&5 $as_echo "$as_me: Cannot locate a valid Visual Studio installation, checking current environment" >&6;} + fi fi # At this point, we should have correct variables in the environment, or we can't continue. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Visual Studio variables" >&5 $as_echo_n "checking for Visual Studio variables... " >&6; } - if test "x$VCINSTALLDIR" != x || test "x$WindowsSDKDir" != x || test "x$WINDOWSSDKDIR" != x; then + if test "x$VCINSTALLDIR" != x || test "x$WindowsSDKDir" != x \ + || test "x$WINDOWSSDKDIR" != x || test "x$DEVKIT_NAME" != x; then if test "x$VS_INCLUDE" = x || test "x$VS_LIB" = x; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: present but broken" >&5 $as_echo "present but broken" >&6; } @@ -27744,7 +27960,7 @@ $as_echo "$as_me: The path of ipath, which resolves as \"$path\", is invalid." > # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -27894,7 +28110,7 @@ $as_echo "$as_me: The path of libpath, which resolves as \"$path\", is invalid." # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -28013,9 +28229,6 @@ $as_echo "$as_me: or run \"bash.exe -l\" from a VS command prompt and then run c export LIB="$VS_LIB" fi - # autoconf magic only relies on PATH, so update it if tools dir is specified - OLD_PATH="$PATH" - # For solaris we really need solaris tools, and not the GNU equivalent. # The build tools on Solaris reside in /usr/ccs (C Compilation System), # so add that to path before starting to probe. @@ -28354,7 +28567,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -28815,7 +29028,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -30102,7 +30315,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -30563,7 +30776,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -31429,7 +31642,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -31848,7 +32061,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -32196,7 +32409,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -32695,7 +32908,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -33327,7 +33540,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -33802,7 +34015,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -34145,7 +34358,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -34486,7 +34699,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -34809,7 +35022,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -35328,7 +35541,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -35800,7 +36013,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -36272,7 +36485,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -36745,7 +36958,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -37329,7 +37542,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -37911,7 +38124,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -38502,7 +38715,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -39090,7 +39303,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -39586,7 +39799,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -40058,7 +40271,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -40530,7 +40743,7 @@ $as_echo "$as_me: Neither \"$new_path\" nor \"$new_path.exe/cmd\" can be found" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -40791,13 +41004,6 @@ $as_echo "$as_me: Rewriting BUILD_LD to \"$new_complete\"" >&6;} fi - # LDEXE is the linker to use, when creating executables. Not really used. - # FIXME: These should just be removed! - LDEXE="$LD" - LDEXECXX="$LDCXX" - - - @@ -41088,7 +41294,7 @@ $as_echo "$as_me: The path of JT_HOME, which resolves as \"$path\", is invalid." # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -43093,50 +43299,69 @@ $as_echo "no" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking if fixpath can be created" >&5 $as_echo_n "checking if fixpath can be created... " >&6; } FIXPATH_SRC="$SRC_ROOT/common/src/fixpath.c" - FIXPATH_BIN="$OUTPUT_ROOT/fixpath.exe" + FIXPATH_BIN="$CONFIGURESUPPORT_OUTPUTDIR/bin/fixpath.exe" + FIXPATH_DIR="$CONFIGURESUPPORT_OUTPUTDIR/fixpath" if test "x$OPENJDK_BUILD_OS_ENV" = xwindows.cygwin; then - FIXPATH_SRC=`$CYGPATH -m $FIXPATH_SRC` - FIXPATH_BIN=`$CYGPATH -m $FIXPATH_BIN` # Important to keep the .exe suffix on Cygwin for Hotspot makefiles - FIXPATH="$OUTPUT_ROOT/fixpath.exe -c" + FIXPATH="$FIXPATH_BIN -c" elif test "x$OPENJDK_BUILD_OS_ENV" = xwindows.msys; then - FIXPATH_SRC=`cmd //c echo $FIXPATH_SRC` - FIXPATH_BIN=`cmd //c echo $FIXPATH_BIN` - # Take all collected prefixes and turn them into a -m/c/foo@/c/bar@... command line # @ was chosen as separator to minimize risk of other tools messing around with it - all_unique_prefixes=`echo "${all_fixpath_prefixes[@]}" | tr ' ' '\n' | grep '^/./' | sort | uniq` + all_unique_prefixes=`echo "${all_fixpath_prefixes[@]}" \ + | tr ' ' '\n' | grep '^/./' | sort | uniq` fixpath_argument_list=`echo $all_unique_prefixes | tr ' ' '@'` - - FIXPATH="$OUTPUT_ROOT/fixpath -m$fixpath_argument_list" + FIXPATH="$FIXPATH_BIN -m$fixpath_argument_list" fi - rm -f $OUTPUT_ROOT/fixpath* - cd $OUTPUT_ROOT - $CC $FIXPATH_SRC -Fe$FIXPATH_BIN > $OUTPUT_ROOT/fixpath1.log 2>&1 + FIXPATH_SRC_W="$FIXPATH_SRC" + FIXPATH_BIN_W="$FIXPATH_BIN" + + unix_path="$FIXPATH_SRC_W" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + windows_path=`$CYGPATH -m "$unix_path"` + FIXPATH_SRC_W="$windows_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + windows_path=`cmd //c echo $unix_path` + FIXPATH_SRC_W="$windows_path" + fi + + + unix_path="$FIXPATH_BIN_W" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + windows_path=`$CYGPATH -m "$unix_path"` + FIXPATH_BIN_W="$windows_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + windows_path=`cmd //c echo $unix_path` + FIXPATH_BIN_W="$windows_path" + fi + + $RM -rf $FIXPATH_BIN $FIXPATH_DIR + $MKDIR -p $FIXPATH_DIR $CONFIGURESUPPORT_OUTPUTDIR/bin + cd $FIXPATH_DIR + $CC $FIXPATH_SRC_W -Fe$FIXPATH_BIN_W > $FIXPATH_DIR/fixpath1.log 2>&1 cd $CURDIR - if test ! -x $OUTPUT_ROOT/fixpath.exe; then + if test ! -x $FIXPATH_BIN; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } - cat $OUTPUT_ROOT/fixpath1.log - as_fn_error $? "Could not create $OUTPUT_ROOT/fixpath.exe" "$LINENO" 5 + cat $FIXPATH_DIR/fixpath1.log + as_fn_error $? "Could not create $FIXPATH_BIN" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking if fixpath.exe works" >&5 $as_echo_n "checking if fixpath.exe works... " >&6; } - cd $OUTPUT_ROOT - $FIXPATH $CC $SRC_ROOT/common/src/fixpath.c -Fe$OUTPUT_ROOT/fixpath2.exe > $OUTPUT_ROOT/fixpath2.log 2>&1 + cd $FIXPATH_DIR + $FIXPATH $CC $FIXPATH_SRC -Fe$FIXPATH_DIR/fixpath2.exe \ + > $FIXPATH_DIR/fixpath2.log 2>&1 cd $CURDIR - if test ! -x $OUTPUT_ROOT/fixpath2.exe; then + if test ! -x $FIXPATH_DIR/fixpath2.exe; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } - cat $OUTPUT_ROOT/fixpath2.log + cat $FIXPATH_DIR/fixpath2.log as_fn_error $? "fixpath did not work!" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } - rm -f $OUTPUT_ROOT/fixpath?.??? $OUTPUT_ROOT/fixpath.obj fi @@ -44623,7 +44848,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_INCLUDE_PATH, which resolves as # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -44749,7 +44974,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_LIB_PATH, which resolves as \"$ # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -44984,7 +45209,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_INCLUDE_PATH, which resolves as # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -45110,7 +45335,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_LIB_PATH, which resolves as \"$ # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -45606,7 +45831,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_INCLUDE_PATH, which resolves as # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -45732,7 +45957,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_LIB_PATH, which resolves as \"$ # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -45942,7 +46167,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_INCLUDE_PATH, which resolves as # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -46068,7 +46293,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_LIB_PATH, which resolves as \"$ # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -46269,7 +46494,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_INCLUDE_PATH, which resolves as # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -46395,7 +46620,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_LIB_PATH, which resolves as \"$ # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -46596,7 +46821,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_INCLUDE_PATH, which resolves as # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -46722,7 +46947,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_LIB_PATH, which resolves as \"$ # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -46924,7 +47149,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_INCLUDE_PATH, which resolves as # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -47050,7 +47275,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_LIB_PATH, which resolves as \"$ # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -47253,7 +47478,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_INCLUDE_PATH, which resolves as # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -47379,7 +47604,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_LIB_PATH, which resolves as \"$ # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -47578,7 +47803,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_INCLUDE_PATH, which resolves as # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -47704,7 +47929,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_LIB_PATH, which resolves as \"$ # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -47903,7 +48128,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_INCLUDE_PATH, which resolves as # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -48029,7 +48254,7 @@ $as_echo "$as_me: The path of POTENTIAL_FREETYPE_LIB_PATH, which resolves as \"$ # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -48211,7 +48436,7 @@ $as_echo "$as_me: The path of FREETYPE_INCLUDE_PATH, which resolves as \"$path\" # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -48345,7 +48570,7 @@ $as_echo "$as_me: The path of FREETYPE_LIB_PATH, which resolves as \"$path\", is # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -49860,7 +50085,7 @@ fi if test "x$with_msvcr_dll" != x; then # If given explicitely by user, do not probe. If not present, fail directly. - DLL_NAME="$DLL_NAME" + DLL_NAME="$MSVCR_NAME" POSSIBLE_MSVC_DLL="$with_msvcr_dll" METHOD="--with-msvcr-dll" if test -n "$POSSIBLE_MSVC_DLL" -a -e "$POSSIBLE_MSVC_DLL"; then @@ -49890,6 +50115,132 @@ $as_echo_n "checking found $DLL_NAME architecture... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } MSVC_DLL="$POSSIBLE_MSVC_DLL" + + # Only process if variable expands to non-empty + + if test "x$MSVC_DLL" != x; then + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + + # Input might be given as Windows format, start by converting to + # unix format. + path="$MSVC_DLL" + new_path=`$CYGPATH -u "$path"` + + # Cygwin tries to hide some aspects of the Windows file system, such that binaries are + # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered + # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then + # "foo.exe" is OK but "foo" is an error. + # + # This test is therefore slightly more accurate than "test -f" to check for file precense. + # It is also a way to make sure we got the proper file name for the real test later on. + test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` + if test "x$test_shortpath" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 + fi + + # Call helper function which possibly converts this using DOS-style short mode. + # If so, the updated path is stored in $new_path. + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + shortmode_path=`$CYGPATH -s -m -a "$input_path"` + path_after_shortmode=`$CYGPATH -u "$shortmode_path"` + if test "x$path_after_shortmode" != "x$input_to_shortpath"; then + # Going to short mode and back again did indeed matter. Since short mode is + # case insensitive, let's make it lowercase to improve readability. + shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Now convert it back to Unix-style (cygpath) + input_path=`$CYGPATH -u "$shortmode_path"` + new_path="$input_path" + fi + fi + + test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/` + if test "x$test_cygdrive_prefix" = x; then + # As a simple fix, exclude /usr/bin since it's not a real path. + if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then + # The path is in a Cygwin special directory (e.g. /home). We need this converted to + # a path prefixed by /cygdrive for fixpath to work. + new_path="$CYGWIN_ROOT_PATH$input_path" + fi + fi + + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + + path="$MSVC_DLL" + has_colon=`$ECHO $path | $GREP ^.:` + new_path="$path" + if test "x$has_colon" = x; then + # Not in mixed or Windows style, start by that. + new_path=`cmd //c echo $path` + fi + + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + fi + + + windows_path="$new_path" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + unix_path=`$CYGPATH -u "$windows_path"` + new_path="$unix_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'` + new_path="$unix_path" + fi + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + # Save the first 10 bytes of this path to the storage, so fixpath can work. + all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}") + + else + # We're on a unix platform. Hooray! :) + path="$MSVC_DLL" + has_space=`$ECHO "$path" | $GREP " "` + if test "x$has_space" != x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 + fi + + # Use eval to expand a potential ~ + eval path="$path" + if test ! -f "$path" && test ! -d "$path"; then + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + fi + + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" + fi + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 $as_echo_n "checking for $DLL_NAME... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 @@ -49905,9 +50256,183 @@ $as_echo "$as_me: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" if test "x$MSVC_DLL" = x; then as_fn_error $? "Could not find a proper $MSVCR_NAME as specified by --with-msvcr-dll" "$LINENO" 5 fi + MSVCR_DLL="$MSVC_DLL" + elif test "x$DEVKIT_MSVCR_DLL" != x; then + + DLL_NAME="$MSVCR_NAME" + POSSIBLE_MSVC_DLL="$DEVKIT_MSVCR_DLL" + METHOD="devkit" + if test -n "$POSSIBLE_MSVC_DLL" -a -e "$POSSIBLE_MSVC_DLL"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: Found $DLL_NAME at $POSSIBLE_MSVC_DLL using $METHOD" >&5 +$as_echo "$as_me: Found $DLL_NAME at $POSSIBLE_MSVC_DLL using $METHOD" >&6;} + + # Need to check if the found msvcr is correct architecture + { $as_echo "$as_me:${as_lineno-$LINENO}: checking found $DLL_NAME architecture" >&5 +$as_echo_n "checking found $DLL_NAME architecture... " >&6; } + MSVC_DLL_FILETYPE=`$FILE -b "$POSSIBLE_MSVC_DLL"` + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + # The MSYS 'file' command returns "PE32 executable for MS Windows (DLL) (GUI) Intel 80386 32-bit" + # on x32 and "PE32+ executable for MS Windows (DLL) (GUI) Mono/.Net assembly" on x64 systems. + if test "x$OPENJDK_TARGET_CPU_BITS" = x32; then + CORRECT_MSVCR_ARCH="PE32 executable" + else + CORRECT_MSVCR_ARCH="PE32+ executable" + fi + else + if test "x$OPENJDK_TARGET_CPU_BITS" = x32; then + CORRECT_MSVCR_ARCH=386 + else + CORRECT_MSVCR_ARCH=x86-64 + fi + fi + if $ECHO "$MSVC_DLL_FILETYPE" | $GREP "$CORRECT_MSVCR_ARCH" 2>&1 > /dev/null; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 +$as_echo "ok" >&6; } + MSVC_DLL="$POSSIBLE_MSVC_DLL" + + # Only process if variable expands to non-empty + + if test "x$MSVC_DLL" != x; then + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + + # Input might be given as Windows format, start by converting to + # unix format. + path="$MSVC_DLL" + new_path=`$CYGPATH -u "$path"` + + # Cygwin tries to hide some aspects of the Windows file system, such that binaries are + # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered + # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then + # "foo.exe" is OK but "foo" is an error. + # + # This test is therefore slightly more accurate than "test -f" to check for file precense. + # It is also a way to make sure we got the proper file name for the real test later on. + test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` + if test "x$test_shortpath" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 + fi + + # Call helper function which possibly converts this using DOS-style short mode. + # If so, the updated path is stored in $new_path. + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + shortmode_path=`$CYGPATH -s -m -a "$input_path"` + path_after_shortmode=`$CYGPATH -u "$shortmode_path"` + if test "x$path_after_shortmode" != "x$input_to_shortpath"; then + # Going to short mode and back again did indeed matter. Since short mode is + # case insensitive, let's make it lowercase to improve readability. + shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Now convert it back to Unix-style (cygpath) + input_path=`$CYGPATH -u "$shortmode_path"` + new_path="$input_path" + fi + fi + + test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/` + if test "x$test_cygdrive_prefix" = x; then + # As a simple fix, exclude /usr/bin since it's not a real path. + if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then + # The path is in a Cygwin special directory (e.g. /home). We need this converted to + # a path prefixed by /cygdrive for fixpath to work. + new_path="$CYGWIN_ROOT_PATH$input_path" + fi + fi + + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + + path="$MSVC_DLL" + has_colon=`$ECHO $path | $GREP ^.:` + new_path="$path" + if test "x$has_colon" = x; then + # Not in mixed or Windows style, start by that. + new_path=`cmd //c echo $path` + fi + + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + fi + + + windows_path="$new_path" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + unix_path=`$CYGPATH -u "$windows_path"` + new_path="$unix_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'` + new_path="$unix_path" + fi + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + # Save the first 10 bytes of this path to the storage, so fixpath can work. + all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}") + + else + # We're on a unix platform. Hooray! :) + path="$MSVC_DLL" + has_space=`$ECHO "$path" | $GREP " "` + if test "x$has_space" != x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 + fi + + # Use eval to expand a potential ~ + eval path="$path" + if test ! -f "$path" && test ! -d "$path"; then + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + fi + + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" + fi + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 +$as_echo_n "checking for $DLL_NAME... " >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 +$as_echo "$MSVC_DLL" >&6; } + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: incorrect, ignoring" >&5 +$as_echo "incorrect, ignoring" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" >&5 +$as_echo "$as_me: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" >&6;} + fi + fi + + if test "x$MSVC_DLL" = x; then + as_fn_error $? "Could not find a proper $MSVCR_NAME as specified by devkit" "$LINENO" 5 + fi + MSVCR_DLL="$MSVC_DLL" else - VAR_NAME="MSVCR_DLL" DLL_NAME="${MSVCR_NAME}" MSVC_DLL= @@ -49962,6 +50487,132 @@ $as_echo_n "checking found $DLL_NAME architecture... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } MSVC_DLL="$POSSIBLE_MSVC_DLL" + + # Only process if variable expands to non-empty + + if test "x$MSVC_DLL" != x; then + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + + # Input might be given as Windows format, start by converting to + # unix format. + path="$MSVC_DLL" + new_path=`$CYGPATH -u "$path"` + + # Cygwin tries to hide some aspects of the Windows file system, such that binaries are + # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered + # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then + # "foo.exe" is OK but "foo" is an error. + # + # This test is therefore slightly more accurate than "test -f" to check for file precense. + # It is also a way to make sure we got the proper file name for the real test later on. + test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` + if test "x$test_shortpath" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 + fi + + # Call helper function which possibly converts this using DOS-style short mode. + # If so, the updated path is stored in $new_path. + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + shortmode_path=`$CYGPATH -s -m -a "$input_path"` + path_after_shortmode=`$CYGPATH -u "$shortmode_path"` + if test "x$path_after_shortmode" != "x$input_to_shortpath"; then + # Going to short mode and back again did indeed matter. Since short mode is + # case insensitive, let's make it lowercase to improve readability. + shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Now convert it back to Unix-style (cygpath) + input_path=`$CYGPATH -u "$shortmode_path"` + new_path="$input_path" + fi + fi + + test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/` + if test "x$test_cygdrive_prefix" = x; then + # As a simple fix, exclude /usr/bin since it's not a real path. + if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then + # The path is in a Cygwin special directory (e.g. /home). We need this converted to + # a path prefixed by /cygdrive for fixpath to work. + new_path="$CYGWIN_ROOT_PATH$input_path" + fi + fi + + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + + path="$MSVC_DLL" + has_colon=`$ECHO $path | $GREP ^.:` + new_path="$path" + if test "x$has_colon" = x; then + # Not in mixed or Windows style, start by that. + new_path=`cmd //c echo $path` + fi + + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + fi + + + windows_path="$new_path" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + unix_path=`$CYGPATH -u "$windows_path"` + new_path="$unix_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'` + new_path="$unix_path" + fi + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + # Save the first 10 bytes of this path to the storage, so fixpath can work. + all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}") + + else + # We're on a unix platform. Hooray! :) + path="$MSVC_DLL" + has_space=`$ECHO "$path" | $GREP " "` + if test "x$has_space" != x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 + fi + + # Use eval to expand a potential ~ + eval path="$path" + if test ! -f "$path" && test ! -d "$path"; then + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + fi + + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" + fi + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 $as_echo_n "checking for $DLL_NAME... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 @@ -50011,6 +50662,132 @@ $as_echo_n "checking found $DLL_NAME architecture... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } MSVC_DLL="$POSSIBLE_MSVC_DLL" + + # Only process if variable expands to non-empty + + if test "x$MSVC_DLL" != x; then + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + + # Input might be given as Windows format, start by converting to + # unix format. + path="$MSVC_DLL" + new_path=`$CYGPATH -u "$path"` + + # Cygwin tries to hide some aspects of the Windows file system, such that binaries are + # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered + # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then + # "foo.exe" is OK but "foo" is an error. + # + # This test is therefore slightly more accurate than "test -f" to check for file precense. + # It is also a way to make sure we got the proper file name for the real test later on. + test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` + if test "x$test_shortpath" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 + fi + + # Call helper function which possibly converts this using DOS-style short mode. + # If so, the updated path is stored in $new_path. + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + shortmode_path=`$CYGPATH -s -m -a "$input_path"` + path_after_shortmode=`$CYGPATH -u "$shortmode_path"` + if test "x$path_after_shortmode" != "x$input_to_shortpath"; then + # Going to short mode and back again did indeed matter. Since short mode is + # case insensitive, let's make it lowercase to improve readability. + shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Now convert it back to Unix-style (cygpath) + input_path=`$CYGPATH -u "$shortmode_path"` + new_path="$input_path" + fi + fi + + test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/` + if test "x$test_cygdrive_prefix" = x; then + # As a simple fix, exclude /usr/bin since it's not a real path. + if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then + # The path is in a Cygwin special directory (e.g. /home). We need this converted to + # a path prefixed by /cygdrive for fixpath to work. + new_path="$CYGWIN_ROOT_PATH$input_path" + fi + fi + + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + + path="$MSVC_DLL" + has_colon=`$ECHO $path | $GREP ^.:` + new_path="$path" + if test "x$has_colon" = x; then + # Not in mixed or Windows style, start by that. + new_path=`cmd //c echo $path` + fi + + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + fi + + + windows_path="$new_path" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + unix_path=`$CYGPATH -u "$windows_path"` + new_path="$unix_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'` + new_path="$unix_path" + fi + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + # Save the first 10 bytes of this path to the storage, so fixpath can work. + all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}") + + else + # We're on a unix platform. Hooray! :) + path="$MSVC_DLL" + has_space=`$ECHO "$path" | $GREP " "` + if test "x$has_space" != x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 + fi + + # Use eval to expand a potential ~ + eval path="$path" + if test ! -f "$path" && test ! -d "$path"; then + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + fi + + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" + fi + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 $as_echo_n "checking for $DLL_NAME... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 @@ -50070,6 +50847,132 @@ $as_echo_n "checking found $DLL_NAME architecture... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } MSVC_DLL="$POSSIBLE_MSVC_DLL" + + # Only process if variable expands to non-empty + + if test "x$MSVC_DLL" != x; then + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + + # Input might be given as Windows format, start by converting to + # unix format. + path="$MSVC_DLL" + new_path=`$CYGPATH -u "$path"` + + # Cygwin tries to hide some aspects of the Windows file system, such that binaries are + # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered + # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then + # "foo.exe" is OK but "foo" is an error. + # + # This test is therefore slightly more accurate than "test -f" to check for file precense. + # It is also a way to make sure we got the proper file name for the real test later on. + test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` + if test "x$test_shortpath" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 + fi + + # Call helper function which possibly converts this using DOS-style short mode. + # If so, the updated path is stored in $new_path. + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + shortmode_path=`$CYGPATH -s -m -a "$input_path"` + path_after_shortmode=`$CYGPATH -u "$shortmode_path"` + if test "x$path_after_shortmode" != "x$input_to_shortpath"; then + # Going to short mode and back again did indeed matter. Since short mode is + # case insensitive, let's make it lowercase to improve readability. + shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Now convert it back to Unix-style (cygpath) + input_path=`$CYGPATH -u "$shortmode_path"` + new_path="$input_path" + fi + fi + + test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/` + if test "x$test_cygdrive_prefix" = x; then + # As a simple fix, exclude /usr/bin since it's not a real path. + if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then + # The path is in a Cygwin special directory (e.g. /home). We need this converted to + # a path prefixed by /cygdrive for fixpath to work. + new_path="$CYGWIN_ROOT_PATH$input_path" + fi + fi + + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + + path="$MSVC_DLL" + has_colon=`$ECHO $path | $GREP ^.:` + new_path="$path" + if test "x$has_colon" = x; then + # Not in mixed or Windows style, start by that. + new_path=`cmd //c echo $path` + fi + + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + fi + + + windows_path="$new_path" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + unix_path=`$CYGPATH -u "$windows_path"` + new_path="$unix_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'` + new_path="$unix_path" + fi + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + # Save the first 10 bytes of this path to the storage, so fixpath can work. + all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}") + + else + # We're on a unix platform. Hooray! :) + path="$MSVC_DLL" + has_space=`$ECHO "$path" | $GREP " "` + if test "x$has_space" != x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 + fi + + # Use eval to expand a potential ~ + eval path="$path" + if test ! -f "$path" && test ! -d "$path"; then + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + fi + + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" + fi + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 $as_echo_n "checking for $DLL_NAME... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 @@ -50136,6 +51039,132 @@ $as_echo_n "checking found $DLL_NAME architecture... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } MSVC_DLL="$POSSIBLE_MSVC_DLL" + + # Only process if variable expands to non-empty + + if test "x$MSVC_DLL" != x; then + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + + # Input might be given as Windows format, start by converting to + # unix format. + path="$MSVC_DLL" + new_path=`$CYGPATH -u "$path"` + + # Cygwin tries to hide some aspects of the Windows file system, such that binaries are + # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered + # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then + # "foo.exe" is OK but "foo" is an error. + # + # This test is therefore slightly more accurate than "test -f" to check for file precense. + # It is also a way to make sure we got the proper file name for the real test later on. + test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` + if test "x$test_shortpath" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 + fi + + # Call helper function which possibly converts this using DOS-style short mode. + # If so, the updated path is stored in $new_path. + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + shortmode_path=`$CYGPATH -s -m -a "$input_path"` + path_after_shortmode=`$CYGPATH -u "$shortmode_path"` + if test "x$path_after_shortmode" != "x$input_to_shortpath"; then + # Going to short mode and back again did indeed matter. Since short mode is + # case insensitive, let's make it lowercase to improve readability. + shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Now convert it back to Unix-style (cygpath) + input_path=`$CYGPATH -u "$shortmode_path"` + new_path="$input_path" + fi + fi + + test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/` + if test "x$test_cygdrive_prefix" = x; then + # As a simple fix, exclude /usr/bin since it's not a real path. + if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then + # The path is in a Cygwin special directory (e.g. /home). We need this converted to + # a path prefixed by /cygdrive for fixpath to work. + new_path="$CYGWIN_ROOT_PATH$input_path" + fi + fi + + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + + path="$MSVC_DLL" + has_colon=`$ECHO $path | $GREP ^.:` + new_path="$path" + if test "x$has_colon" = x; then + # Not in mixed or Windows style, start by that. + new_path=`cmd //c echo $path` + fi + + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + fi + + + windows_path="$new_path" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + unix_path=`$CYGPATH -u "$windows_path"` + new_path="$unix_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'` + new_path="$unix_path" + fi + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + # Save the first 10 bytes of this path to the storage, so fixpath can work. + all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}") + + else + # We're on a unix platform. Hooray! :) + path="$MSVC_DLL" + has_space=`$ECHO "$path" | $GREP " "` + if test "x$has_space" != x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 + fi + + # Use eval to expand a potential ~ + eval path="$path" + if test ! -f "$path" && test ! -d "$path"; then + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + fi + + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" + fi + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 $as_echo_n "checking for $DLL_NAME... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 @@ -50199,39 +51228,15 @@ $as_echo_n "checking found $DLL_NAME architecture... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } MSVC_DLL="$POSSIBLE_MSVC_DLL" - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 -$as_echo_n "checking for $DLL_NAME... " >&6; } - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 -$as_echo "$MSVC_DLL" >&6; } - else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: incorrect, ignoring" >&5 -$as_echo "incorrect, ignoring" >&6; } - { $as_echo "$as_me:${as_lineno-$LINENO}: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" >&5 -$as_echo "$as_me: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" >&6;} - fi - fi - - fi - fi - - if test "x$MSVC_DLL" = x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 -$as_echo_n "checking for $DLL_NAME... " >&6; } - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } - as_fn_error $? "Could not find $DLL_NAME. Please specify using --with-msvcr-dll." "$LINENO" 5 - fi - - MSVCR_DLL=$MSVC_DLL # Only process if variable expands to non-empty - if test "x$MSVCR_DLL" != x; then + if test "x$MSVC_DLL" != x; then if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then # Input might be given as Windows format, start by converting to # unix format. - path="$MSVCR_DLL" + path="$MSVC_DLL" new_path=`$CYGPATH -u "$path"` # Cygwin tries to hide some aspects of the Windows file system, such that binaries are @@ -50243,9 +51248,9 @@ $as_echo "no" >&6; } # It is also a way to make sure we got the proper file name for the real test later on. test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` if test "x$test_shortpath" = x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVCR_DLL, which resolves as \"$path\", is invalid." >&5 -$as_echo "$as_me: The path of MSVCR_DLL, which resolves as \"$path\", is invalid." >&6;} - as_fn_error $? "Cannot locate the the path of MSVCR_DLL" "$LINENO" 5 + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 fi # Call helper function which possibly converts this using DOS-style short mode. @@ -50265,7 +51270,7 @@ $as_echo "$as_me: The path of MSVCR_DLL, which resolves as \"$path\", is invalid # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -50283,14 +51288,14 @@ $as_echo "$as_me: The path of MSVCR_DLL, which resolves as \"$path\", is invalid if test "x$path" != "x$new_path"; then - MSVCR_DLL="$new_path" - { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVCR_DLL to \"$new_path\"" >&5 -$as_echo "$as_me: Rewriting MSVCR_DLL to \"$new_path\"" >&6;} + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} fi elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then - path="$MSVCR_DLL" + path="$MSVC_DLL" has_colon=`$ECHO $path | $GREP ^.:` new_path="$path" if test "x$has_colon" = x; then @@ -50321,9 +51326,9 @@ $as_echo "$as_me: Rewriting MSVCR_DLL to \"$new_path\"" >&6;} fi if test "x$path" != "x$new_path"; then - MSVCR_DLL="$new_path" - { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVCR_DLL to \"$new_path\"" >&5 -$as_echo "$as_me: Rewriting MSVCR_DLL to \"$new_path\"" >&6;} + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} fi # Save the first 10 bytes of this path to the storage, so fixpath can work. @@ -50331,29 +51336,51 @@ $as_echo "$as_me: Rewriting MSVCR_DLL to \"$new_path\"" >&6;} else # We're on a unix platform. Hooray! :) - path="$MSVCR_DLL" + path="$MSVC_DLL" has_space=`$ECHO "$path" | $GREP " "` if test "x$has_space" != x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVCR_DLL, which resolves as \"$path\", is invalid." >&5 -$as_echo "$as_me: The path of MSVCR_DLL, which resolves as \"$path\", is invalid." >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 fi # Use eval to expand a potential ~ eval path="$path" if test ! -f "$path" && test ! -d "$path"; then - as_fn_error $? "The path of MSVCR_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 fi - MSVCR_DLL="`cd "$path"; $THEPWDCMD -L`" + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" fi fi - MSVCR_DLL=$MSVCR_DLL - - + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 +$as_echo_n "checking for $DLL_NAME... " >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 +$as_echo "$MSVC_DLL" >&6; } + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: incorrect, ignoring" >&5 +$as_echo "incorrect, ignoring" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" >&5 +$as_echo "$as_me: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" >&6;} + fi fi + fi + fi + + if test "x$MSVC_DLL" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 +$as_echo_n "checking for $DLL_NAME... " >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + as_fn_error $? "Could not find $DLL_NAME. Please specify using --with-msvcr-dll." "$LINENO" 5 + fi + + MSVCR_DLL="$MSVC_DLL" + fi + + # Check whether --with-msvcp-dll was given. if test "${with_msvcp_dll+set}" = set; then : @@ -50365,7 +51392,7 @@ fi if test "x$with_msvcp_dll" != x; then # If given explicitely by user, do not probe. If not present, fail directly. - DLL_NAME="$DLL_NAME" + DLL_NAME="$MSVCP_NAME" POSSIBLE_MSVC_DLL="$with_msvcp_dll" METHOD="--with-msvcp-dll" if test -n "$POSSIBLE_MSVC_DLL" -a -e "$POSSIBLE_MSVC_DLL"; then @@ -50395,6 +51422,132 @@ $as_echo_n "checking found $DLL_NAME architecture... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } MSVC_DLL="$POSSIBLE_MSVC_DLL" + + # Only process if variable expands to non-empty + + if test "x$MSVC_DLL" != x; then + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + + # Input might be given as Windows format, start by converting to + # unix format. + path="$MSVC_DLL" + new_path=`$CYGPATH -u "$path"` + + # Cygwin tries to hide some aspects of the Windows file system, such that binaries are + # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered + # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then + # "foo.exe" is OK but "foo" is an error. + # + # This test is therefore slightly more accurate than "test -f" to check for file precense. + # It is also a way to make sure we got the proper file name for the real test later on. + test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` + if test "x$test_shortpath" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 + fi + + # Call helper function which possibly converts this using DOS-style short mode. + # If so, the updated path is stored in $new_path. + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + shortmode_path=`$CYGPATH -s -m -a "$input_path"` + path_after_shortmode=`$CYGPATH -u "$shortmode_path"` + if test "x$path_after_shortmode" != "x$input_to_shortpath"; then + # Going to short mode and back again did indeed matter. Since short mode is + # case insensitive, let's make it lowercase to improve readability. + shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Now convert it back to Unix-style (cygpath) + input_path=`$CYGPATH -u "$shortmode_path"` + new_path="$input_path" + fi + fi + + test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/` + if test "x$test_cygdrive_prefix" = x; then + # As a simple fix, exclude /usr/bin since it's not a real path. + if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then + # The path is in a Cygwin special directory (e.g. /home). We need this converted to + # a path prefixed by /cygdrive for fixpath to work. + new_path="$CYGWIN_ROOT_PATH$input_path" + fi + fi + + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + + path="$MSVC_DLL" + has_colon=`$ECHO $path | $GREP ^.:` + new_path="$path" + if test "x$has_colon" = x; then + # Not in mixed or Windows style, start by that. + new_path=`cmd //c echo $path` + fi + + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + fi + + + windows_path="$new_path" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + unix_path=`$CYGPATH -u "$windows_path"` + new_path="$unix_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'` + new_path="$unix_path" + fi + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + # Save the first 10 bytes of this path to the storage, so fixpath can work. + all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}") + + else + # We're on a unix platform. Hooray! :) + path="$MSVC_DLL" + has_space=`$ECHO "$path" | $GREP " "` + if test "x$has_space" != x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 + fi + + # Use eval to expand a potential ~ + eval path="$path" + if test ! -f "$path" && test ! -d "$path"; then + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + fi + + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" + fi + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 $as_echo_n "checking for $DLL_NAME... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 @@ -50410,9 +51563,183 @@ $as_echo "$as_me: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" if test "x$MSVC_DLL" = x; then as_fn_error $? "Could not find a proper $MSVCP_NAME as specified by --with-msvcp-dll" "$LINENO" 5 fi + MSVCP_DLL="$MSVC_DLL" + elif test "x$DEVKIT_MSVCP_DLL" != x; then + + DLL_NAME="$MSVCP_NAME" + POSSIBLE_MSVC_DLL="$DEVKIT_MSVCP_DLL" + METHOD="devkit" + if test -n "$POSSIBLE_MSVC_DLL" -a -e "$POSSIBLE_MSVC_DLL"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: Found $DLL_NAME at $POSSIBLE_MSVC_DLL using $METHOD" >&5 +$as_echo "$as_me: Found $DLL_NAME at $POSSIBLE_MSVC_DLL using $METHOD" >&6;} + + # Need to check if the found msvcr is correct architecture + { $as_echo "$as_me:${as_lineno-$LINENO}: checking found $DLL_NAME architecture" >&5 +$as_echo_n "checking found $DLL_NAME architecture... " >&6; } + MSVC_DLL_FILETYPE=`$FILE -b "$POSSIBLE_MSVC_DLL"` + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + # The MSYS 'file' command returns "PE32 executable for MS Windows (DLL) (GUI) Intel 80386 32-bit" + # on x32 and "PE32+ executable for MS Windows (DLL) (GUI) Mono/.Net assembly" on x64 systems. + if test "x$OPENJDK_TARGET_CPU_BITS" = x32; then + CORRECT_MSVCR_ARCH="PE32 executable" + else + CORRECT_MSVCR_ARCH="PE32+ executable" + fi + else + if test "x$OPENJDK_TARGET_CPU_BITS" = x32; then + CORRECT_MSVCR_ARCH=386 + else + CORRECT_MSVCR_ARCH=x86-64 + fi + fi + if $ECHO "$MSVC_DLL_FILETYPE" | $GREP "$CORRECT_MSVCR_ARCH" 2>&1 > /dev/null; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 +$as_echo "ok" >&6; } + MSVC_DLL="$POSSIBLE_MSVC_DLL" + + # Only process if variable expands to non-empty + + if test "x$MSVC_DLL" != x; then + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + + # Input might be given as Windows format, start by converting to + # unix format. + path="$MSVC_DLL" + new_path=`$CYGPATH -u "$path"` + + # Cygwin tries to hide some aspects of the Windows file system, such that binaries are + # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered + # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then + # "foo.exe" is OK but "foo" is an error. + # + # This test is therefore slightly more accurate than "test -f" to check for file precense. + # It is also a way to make sure we got the proper file name for the real test later on. + test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` + if test "x$test_shortpath" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 + fi + + # Call helper function which possibly converts this using DOS-style short mode. + # If so, the updated path is stored in $new_path. + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + shortmode_path=`$CYGPATH -s -m -a "$input_path"` + path_after_shortmode=`$CYGPATH -u "$shortmode_path"` + if test "x$path_after_shortmode" != "x$input_to_shortpath"; then + # Going to short mode and back again did indeed matter. Since short mode is + # case insensitive, let's make it lowercase to improve readability. + shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Now convert it back to Unix-style (cygpath) + input_path=`$CYGPATH -u "$shortmode_path"` + new_path="$input_path" + fi + fi + + test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/` + if test "x$test_cygdrive_prefix" = x; then + # As a simple fix, exclude /usr/bin since it's not a real path. + if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then + # The path is in a Cygwin special directory (e.g. /home). We need this converted to + # a path prefixed by /cygdrive for fixpath to work. + new_path="$CYGWIN_ROOT_PATH$input_path" + fi + fi + + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + + path="$MSVC_DLL" + has_colon=`$ECHO $path | $GREP ^.:` + new_path="$path" + if test "x$has_colon" = x; then + # Not in mixed or Windows style, start by that. + new_path=`cmd //c echo $path` + fi + + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + fi + + + windows_path="$new_path" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + unix_path=`$CYGPATH -u "$windows_path"` + new_path="$unix_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'` + new_path="$unix_path" + fi + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + # Save the first 10 bytes of this path to the storage, so fixpath can work. + all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}") + + else + # We're on a unix platform. Hooray! :) + path="$MSVC_DLL" + has_space=`$ECHO "$path" | $GREP " "` + if test "x$has_space" != x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 + fi + + # Use eval to expand a potential ~ + eval path="$path" + if test ! -f "$path" && test ! -d "$path"; then + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + fi + + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" + fi + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 +$as_echo_n "checking for $DLL_NAME... " >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 +$as_echo "$MSVC_DLL" >&6; } + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: incorrect, ignoring" >&5 +$as_echo "incorrect, ignoring" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" >&5 +$as_echo "$as_me: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" >&6;} + fi + fi + + if test "x$MSVC_DLL" = x; then + as_fn_error $? "Could not find a proper $MSVCP_NAME as specified by devkit" "$LINENO" 5 + fi + MSVCP_DLL="$MSVC_DLL" else - VAR_NAME="MSVCP_DLL" DLL_NAME="${MSVCP_NAME}" MSVC_DLL= @@ -50467,6 +51794,132 @@ $as_echo_n "checking found $DLL_NAME architecture... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } MSVC_DLL="$POSSIBLE_MSVC_DLL" + + # Only process if variable expands to non-empty + + if test "x$MSVC_DLL" != x; then + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + + # Input might be given as Windows format, start by converting to + # unix format. + path="$MSVC_DLL" + new_path=`$CYGPATH -u "$path"` + + # Cygwin tries to hide some aspects of the Windows file system, such that binaries are + # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered + # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then + # "foo.exe" is OK but "foo" is an error. + # + # This test is therefore slightly more accurate than "test -f" to check for file precense. + # It is also a way to make sure we got the proper file name for the real test later on. + test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` + if test "x$test_shortpath" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 + fi + + # Call helper function which possibly converts this using DOS-style short mode. + # If so, the updated path is stored in $new_path. + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + shortmode_path=`$CYGPATH -s -m -a "$input_path"` + path_after_shortmode=`$CYGPATH -u "$shortmode_path"` + if test "x$path_after_shortmode" != "x$input_to_shortpath"; then + # Going to short mode and back again did indeed matter. Since short mode is + # case insensitive, let's make it lowercase to improve readability. + shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Now convert it back to Unix-style (cygpath) + input_path=`$CYGPATH -u "$shortmode_path"` + new_path="$input_path" + fi + fi + + test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/` + if test "x$test_cygdrive_prefix" = x; then + # As a simple fix, exclude /usr/bin since it's not a real path. + if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then + # The path is in a Cygwin special directory (e.g. /home). We need this converted to + # a path prefixed by /cygdrive for fixpath to work. + new_path="$CYGWIN_ROOT_PATH$input_path" + fi + fi + + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + + path="$MSVC_DLL" + has_colon=`$ECHO $path | $GREP ^.:` + new_path="$path" + if test "x$has_colon" = x; then + # Not in mixed or Windows style, start by that. + new_path=`cmd //c echo $path` + fi + + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + fi + + + windows_path="$new_path" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + unix_path=`$CYGPATH -u "$windows_path"` + new_path="$unix_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'` + new_path="$unix_path" + fi + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + # Save the first 10 bytes of this path to the storage, so fixpath can work. + all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}") + + else + # We're on a unix platform. Hooray! :) + path="$MSVC_DLL" + has_space=`$ECHO "$path" | $GREP " "` + if test "x$has_space" != x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 + fi + + # Use eval to expand a potential ~ + eval path="$path" + if test ! -f "$path" && test ! -d "$path"; then + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + fi + + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" + fi + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 $as_echo_n "checking for $DLL_NAME... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 @@ -50516,6 +51969,132 @@ $as_echo_n "checking found $DLL_NAME architecture... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } MSVC_DLL="$POSSIBLE_MSVC_DLL" + + # Only process if variable expands to non-empty + + if test "x$MSVC_DLL" != x; then + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + + # Input might be given as Windows format, start by converting to + # unix format. + path="$MSVC_DLL" + new_path=`$CYGPATH -u "$path"` + + # Cygwin tries to hide some aspects of the Windows file system, such that binaries are + # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered + # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then + # "foo.exe" is OK but "foo" is an error. + # + # This test is therefore slightly more accurate than "test -f" to check for file precense. + # It is also a way to make sure we got the proper file name for the real test later on. + test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` + if test "x$test_shortpath" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 + fi + + # Call helper function which possibly converts this using DOS-style short mode. + # If so, the updated path is stored in $new_path. + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + shortmode_path=`$CYGPATH -s -m -a "$input_path"` + path_after_shortmode=`$CYGPATH -u "$shortmode_path"` + if test "x$path_after_shortmode" != "x$input_to_shortpath"; then + # Going to short mode and back again did indeed matter. Since short mode is + # case insensitive, let's make it lowercase to improve readability. + shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Now convert it back to Unix-style (cygpath) + input_path=`$CYGPATH -u "$shortmode_path"` + new_path="$input_path" + fi + fi + + test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/` + if test "x$test_cygdrive_prefix" = x; then + # As a simple fix, exclude /usr/bin since it's not a real path. + if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then + # The path is in a Cygwin special directory (e.g. /home). We need this converted to + # a path prefixed by /cygdrive for fixpath to work. + new_path="$CYGWIN_ROOT_PATH$input_path" + fi + fi + + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + + path="$MSVC_DLL" + has_colon=`$ECHO $path | $GREP ^.:` + new_path="$path" + if test "x$has_colon" = x; then + # Not in mixed or Windows style, start by that. + new_path=`cmd //c echo $path` + fi + + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + fi + + + windows_path="$new_path" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + unix_path=`$CYGPATH -u "$windows_path"` + new_path="$unix_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'` + new_path="$unix_path" + fi + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + # Save the first 10 bytes of this path to the storage, so fixpath can work. + all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}") + + else + # We're on a unix platform. Hooray! :) + path="$MSVC_DLL" + has_space=`$ECHO "$path" | $GREP " "` + if test "x$has_space" != x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 + fi + + # Use eval to expand a potential ~ + eval path="$path" + if test ! -f "$path" && test ! -d "$path"; then + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + fi + + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" + fi + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 $as_echo_n "checking for $DLL_NAME... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 @@ -50575,6 +52154,132 @@ $as_echo_n "checking found $DLL_NAME architecture... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } MSVC_DLL="$POSSIBLE_MSVC_DLL" + + # Only process if variable expands to non-empty + + if test "x$MSVC_DLL" != x; then + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + + # Input might be given as Windows format, start by converting to + # unix format. + path="$MSVC_DLL" + new_path=`$CYGPATH -u "$path"` + + # Cygwin tries to hide some aspects of the Windows file system, such that binaries are + # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered + # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then + # "foo.exe" is OK but "foo" is an error. + # + # This test is therefore slightly more accurate than "test -f" to check for file precense. + # It is also a way to make sure we got the proper file name for the real test later on. + test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` + if test "x$test_shortpath" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 + fi + + # Call helper function which possibly converts this using DOS-style short mode. + # If so, the updated path is stored in $new_path. + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + shortmode_path=`$CYGPATH -s -m -a "$input_path"` + path_after_shortmode=`$CYGPATH -u "$shortmode_path"` + if test "x$path_after_shortmode" != "x$input_to_shortpath"; then + # Going to short mode and back again did indeed matter. Since short mode is + # case insensitive, let's make it lowercase to improve readability. + shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Now convert it back to Unix-style (cygpath) + input_path=`$CYGPATH -u "$shortmode_path"` + new_path="$input_path" + fi + fi + + test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/` + if test "x$test_cygdrive_prefix" = x; then + # As a simple fix, exclude /usr/bin since it's not a real path. + if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then + # The path is in a Cygwin special directory (e.g. /home). We need this converted to + # a path prefixed by /cygdrive for fixpath to work. + new_path="$CYGWIN_ROOT_PATH$input_path" + fi + fi + + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + + path="$MSVC_DLL" + has_colon=`$ECHO $path | $GREP ^.:` + new_path="$path" + if test "x$has_colon" = x; then + # Not in mixed or Windows style, start by that. + new_path=`cmd //c echo $path` + fi + + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + fi + + + windows_path="$new_path" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + unix_path=`$CYGPATH -u "$windows_path"` + new_path="$unix_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'` + new_path="$unix_path" + fi + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + # Save the first 10 bytes of this path to the storage, so fixpath can work. + all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}") + + else + # We're on a unix platform. Hooray! :) + path="$MSVC_DLL" + has_space=`$ECHO "$path" | $GREP " "` + if test "x$has_space" != x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 + fi + + # Use eval to expand a potential ~ + eval path="$path" + if test ! -f "$path" && test ! -d "$path"; then + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + fi + + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" + fi + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 $as_echo_n "checking for $DLL_NAME... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 @@ -50641,6 +52346,132 @@ $as_echo_n "checking found $DLL_NAME architecture... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } MSVC_DLL="$POSSIBLE_MSVC_DLL" + + # Only process if variable expands to non-empty + + if test "x$MSVC_DLL" != x; then + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + + # Input might be given as Windows format, start by converting to + # unix format. + path="$MSVC_DLL" + new_path=`$CYGPATH -u "$path"` + + # Cygwin tries to hide some aspects of the Windows file system, such that binaries are + # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered + # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then + # "foo.exe" is OK but "foo" is an error. + # + # This test is therefore slightly more accurate than "test -f" to check for file precense. + # It is also a way to make sure we got the proper file name for the real test later on. + test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` + if test "x$test_shortpath" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 + fi + + # Call helper function which possibly converts this using DOS-style short mode. + # If so, the updated path is stored in $new_path. + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + shortmode_path=`$CYGPATH -s -m -a "$input_path"` + path_after_shortmode=`$CYGPATH -u "$shortmode_path"` + if test "x$path_after_shortmode" != "x$input_to_shortpath"; then + # Going to short mode and back again did indeed matter. Since short mode is + # case insensitive, let's make it lowercase to improve readability. + shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + # Now convert it back to Unix-style (cygpath) + input_path=`$CYGPATH -u "$shortmode_path"` + new_path="$input_path" + fi + fi + + test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/` + if test "x$test_cygdrive_prefix" = x; then + # As a simple fix, exclude /usr/bin since it's not a real path. + if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then + # The path is in a Cygwin special directory (e.g. /home). We need this converted to + # a path prefixed by /cygdrive for fixpath to work. + new_path="$CYGWIN_ROOT_PATH$input_path" + fi + fi + + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + + path="$MSVC_DLL" + has_colon=`$ECHO $path | $GREP ^.:` + new_path="$path" + if test "x$has_colon" = x; then + # Not in mixed or Windows style, start by that. + new_path=`cmd //c echo $path` + fi + + + input_path="$new_path" + # Check if we need to convert this using DOS-style short mode. If the path + # contains just simple characters, use it. Otherwise (spaces, weird characters), + # take no chances and rewrite it. + # Note: m4 eats our [], so we need to use [ and ] instead. + has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]` + if test "x$has_forbidden_chars" != x; then + # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \) + new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + fi + + + windows_path="$new_path" + if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then + unix_path=`$CYGPATH -u "$windows_path"` + new_path="$unix_path" + elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then + unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'` + new_path="$unix_path" + fi + + if test "x$path" != "x$new_path"; then + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} + fi + + # Save the first 10 bytes of this path to the storage, so fixpath can work. + all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}") + + else + # We're on a unix platform. Hooray! :) + path="$MSVC_DLL" + has_space=`$ECHO "$path" | $GREP " "` + if test "x$has_space" != x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 + fi + + # Use eval to expand a potential ~ + eval path="$path" + if test ! -f "$path" && test ! -d "$path"; then + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + fi + + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" + fi + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 $as_echo_n "checking for $DLL_NAME... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 @@ -50704,39 +52535,15 @@ $as_echo_n "checking found $DLL_NAME architecture... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } MSVC_DLL="$POSSIBLE_MSVC_DLL" - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 -$as_echo_n "checking for $DLL_NAME... " >&6; } - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 -$as_echo "$MSVC_DLL" >&6; } - else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: incorrect, ignoring" >&5 -$as_echo "incorrect, ignoring" >&6; } - { $as_echo "$as_me:${as_lineno-$LINENO}: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" >&5 -$as_echo "$as_me: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" >&6;} - fi - fi - - fi - fi - - if test "x$MSVC_DLL" = x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 -$as_echo_n "checking for $DLL_NAME... " >&6; } - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } - as_fn_error $? "Could not find $DLL_NAME. Please specify using --with-msvcr-dll." "$LINENO" 5 - fi - - MSVCP_DLL=$MSVC_DLL # Only process if variable expands to non-empty - if test "x$MSVCP_DLL" != x; then + if test "x$MSVC_DLL" != x; then if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then # Input might be given as Windows format, start by converting to # unix format. - path="$MSVCP_DLL" + path="$MSVC_DLL" new_path=`$CYGPATH -u "$path"` # Cygwin tries to hide some aspects of the Windows file system, such that binaries are @@ -50748,9 +52555,9 @@ $as_echo "no" >&6; } # It is also a way to make sure we got the proper file name for the real test later on. test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null` if test "x$test_shortpath" = x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVCP_DLL, which resolves as \"$path\", is invalid." >&5 -$as_echo "$as_me: The path of MSVCP_DLL, which resolves as \"$path\", is invalid." >&6;} - as_fn_error $? "Cannot locate the the path of MSVCP_DLL" "$LINENO" 5 + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} + as_fn_error $? "Cannot locate the the path of MSVC_DLL" "$LINENO" 5 fi # Call helper function which possibly converts this using DOS-style short mode. @@ -50770,7 +52577,7 @@ $as_echo "$as_me: The path of MSVCP_DLL, which resolves as \"$path\", is invalid # Going to short mode and back again did indeed matter. Since short mode is # case insensitive, let's make it lowercase to improve readability. shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Now convert it back to Unix-stile (cygpath) + # Now convert it back to Unix-style (cygpath) input_path=`$CYGPATH -u "$shortmode_path"` new_path="$input_path" fi @@ -50788,14 +52595,14 @@ $as_echo "$as_me: The path of MSVCP_DLL, which resolves as \"$path\", is invalid if test "x$path" != "x$new_path"; then - MSVCP_DLL="$new_path" - { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVCP_DLL to \"$new_path\"" >&5 -$as_echo "$as_me: Rewriting MSVCP_DLL to \"$new_path\"" >&6;} + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} fi elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then - path="$MSVCP_DLL" + path="$MSVC_DLL" has_colon=`$ECHO $path | $GREP ^.:` new_path="$path" if test "x$has_colon" = x; then @@ -50826,9 +52633,9 @@ $as_echo "$as_me: Rewriting MSVCP_DLL to \"$new_path\"" >&6;} fi if test "x$path" != "x$new_path"; then - MSVCP_DLL="$new_path" - { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVCP_DLL to \"$new_path\"" >&5 -$as_echo "$as_me: Rewriting MSVCP_DLL to \"$new_path\"" >&6;} + MSVC_DLL="$new_path" + { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting MSVC_DLL to \"$new_path\"" >&5 +$as_echo "$as_me: Rewriting MSVC_DLL to \"$new_path\"" >&6;} fi # Save the first 10 bytes of this path to the storage, so fixpath can work. @@ -50836,30 +52643,52 @@ $as_echo "$as_me: Rewriting MSVCP_DLL to \"$new_path\"" >&6;} else # We're on a unix platform. Hooray! :) - path="$MSVCP_DLL" + path="$MSVC_DLL" has_space=`$ECHO "$path" | $GREP " "` if test "x$has_space" != x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVCP_DLL, which resolves as \"$path\", is invalid." >&5 -$as_echo "$as_me: The path of MSVCP_DLL, which resolves as \"$path\", is invalid." >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&5 +$as_echo "$as_me: The path of MSVC_DLL, which resolves as \"$path\", is invalid." >&6;} as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5 fi # Use eval to expand a potential ~ eval path="$path" if test ! -f "$path" && test ! -d "$path"; then - as_fn_error $? "The path of MSVCP_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 + as_fn_error $? "The path of MSVC_DLL, which resolves as \"$path\", is not found." "$LINENO" 5 fi - MSVCP_DLL="`cd "$path"; $THEPWDCMD -L`" + MSVC_DLL="`cd "$path"; $THEPWDCMD -L`" fi fi - MSVCP_DLL=$MSVCP_DLL - + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 +$as_echo_n "checking for $DLL_NAME... " >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MSVC_DLL" >&5 +$as_echo "$MSVC_DLL" >&6; } + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: incorrect, ignoring" >&5 +$as_echo "incorrect, ignoring" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" >&5 +$as_echo "$as_me: The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE" >&6;} + fi + fi fi fi + if test "x$MSVC_DLL" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $DLL_NAME" >&5 +$as_echo_n "checking for $DLL_NAME... " >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + as_fn_error $? "Could not find $DLL_NAME. Please specify using --with-msvcr-dll." "$LINENO" 5 + fi + + MSVCP_DLL="$MSVC_DLL" + fi + + fi + # Check whether --with-dxsdk was given. @@ -51372,13 +53201,6 @@ $as_echo_n "checking whether to use sjavac... " >&6; } $as_echo "$ENABLE_SJAVAC" >&6; } - if test "x$ENABLE_SJAVAC" = xyes; then - SJAVAC_SERVER_DIR="$OUTPUT_ROOT/javacservers" - else - SJAVAC_SERVER_DIR= - fi - - # Can the C/C++ compiler use precompiled headers? @@ -51806,7 +53628,7 @@ $as_echo "$OUTPUT_DIR_IS_LOCAL" >&6; } # We're messing a bit with internal autoconf variables to put the config.status # in the output directory instead of the current directory. -CONFIG_STATUS="$OUTPUT_ROOT/config.status" +CONFIG_STATUS="$CONFIGURESUPPORT_OUTPUTDIR/config.status" # Create the actual output files. Now the main work of configure is done. cat >confcache <<\_ACEOF @@ -52974,7 +54796,7 @@ fi # Try to move the config.log file to the output directory. if test -e ./config.log; then - $MV -f ./config.log "$OUTPUT_ROOT/config.log" 2> /dev/null + $MV -f ./config.log "$CONFIGURESUPPORT_OUTPUTDIR/config.log" 2> /dev/null fi # Make the compare script executable diff --git a/common/autoconf/spec.gmk.in b/common/autoconf/spec.gmk.in index d21ab83451a..d9c172dc964 100644 --- a/common/autoconf/spec.gmk.in +++ b/common/autoconf/spec.gmk.in @@ -55,25 +55,12 @@ CONFIGURE_COMMAND_LINE:=@CONFIGURE_COMMAND_LINE@ # A self-referential reference to this file. SPEC:=@SPEC@ -# Specify where the spec file is. -MAKE_ARGS="SPEC=$(SPEC)" +# What make to use for main processing, after bootstrapping top-level Makefile. +MAKE := @MAKE@ -MAKE:=@MAKE@ - -# Pass along the verbosity and log level settings. -ifeq (,$(findstring VERBOSE=,$(MAKE))) - MAKE:=$(MAKE) $(VERBOSE) VERBOSE="$(VERBOSE)" LOG_LEVEL="$(LOG_LEVEL)" -endif - -# No implicit variables or rules! -ifeq (,$(findstring -R,$(MAKE))) - MAKE:=$(MAKE) -R -endif - -# Specify where the common include directory for makefiles is. -ifeq (,$(findstring -I @TOPDIR@/make/common,$(MAKE))) - MAKE:=$(MAKE) -I @TOPDIR@/make/common -endif +# The default make arguments +MAKE_ARGS = $(MAKE_LOG_FLAGS) -r -R -I $(TOPDIR)/make/common SPEC=$(SPEC) \ + MAKE_LOG_FLAGS="$(MAKE_LOG_FLAGS)" LOG_LEVEL=$(LOG_LEVEL) OUTPUT_SYNC_SUPPORTED:=@OUTPUT_SYNC_SUPPORTED@ OUTPUT_SYNC:=@OUTPUT_SYNC@ @@ -146,6 +133,9 @@ OVERRIDE_SRC_ROOT:=@OVERRIDE_SRC_ROOT@ # The top-level directory of the forest (SRC_ROOT is a traditional alias) TOPDIR:=@TOPDIR@ +# These two versions of TOPDIR are used in string comparisons +ORIGINAL_TOPDIR:=@ORIGINAL_TOPDIR@ +CANONICAL_TOPDIR:=@CANONICAL_TOPDIR@ SRC_ROOT:=@TOPDIR@ OUTPUT_ROOT:=@OUTPUT_ROOT@ @@ -192,6 +182,7 @@ else FULL_VERSION=$(RELEASE)-$(JDK_BUILD_NUMBER) endif JRE_RELEASE_VERSION:=$(FULL_VERSION) +JDK_VERSION_FOR_MANIFEST := $(JDK_MINOR_VERSION).$(JDK_MICRO_VERSION).$(if $(JDK_UPDATE_VERSION),$(JDK_UPDATE_VERSION),0).$(COOKED_BUILD_NUMBER) # How to compile the code: release, fastdebug or slowdebug DEBUG_LEVEL:=@DEBUG_LEVEL@ @@ -241,13 +232,14 @@ BUILD_OUTPUT:=@BUILD_OUTPUT@ # Colon left out to be able to override IMAGES_OUTPUTDIR for bootcycle-images SUPPORT_OUTPUTDIR=$(BUILD_OUTPUT)/support BUILDTOOLS_OUTPUTDIR=$(BUILD_OUTPUT)/buildtools -MAKESUPPORT_OUTPUTDIR=$(BUILD_OUTPUT)/makesupport HOTSPOT_OUTPUTDIR=$(BUILD_OUTPUT)/hotspot JDK_OUTPUTDIR=$(BUILD_OUTPUT)/jdk IMAGES_OUTPUTDIR=$(BUILD_OUTPUT)/images TESTMAKE_OUTPUTDIR=$(BUILD_OUTPUT)/test-make MAKESUPPORT_OUTPUTDIR=$(BUILD_OUTPUT)/make-support +# This does not get overridden in a bootcycle build +CONFIGURESUPPORT_OUTPUTDIR:=@CONFIGURESUPPORT_OUTPUTDIR@ HOTSPOT_DIST=@HOTSPOT_DIST@ @@ -269,7 +261,7 @@ MEMORY_SIZE:=@MEMORY_SIZE@ ENABLE_SJAVAC:=@ENABLE_SJAVAC@ # Store sjavac server synchronization files here, and # the sjavac server log files. -SJAVAC_SERVER_DIR:=@SJAVAC_SERVER_DIR@ +SJAVAC_SERVER_DIR=$(MAKESUPPORT_OUTPUTDIR)/javacservers # Number of parallel jobs to use for compilation JOBS?=@JOBS@ @@ -363,10 +355,6 @@ USING_BROKEN_SUSE_LD:=@USING_BROKEN_SUSE_LD@ LDFLAGS_JDKLIB:=@LDFLAGS_JDKLIB@ LDFLAGS_JDKLIB_SUFFIX:=@LDFLAGS_JDKLIB_SUFFIX@ -# On some platforms the linker cannot be used to create executables, thus -# the need for a separate LDEXE command. -LDEXE:=@FIXPATH@ @LDEXE@ - # LDFLAGS used to link the jdk native launchers (C-code) LDFLAGS_JDKEXE:=@LDFLAGS_JDKEXE@ LDFLAGS_JDKEXE_SUFFIX:=@LDFLAGS_JDKEXE_SUFFIX@ @@ -379,9 +367,6 @@ LDCXX:=@FIXPATH@ @LDCXX@ # The flags for linking libstdc++ linker. LIBCXX:=@LIBCXX@ -# Sometimes a different linker is needed for c++ executables -LDEXECXX:=@FIXPATH@ @LDEXECXX@ - # Compiler and linker flags used when building native tests CFLAGS_TESTLIB:=@CFLAGS_TESTLIB@ CXXFLAGS_TESTLIB:=@CXXFLAGS_TESTLIB@ @@ -573,18 +558,6 @@ JTREGEXE:=@JTREGEXE@ XCODEBUILD=@XCODEBUILD@ FIXPATH:=@FIXPATH@ -# Where the build output is stored for your convenience. -BUILD_LOG:=@BUILD_LOG@ -BUILD_LOG_PREVIOUS:=@BUILD_LOG_PREVIOUS@ -# Disable the build log wrapper on sjavac+windows until -# we have solved how to prevent the log wrapper to wait -# for the background sjavac server process. -ifeq (@ENABLE_SJAVAC@X@OPENJDK_BUILD_OS@,yesXwindows) - BUILD_LOG_WRAPPER:= -else - BUILD_LOG_WRAPPER:=@BUILD_LOG_WRAPPER@ -endif - # Build setup ENABLE_JFR=@ENABLE_JFR@ ENABLE_INTREE_EC=@ENABLE_INTREE_EC@ diff --git a/common/autoconf/toolchain.m4 b/common/autoconf/toolchain.m4 index 7737ef8adf2..4a3c6426273 100644 --- a/common/autoconf/toolchain.m4 +++ b/common/autoconf/toolchain.m4 @@ -189,11 +189,15 @@ AC_DEFUN_ONCE([TOOLCHAIN_PRE_DETECTION], ORG_CFLAGS="$CFLAGS" ORG_CXXFLAGS="$CXXFLAGS" + # autoconf magic only relies on PATH, so update it if tools dir is specified + OLD_PATH="$PATH" + # On Windows, we need to detect the visual studio installation first. # This will change the PATH, but we need to keep that new PATH even # after toolchain detection is done, since the compiler (on x86) uses # it for DLL resolution in runtime. - if test "x$OPENJDK_BUILD_OS" = "xwindows" && test "x$TOOLCHAIN_TYPE" = "xmicrosoft"; then + if test "x$OPENJDK_BUILD_OS" = "xwindows" \ + && test "x$TOOLCHAIN_TYPE" = "xmicrosoft"; then TOOLCHAIN_SETUP_VISUAL_STUDIO_ENV # Reset path to VS_PATH. It will include everything that was on PATH at the time we # ran TOOLCHAIN_SETUP_VISUAL_STUDIO_ENV. @@ -203,9 +207,6 @@ AC_DEFUN_ONCE([TOOLCHAIN_PRE_DETECTION], export LIB="$VS_LIB" fi - # autoconf magic only relies on PATH, so update it if tools dir is specified - OLD_PATH="$PATH" - # For solaris we really need solaris tools, and not the GNU equivalent. # The build tools on Solaris reside in /usr/ccs (C Compilation System), # so add that to path before starting to probe. @@ -662,13 +663,6 @@ AC_DEFUN_ONCE([TOOLCHAIN_SETUP_LEGACY], USE_CLANG=true fi AC_SUBST(USE_CLANG) - - # LDEXE is the linker to use, when creating executables. Not really used. - # FIXME: These should just be removed! - LDEXE="$LD" - LDEXECXX="$LDCXX" - AC_SUBST(LDEXE) - AC_SUBST(LDEXECXX) ]) # Do some additional checks on the detected tools. diff --git a/common/autoconf/toolchain_windows.m4 b/common/autoconf/toolchain_windows.m4 index 78e03f78c40..4a40fa63a91 100644 --- a/common/autoconf/toolchain_windows.m4 +++ b/common/autoconf/toolchain_windows.m4 @@ -24,8 +24,8 @@ # ################################################################################ - -VALID_VS_VERSIONS="2010 2012 2013" +# The order of these defines the priority by which we try to find them. +VALID_VS_VERSIONS="2013 2012 2010" VS_DESCRIPTION_2010="Microsoft Visual Studio 2010" VS_VERSION_INTERNAL_2010=100 @@ -72,7 +72,7 @@ AC_DEFUN([TOOLCHAIN_CHECK_POSSIBLE_VISUAL_STUDIO_ROOT], else VCVARSFILE="vc/bin/amd64/vcvars64.bat" fi - + BASIC_WINDOWS_REWRITE_AS_UNIX_PATH(VS_BASE) if test -d "$VS_BASE"; then if test -f "$VS_BASE/$VCVARSFILE"; then @@ -210,6 +210,37 @@ AC_DEFUN([TOOLCHAIN_FIND_VISUAL_STUDIO], done exit 0 + elif test "x$DEVKIT_VS_VERSION" != x; then + VS_VERSION=$DEVKIT_VS_VERSION + TOOLCHAIN_VERSION=$VS_VERSION + eval VS_DESCRIPTION="\${VS_DESCRIPTION_${VS_VERSION}}" + eval VS_VERSION_INTERNAL="\${VS_VERSION_INTERNAL_${VS_VERSION}}" + eval MSVCR_NAME="\${VS_MSVCR_${VS_VERSION}}" + eval MSVCP_NAME="\${VS_MSVCP_${VS_VERSION}}" + eval PLATFORM_TOOLSET="\${VS_VS_PLATFORM_NAME_${VS_VERSION}}" + VS_PATH="$TOOLCHAIN_PATH:$PATH" + + # Convert DEVKIT_VS_INCLUDE into windows style VS_INCLUDE so that it + # can still be exported as INCLUDE for compiler invocations without + # SYSROOT_CFLAGS + OLDIFS="$IFS" + IFS=";" + for i in $DEVKIT_VS_INCLUDE; do + ipath=$i + BASIC_WINDOWS_REWRITE_AS_WINDOWS_MIXED_PATH([ipath]) + VS_INCLUDE="$VS_INCLUDE;$ipath" + done + # Convert DEVKIT_VS_LIB into VS_LIB so that it can still be exported + # as LIB for compiler invocations without SYSROOT_LDFLAGS + for i in $DEVKIT_VS_LIB; do + libpath=$i + BASIC_WINDOWS_REWRITE_AS_WINDOWS_MIXED_PATH([libpath]) + VS_LIB="$VS_LIB;$libpath" + done + IFS="$OLDIFS" + + AC_MSG_NOTICE([Found devkit $VS_DESCRIPTION]) + elif test "x$with_toolchain_version" != x; then # User override; check that it is valid if test "x${VALID_VS_VERSIONS/$with_toolchain_version/}" = "x${VALID_VS_VERSIONS}"; then @@ -262,71 +293,81 @@ AC_DEFUN([TOOLCHAIN_SETUP_VISUAL_STUDIO_ENV], # First-hand choice is to locate and run the vsvars bat file. TOOLCHAIN_FIND_VISUAL_STUDIO - if test "x$VS_ENV_CMD" != x; then - # We have found a Visual Studio environment on disk, let's extract variables from the vsvars bat file. - BASIC_FIXUP_EXECUTABLE(VS_ENV_CMD) + # If we have a devkit, skip all of the below. + if test "x$DEVKIT_VS_VERSION" = x; then + if test "x$VS_ENV_CMD" != x; then + # We have found a Visual Studio environment on disk, let's extract variables from the vsvars bat file. + BASIC_FIXUP_EXECUTABLE(VS_ENV_CMD) - # Lets extract the variables that are set by vcvarsall.bat/vsvars32.bat/vsvars64.bat - AC_MSG_NOTICE([Trying to extract Visual Studio environment variables]) + # Lets extract the variables that are set by vcvarsall.bat/vsvars32.bat/vsvars64.bat + AC_MSG_NOTICE([Trying to extract Visual Studio environment variables]) - # We need to create a couple of temporary files. - VS_ENV_TMP_DIR="$OUTPUT_ROOT/vs-env" - $MKDIR -p $VS_ENV_TMP_DIR + # We need to create a couple of temporary files. + VS_ENV_TMP_DIR="$CONFIGURESUPPORT_OUTPUTDIR/vs-env" + $MKDIR -p $VS_ENV_TMP_DIR - # Cannot use the VS10 setup script directly (since it only updates the DOS subshell environment). - # Instead create a shell script which will set the relevant variables when run. - WINPATH_VS_ENV_CMD="$VS_ENV_CMD" - BASIC_WINDOWS_REWRITE_AS_WINDOWS_MIXED_PATH([WINPATH_VS_ENV_CMD]) - WINPATH_BASH="$BASH" - BASIC_WINDOWS_REWRITE_AS_WINDOWS_MIXED_PATH([WINPATH_BASH]) + # Cannot use the VS10 setup script directly (since it only updates the DOS subshell environment). + # Instead create a shell script which will set the relevant variables when run. + WINPATH_VS_ENV_CMD="$VS_ENV_CMD" + BASIC_WINDOWS_REWRITE_AS_WINDOWS_MIXED_PATH([WINPATH_VS_ENV_CMD]) + WINPATH_BASH="$BASH" + BASIC_WINDOWS_REWRITE_AS_WINDOWS_MIXED_PATH([WINPATH_BASH]) - # Generate a DOS batch file which runs $VS_ENV_CMD, and then creates a shell - # script (executable by bash) that will setup the important variables. - EXTRACT_VC_ENV_BAT_FILE="$VS_ENV_TMP_DIR/extract-vs-env.bat" - $ECHO "@echo off" > $EXTRACT_VC_ENV_BAT_FILE - # This will end up something like: - # call C:/progra~2/micros~2.0/vc/bin/amd64/vcvars64.bat - $ECHO "call $WINPATH_VS_ENV_CMD $VS_ENV_ARGS" >> $EXTRACT_VC_ENV_BAT_FILE - # These will end up something like: - # C:/CygWin/bin/bash -c 'echo VS_PATH=\"$PATH\" > localdevenv.sh - # The trailing space for everyone except PATH is no typo, but is needed due - # to trailing \ in the Windows paths. These will be stripped later. - $ECHO "$WINPATH_BASH -c 'echo VS_PATH="'\"$PATH\" > set-vs-env.sh' >> $EXTRACT_VC_ENV_BAT_FILE - $ECHO "$WINPATH_BASH -c 'echo VS_INCLUDE="'\"$INCLUDE\;$include \" >> set-vs-env.sh' >> $EXTRACT_VC_ENV_BAT_FILE - $ECHO "$WINPATH_BASH -c 'echo VS_LIB="'\"$LIB\;$lib \" >> set-vs-env.sh' >> $EXTRACT_VC_ENV_BAT_FILE - $ECHO "$WINPATH_BASH -c 'echo VCINSTALLDIR="'\"$VCINSTALLDIR \" >> set-vs-env.sh' >> $EXTRACT_VC_ENV_BAT_FILE - $ECHO "$WINPATH_BASH -c 'echo WindowsSdkDir="'\"$WindowsSdkDir \" >> set-vs-env.sh' >> $EXTRACT_VC_ENV_BAT_FILE - $ECHO "$WINPATH_BASH -c 'echo WINDOWSSDKDIR="'\"$WINDOWSSDKDIR \" >> set-vs-env.sh' >> $EXTRACT_VC_ENV_BAT_FILE + # Generate a DOS batch file which runs $VS_ENV_CMD, and then creates a shell + # script (executable by bash) that will setup the important variables. + EXTRACT_VC_ENV_BAT_FILE="$VS_ENV_TMP_DIR/extract-vs-env.bat" + $ECHO "@echo off" > $EXTRACT_VC_ENV_BAT_FILE + # This will end up something like: + # call C:/progra~2/micros~2.0/vc/bin/amd64/vcvars64.bat + $ECHO "call $WINPATH_VS_ENV_CMD $VS_ENV_ARGS" >> $EXTRACT_VC_ENV_BAT_FILE + # These will end up something like: + # C:/CygWin/bin/bash -c 'echo VS_PATH=\"$PATH\" > localdevenv.sh + # The trailing space for everyone except PATH is no typo, but is needed due + # to trailing \ in the Windows paths. These will be stripped later. + $ECHO "$WINPATH_BASH -c 'echo VS_PATH="'\"$PATH\" > set-vs-env.sh' \ + >> $EXTRACT_VC_ENV_BAT_FILE + $ECHO "$WINPATH_BASH -c 'echo VS_INCLUDE="'\"$INCLUDE\;$include \" >> set-vs-env.sh' \ + >> $EXTRACT_VC_ENV_BAT_FILE + $ECHO "$WINPATH_BASH -c 'echo VS_LIB="'\"$LIB\;$lib \" >> set-vs-env.sh' \ + >> $EXTRACT_VC_ENV_BAT_FILE + $ECHO "$WINPATH_BASH -c 'echo VCINSTALLDIR="'\"$VCINSTALLDIR \" >> set-vs-env.sh' \ + >> $EXTRACT_VC_ENV_BAT_FILE + $ECHO "$WINPATH_BASH -c 'echo WindowsSdkDir="'\"$WindowsSdkDir \" >> set-vs-env.sh' \ + >> $EXTRACT_VC_ENV_BAT_FILE + $ECHO "$WINPATH_BASH -c 'echo WINDOWSSDKDIR="'\"$WINDOWSSDKDIR \" >> set-vs-env.sh' \ + >> $EXTRACT_VC_ENV_BAT_FILE - # Now execute the newly created bat file. - # The | cat is to stop SetEnv.Cmd to mess with system colors on msys. - # Change directory so we don't need to mess with Windows paths in redirects. - cd $VS_ENV_TMP_DIR - cmd /c extract-vs-env.bat | $CAT - cd $CURDIR + # Now execute the newly created bat file. + # The | cat is to stop SetEnv.Cmd to mess with system colors on msys. + # Change directory so we don't need to mess with Windows paths in redirects. + cd $VS_ENV_TMP_DIR + cmd /c extract-vs-env.bat | $CAT + cd $CURDIR - if test ! -s $VS_ENV_TMP_DIR/set-vs-env.sh; then - AC_MSG_NOTICE([Could not succesfully extract the envionment variables needed for the VS setup.]) - AC_MSG_NOTICE([Try setting --with-tools-dir to the VC/bin directory within the VS installation]) - AC_MSG_NOTICE([or run "bash.exe -l" from a VS command prompt and then run configure from there.]) - AC_MSG_ERROR([Cannot continue]) + if test ! -s $VS_ENV_TMP_DIR/set-vs-env.sh; then + AC_MSG_NOTICE([Could not succesfully extract the envionment variables needed for the VS setup.]) + AC_MSG_NOTICE([Try setting --with-tools-dir to the VC/bin directory within the VS installation]) + AC_MSG_NOTICE([or run "bash.exe -l" from a VS command prompt and then run configure from there.]) + AC_MSG_ERROR([Cannot continue]) + fi + + # Now set all paths and other env variables. This will allow the rest of + # the configure script to find and run the compiler in the proper way. + AC_MSG_NOTICE([Setting extracted environment variables]) + . $VS_ENV_TMP_DIR/set-vs-env.sh + # Now we have VS_PATH, VS_INCLUDE, VS_LIB. For further checking, we + # also define VCINSTALLDIR, WindowsSdkDir and WINDOWSSDKDIR. + else + # We did not find a vsvars bat file, let's hope we are run from a VS command prompt. + AC_MSG_NOTICE([Cannot locate a valid Visual Studio installation, checking current environment]) fi - - # Now set all paths and other env variables. This will allow the rest of - # the configure script to find and run the compiler in the proper way. - AC_MSG_NOTICE([Setting extracted environment variables]) - . $VS_ENV_TMP_DIR/set-vs-env.sh - # Now we have VS_PATH, VS_INCLUDE, VS_LIB. For further checking, we - # also define VCINSTALLDIR, WindowsSdkDir and WINDOWSSDKDIR. - else - # We did not find a vsvars bat file, let's hope we are run from a VS command prompt. - AC_MSG_NOTICE([Cannot locate a valid Visual Studio installation, checking current environment]) fi # At this point, we should have correct variables in the environment, or we can't continue. AC_MSG_CHECKING([for Visual Studio variables]) - if test "x$VCINSTALLDIR" != x || test "x$WindowsSDKDir" != x || test "x$WINDOWSSDKDIR" != x; then + if test "x$VCINSTALLDIR" != x || test "x$WindowsSDKDir" != x \ + || test "x$WINDOWSSDKDIR" != x || test "x$DEVKIT_NAME" != x; then if test "x$VS_INCLUDE" = x || test "x$VS_LIB" = x; then AC_MSG_RESULT([present but broken]) AC_MSG_ERROR([Your VC command prompt seems broken, INCLUDE and/or LIB is missing.]) @@ -403,10 +444,10 @@ AC_DEFUN([TOOLCHAIN_CHECK_POSSIBLE_MSVC_DLL], POSSIBLE_MSVC_DLL="$2" METHOD="$3" if test -n "$POSSIBLE_MSVC_DLL" -a -e "$POSSIBLE_MSVC_DLL"; then - AC_MSG_NOTICE([Found $1 at $POSSIBLE_MSVC_DLL using $METHOD]) - + AC_MSG_NOTICE([Found $DLL_NAME at $POSSIBLE_MSVC_DLL using $METHOD]) + # Need to check if the found msvcr is correct architecture - AC_MSG_CHECKING([found $1 architecture]) + AC_MSG_CHECKING([found $DLL_NAME architecture]) MSVC_DLL_FILETYPE=`$FILE -b "$POSSIBLE_MSVC_DLL"` if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then # The MSYS 'file' command returns "PE32 executable for MS Windows (DLL) (GUI) Intel 80386 32-bit" @@ -426,19 +467,19 @@ AC_DEFUN([TOOLCHAIN_CHECK_POSSIBLE_MSVC_DLL], if $ECHO "$MSVC_DLL_FILETYPE" | $GREP "$CORRECT_MSVCR_ARCH" 2>&1 > /dev/null; then AC_MSG_RESULT([ok]) MSVC_DLL="$POSSIBLE_MSVC_DLL" - AC_MSG_CHECKING([for $1]) + BASIC_FIXUP_PATH(MSVC_DLL) + AC_MSG_CHECKING([for $DLL_NAME]) AC_MSG_RESULT([$MSVC_DLL]) else AC_MSG_RESULT([incorrect, ignoring]) - AC_MSG_NOTICE([The file type of the located $1 is $MSVC_DLL_FILETYPE]) + AC_MSG_NOTICE([The file type of the located $DLL_NAME is $MSVC_DLL_FILETYPE]) fi fi ]) AC_DEFUN([TOOLCHAIN_SETUP_MSVC_DLL], [ - VAR_NAME="$1" - DLL_NAME="$2" + DLL_NAME="$1" MSVC_DLL= if test "x$MSVC_DLL" = x; then @@ -463,9 +504,9 @@ AC_DEFUN([TOOLCHAIN_SETUP_MSVC_DLL], TOOLCHAIN_CHECK_POSSIBLE_MSVC_DLL([$DLL_NAME], [$POSSIBLE_MSVC_DLL], [well-known location in Boot JDK]) fi - + if test "x$MSVC_DLL" = x; then - # Probe: Look in the Windows system32 directory + # Probe: Look in the Windows system32 directory CYGWIN_SYSTEMROOT="$SYSTEMROOT" BASIC_WINDOWS_REWRITE_AS_UNIX_PATH(CYGWIN_SYSTEMROOT) POSSIBLE_MSVC_DLL="$CYGWIN_SYSTEMROOT/system32/$DLL_NAME" @@ -489,7 +530,7 @@ AC_DEFUN([TOOLCHAIN_SETUP_MSVC_DLL], [search of VS100COMNTOOLS]) fi fi - + if test "x$MSVC_DLL" = x; then # Probe: Search wildly in the VCINSTALLDIR. We've probably lost by now. # (This was the original behaviour; kept since it might turn something up) @@ -506,21 +547,17 @@ AC_DEFUN([TOOLCHAIN_SETUP_MSVC_DLL], | $HEAD --lines 1` fi fi - + TOOLCHAIN_CHECK_POSSIBLE_MSVC_DLL([$DLL_NAME], [$POSSIBLE_MSVC_DLL], [search of VCINSTALLDIR]) fi fi - + if test "x$MSVC_DLL" = x; then AC_MSG_CHECKING([for $DLL_NAME]) AC_MSG_RESULT([no]) AC_MSG_ERROR([Could not find $DLL_NAME. Please specify using --with-msvcr-dll.]) fi - - $1=$MSVC_DLL - BASIC_FIXUP_PATH($1) - AC_SUBST($1, [$]$1) ]) AC_DEFUN([TOOLCHAIN_SETUP_VS_RUNTIME_DLLS], @@ -530,14 +567,22 @@ AC_DEFUN([TOOLCHAIN_SETUP_VS_RUNTIME_DLLS], if test "x$with_msvcr_dll" != x; then # If given explicitely by user, do not probe. If not present, fail directly. - TOOLCHAIN_CHECK_POSSIBLE_MSVC_DLL([$DLL_NAME], [$with_msvcr_dll], - [--with-msvcr-dll]) + TOOLCHAIN_CHECK_POSSIBLE_MSVC_DLL($MSVCR_NAME, [$with_msvcr_dll], [--with-msvcr-dll]) if test "x$MSVC_DLL" = x; then AC_MSG_ERROR([Could not find a proper $MSVCR_NAME as specified by --with-msvcr-dll]) fi + MSVCR_DLL="$MSVC_DLL" + elif test "x$DEVKIT_MSVCR_DLL" != x; then + TOOLCHAIN_CHECK_POSSIBLE_MSVC_DLL($MSVCR_NAME, [$DEVKIT_MSVCR_DLL], [devkit]) + if test "x$MSVC_DLL" = x; then + AC_MSG_ERROR([Could not find a proper $MSVCR_NAME as specified by devkit]) + fi + MSVCR_DLL="$MSVC_DLL" else - TOOLCHAIN_SETUP_MSVC_DLL([MSVCR_DLL], [${MSVCR_NAME}]) + TOOLCHAIN_SETUP_MSVC_DLL([${MSVCR_NAME}]) + MSVCR_DLL="$MSVC_DLL" fi + AC_SUBST(MSVCR_DLL) AC_ARG_WITH(msvcp-dll, [AS_HELP_STRING([--with-msvcp-dll], [path to microsoft C++ runtime dll (msvcp*.dll) (Windows only) @<:@probed@:>@])]) @@ -545,13 +590,21 @@ AC_DEFUN([TOOLCHAIN_SETUP_VS_RUNTIME_DLLS], if test "x$MSVCP_NAME" != "x"; then if test "x$with_msvcp_dll" != x; then # If given explicitely by user, do not probe. If not present, fail directly. - TOOLCHAIN_CHECK_POSSIBLE_MSVC_DLL([$DLL_NAME], [$with_msvcp_dll], - [--with-msvcp-dll]) + TOOLCHAIN_CHECK_POSSIBLE_MSVC_DLL($MSVCP_NAME, [$with_msvcp_dll], [--with-msvcp-dll]) if test "x$MSVC_DLL" = x; then AC_MSG_ERROR([Could not find a proper $MSVCP_NAME as specified by --with-msvcp-dll]) fi + MSVCP_DLL="$MSVC_DLL" + elif test "x$DEVKIT_MSVCP_DLL" != x; then + TOOLCHAIN_CHECK_POSSIBLE_MSVC_DLL($MSVCP_NAME, [$DEVKIT_MSVCP_DLL], [devkit]) + if test "x$MSVC_DLL" = x; then + AC_MSG_ERROR([Could not find a proper $MSVCP_NAME as specified by devkit]) + fi + MSVCP_DLL="$MSVC_DLL" else - TOOLCHAIN_SETUP_MSVC_DLL([MSVCP_DLL], [${MSVCP_NAME}]) + TOOLCHAIN_SETUP_MSVC_DLL([${MSVCP_NAME}]) + MSVCP_DLL="$MSVC_DLL" fi + AC_SUBST(MSVCP_DLL) fi ]) diff --git a/common/bin/unshuffle_list.txt b/common/bin/unshuffle_list.txt index a27c192e7fc..0553eb826fc 100644 --- a/common/bin/unshuffle_list.txt +++ b/common/bin/unshuffle_list.txt @@ -1294,6 +1294,9 @@ jdk/src/jdk.crypto.pkcs11/windows/native/libj2pkcs11/j2secmod_md.h : jdk/src/win jdk/src/jdk.crypto.pkcs11/windows/native/libj2pkcs11/p11_md.c : jdk/src/windows/native/sun/security/pkcs11/wrapper/p11_md.c jdk/src/jdk.crypto.pkcs11/windows/native/libj2pkcs11/p11_md.h : jdk/src/windows/native/sun/security/pkcs11/wrapper/p11_md.h jdk/src/jdk.deploy.osx/macosx/classes/com/apple/concurrent/package.html : jdk/src/macosx/classes/com/apple/concurrent/package.html +jdk/src/jdk.deploy.osx/macosx/classes/apple/applescript : jdk/src/macosx/classes/apple/applescript +jdk/src/jdk.deploy.osx/macosx/classes/apple/security : jdk/src/macosx/classes/apple/security +jdk/src/jdk.deploy.osx/macosx/classes/com/apple/concurrent : jdk/src/macosx/classes/com/apple/concurrent jdk/src/jdk.deploy.osx/macosx/native/libapplescriptengine : jdk/src/macosx/native/apple/applescript jdk/src/jdk.deploy.osx/macosx/native/libosx/CFileManager.m : jdk/src/macosx/native/com/apple/eio/CFileManager.m jdk/src/jdk.deploy.osx/macosx/native/libosx/Dispatch.m : jdk/src/macosx/native/com/apple/concurrent/Dispatch.m diff --git a/configure b/configure index 4ab8846d575..af0b5b57bd8 100644 --- a/configure +++ b/configure @@ -31,4 +31,5 @@ this_script_dir=`cd $this_script_dir > /dev/null && pwd` # Delegate to wrapper, forcing wrapper to believe $0 is this script by using -c. # This trick is needed to get autoconf to co-operate properly. -bash -c ". $this_script_dir/common/autoconf/configure" $this_script_dir/configure CHECKME $this_script_dir "$@" +# The ${-:+-$-} construction passes on bash options. +bash ${-:+-$-} -c ". $this_script_dir/common/autoconf/configure" $this_script_dir/configure CHECKME $this_script_dir "$@" diff --git a/corba/.hgtags b/corba/.hgtags index fd64f5a34f9..b1d9426e786 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -298,3 +298,10 @@ b8538bbb6f224ab1dabba579137099c166ad4724 jdk9-b52 aadc16ca5ab7d56f92ef9dbfa443595a939241b4 jdk9-b53 d469c5ad0c763e325a78e0af3016878a57dfc5cc jdk9-b54 734ca5311a225711b79618f3e92f47f07c82154a jdk9-b55 +ef4afd6832b00b8687832c2a36c90e43750ebe40 jdk9-b56 +d8ebf1a5b18ccbc849f5bf0f80aa3d78583eee68 jdk9-b57 +86dd5de1f5cb09073019bd629e22cfcd012d8b4b jdk9-b58 +cda6ae062f85fac5555f4e1318885b0ecd998bd1 jdk9-b59 +caa330b275f39282793466529f6864766b31d9fd jdk9-b60 +d690f489ca0bb95a6157d996da2fa72bcbcf02ea jdk9-b61 +d27f7e0a7aca129969de23e9934408a31b4abf4c jdk9-b62 diff --git a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/corba/RequestImpl.java b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/corba/RequestImpl.java index 886d1575896..c6eb5f7051a 100644 --- a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/corba/RequestImpl.java +++ b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/corba/RequestImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -65,6 +65,7 @@ import com.sun.corba.se.spi.presentation.rmi.StubAdapter; import com.sun.corba.se.spi.logging.CORBALogDomains; import com.sun.corba.se.impl.logging.ORBUtilSystemException; import com.sun.corba.se.impl.corba.AsynchInvoke; +import com.sun.corba.se.impl.transport.ManagedLocalsThread; public class RequestImpl extends Request @@ -255,7 +256,7 @@ public class RequestImpl public synchronized void send_deferred() { AsynchInvoke invokeObject = new AsynchInvoke(_orb, this, false); - new Thread(invokeObject).start(); + new ManagedLocalsThread(invokeObject).start(); } public synchronized boolean poll_response() diff --git a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/io/IIOPInputStream.java b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/io/IIOPInputStream.java index e14b25ebb1b..8d4e68145a6 100644 --- a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/io/IIOPInputStream.java +++ b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/io/IIOPInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1768,43 +1768,59 @@ public class IIOPInputStream switch (field.getTypeCode()) { case 'B': byte byteValue = orbStream.read_octet(); - bridge.putByte( o, field.getFieldID(), byteValue ) ; - //reflective code: field.getField().setByte( o, byteValue ) ; + if (field.getField() != null) { + bridge.putByte( o, field.getFieldID(), byteValue ) ; + //reflective code: field.getField().setByte( o, byteValue ) ; + } break; case 'Z': boolean booleanValue = orbStream.read_boolean(); - bridge.putBoolean( o, field.getFieldID(), booleanValue ) ; - //reflective code: field.getField().setBoolean( o, booleanValue ) ; + if (field.getField() != null) { + bridge.putBoolean( o, field.getFieldID(), booleanValue ) ; + //reflective code: field.getField().setBoolean( o, booleanValue ) ; + } break; case 'C': char charValue = orbStream.read_wchar(); - bridge.putChar( o, field.getFieldID(), charValue ) ; - //reflective code: field.getField().setChar( o, charValue ) ; + if (field.getField() != null) { + bridge.putChar( o, field.getFieldID(), charValue ) ; + //reflective code: field.getField().setChar( o, charValue ) ; + } break; case 'S': short shortValue = orbStream.read_short(); - bridge.putShort( o, field.getFieldID(), shortValue ) ; - //reflective code: field.getField().setShort( o, shortValue ) ; + if (field.getField() != null) { + bridge.putShort( o, field.getFieldID(), shortValue ) ; + //reflective code: field.getField().setShort( o, shortValue ) ; + } break; case 'I': int intValue = orbStream.read_long(); - bridge.putInt( o, field.getFieldID(), intValue ) ; - //reflective code: field.getField().setInt( o, intValue ) ; + if (field.getField() != null) { + bridge.putInt( o, field.getFieldID(), intValue ) ; + //reflective code: field.getField().setInt( o, intValue ) ; + } break; case 'J': long longValue = orbStream.read_longlong(); - bridge.putLong( o, field.getFieldID(), longValue ) ; - //reflective code: field.getField().setLong( o, longValue ) ; + if (field.getField() != null) { + bridge.putLong( o, field.getFieldID(), longValue ) ; + //reflective code: field.getField().setLong( o, longValue ) ; + } break; case 'F' : float floatValue = orbStream.read_float(); - bridge.putFloat( o, field.getFieldID(), floatValue ) ; - //reflective code: field.getField().setFloat( o, floatValue ) ; + if (field.getField() != null) { + bridge.putFloat( o, field.getFieldID(), floatValue ) ; + //reflective code: field.getField().setFloat( o, floatValue ) ; + } break; case 'D' : double doubleValue = orbStream.read_double(); - bridge.putDouble( o, field.getFieldID(), doubleValue ) ; - //reflective code: field.getField().setDouble( o, doubleValue ) ; + if (field.getField() != null) { + bridge.putDouble( o, field.getFieldID(), doubleValue ) ; + //reflective code: field.getField().setDouble( o, doubleValue ) ; + } break; default: // XXX I18N, logging needed. @@ -2217,9 +2233,6 @@ public class IIOPInputStream if (o != null) { for (int i = 0; i < primFields; ++i) { - if (fields[i].getField() == null) - continue; - inputPrimitiveField(o, cl, fields[i]); } } diff --git a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/io/OutputStreamHook.java b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/io/OutputStreamHook.java index 6908cad9a83..79ef01e8765 100644 --- a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/io/OutputStreamHook.java +++ b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/io/OutputStreamHook.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,7 @@ package com.sun.corba.se.impl.io; import java.io.IOException; +import java.io.NotActiveException; import java.io.OutputStream; import java.io.ObjectOutputStream; import java.io.ObjectOutput; @@ -154,7 +155,9 @@ public abstract class OutputStreamHook extends ObjectOutputStream public ObjectOutputStream.PutField putFields() throws IOException { - putFields = new HookPutFields(); + if (putFields == null) { + putFields = new HookPutFields(); + } return putFields; } @@ -175,8 +178,11 @@ public abstract class OutputStreamHook extends ObjectOutputStream throws IOException { writeObjectState.defaultWriteObject(this); - - putFields.write(this); + if (putFields != null) { + putFields.write(this); + } else { + throw new NotActiveException("no current PutField object"); + } } abstract org.omg.CORBA_2_3.portable.OutputStream getOrbStream(); diff --git a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/javax/rmi/CORBA/Util.java b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/javax/rmi/CORBA/Util.java index 7829d52a495..473cf6487ca 100644 --- a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/javax/rmi/CORBA/Util.java +++ b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/javax/rmi/CORBA/Util.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -112,6 +112,8 @@ import com.sun.corba.se.impl.util.JDKBridge; import com.sun.corba.se.impl.logging.UtilSystemException; import com.sun.corba.se.spi.logging.CORBALogDomains; import sun.corba.SharedSecrets; +import com.sun.corba.se.impl.transport.ManagedLocalsThread; + /** * Provides utility methods that can be used by stubs and ties to @@ -750,7 +752,7 @@ public class Util implements javax.rmi.CORBA.UtilDelegate } } -class KeepAlive extends Thread +class KeepAlive extends ManagedLocalsThread { boolean quit = false; diff --git a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/oa/poa/POAImpl.java b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/oa/poa/POAImpl.java index 0698aafef43..d10f4e3eccd 100644 --- a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/oa/poa/POAImpl.java +++ b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/oa/poa/POAImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -103,6 +103,7 @@ import com.sun.corba.se.impl.orbutil.concurrent.Sync ; import com.sun.corba.se.impl.orbutil.concurrent.SyncUtil ; import com.sun.corba.se.impl.orbutil.concurrent.ReentrantMutex ; import com.sun.corba.se.impl.orbutil.concurrent.CondVar ; +import com.sun.corba.se.impl.transport.ManagedLocalsThread; /** * POAImpl is the implementation of the Portable Object Adapter. It @@ -516,7 +517,7 @@ public class POAImpl extends ObjectAdapterBase implements POA // Converted from anonymous class to local class // so that we can call performDestroy() directly. - static class DestroyThread extends Thread { + static class DestroyThread extends ManagedLocalsThread { private boolean wait ; private boolean etherealize ; private boolean debug ; diff --git a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/oa/poa/POAManagerImpl.java b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/oa/poa/POAManagerImpl.java index a044c14ea70..41100a4b3bd 100644 --- a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/oa/poa/POAManagerImpl.java +++ b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/oa/poa/POAManagerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -48,6 +48,7 @@ import com.sun.corba.se.spi.protocol.PIHandler ; import com.sun.corba.se.impl.logging.POASystemException ; import com.sun.corba.se.impl.orbutil.ORBUtility ; +import com.sun.corba.se.impl.transport.ManagedLocalsThread; /** POAManagerImpl is the implementation of the POAManager interface. * Its public methods are activate(), hold_requests(), discard_requests() @@ -357,7 +358,7 @@ public class POAManagerImpl extends org.omg.CORBA.LocalObject implements if (wait_for_completion) deactivator.run() ; else { - Thread thr = new Thread(deactivator) ; + Thread thr = new ManagedLocalsThread(deactivator) ; thr.start() ; } } finally { diff --git a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/oa/poa/POAPolicyMediatorImpl_R_USM.java b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/oa/poa/POAPolicyMediatorImpl_R_USM.java index 6c40f741845..21a5c340612 100644 --- a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/oa/poa/POAPolicyMediatorImpl_R_USM.java +++ b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/oa/poa/POAPolicyMediatorImpl_R_USM.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,6 @@ package com.sun.corba.se.impl.oa.poa ; import java.util.Set ; - import org.omg.CORBA.SystemException ; import org.omg.PortableServer.ServantActivator ; @@ -50,6 +49,7 @@ import com.sun.corba.se.impl.javax.rmi.CORBA.Util ; import com.sun.corba.se.spi.oa.OAInvocationInfo ; import com.sun.corba.se.spi.oa.NullServant ; +import com.sun.corba.se.impl.transport.ManagedLocalsThread; /** Implementation of POARequesHandler that provides policy specific * operations on the POA. @@ -303,13 +303,14 @@ public class POAPolicyMediatorImpl_R_USM extends POAPolicyMediatorBase_R { throw new WrongPolicy(); } - class Etherealizer extends Thread { + class Etherealizer extends ManagedLocalsThread { private POAPolicyMediatorImpl_R_USM mediator ; private ActiveObjectMap.Key key ; private AOMEntry entry ; private Servant servant ; private boolean debug ; + public Etherealizer( POAPolicyMediatorImpl_R_USM mediator, ActiveObjectMap.Key key, AOMEntry entry, Servant servant, boolean debug ) diff --git a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/orb/ORBImpl.java b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/orb/ORBImpl.java index 8bda9dcbf0b..c619b8a9268 100644 --- a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/orb/ORBImpl.java +++ b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/orb/ORBImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -165,6 +165,7 @@ import com.sun.corba.se.impl.util.Utility; import com.sun.corba.se.impl.logging.ORBUtilSystemException; import com.sun.corba.se.impl.copyobject.CopierManagerImpl; import com.sun.corba.se.impl.presentation.rmi.PresentationManagerImpl; +import com.sun.corba.se.impl.transport.ManagedLocalsThread; /** * The JavaIDL ORB implementation. @@ -691,7 +692,7 @@ public class ORBImpl extends com.sun.corba.se.spi.orb.ORB for (int i = 0; i < req.length; i++) { AsynchInvoke invokeObject = new AsynchInvoke( this, (com.sun.corba.se.impl.corba.RequestImpl)req[i], true); - new Thread(invokeObject).start(); + new ManagedLocalsThread(invokeObject).start(); } } diff --git a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/orbutil/threadpool/ThreadPoolImpl.java b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/orbutil/threadpool/ThreadPoolImpl.java index f98880bf68d..12a8127d061 100644 --- a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/orbutil/threadpool/ThreadPoolImpl.java +++ b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/orbutil/threadpool/ThreadPoolImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -54,6 +54,7 @@ import com.sun.corba.se.spi.monitoring.LongMonitoredAttributeBase; import com.sun.corba.se.impl.logging.ORBUtilSystemException; import com.sun.corba.se.impl.orbutil.ORBConstants; import com.sun.corba.se.spi.logging.CORBALogDomains; +import com.sun.corba.se.impl.transport.ManagedLocalsThread; public class ThreadPoolImpl implements ThreadPool { @@ -459,7 +460,7 @@ public class ThreadPoolImpl implements ThreadPool } - private class WorkerThread extends Thread implements Closeable + private class WorkerThread extends ManagedLocalsThread implements Closeable { private Work currentWork; private int threadId = 0; // unique id for the thread diff --git a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/transport/ManagedLocalsThread.java b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/transport/ManagedLocalsThread.java new file mode 100644 index 00000000000..b888de30228 --- /dev/null +++ b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/transport/ManagedLocalsThread.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.corba.se.impl.transport; + +import sun.misc.Unsafe; +import java.lang.reflect.Field; +import java.security.AccessController; +import java.security.PrivilegedAction; + +/** + * A thread that has it's thread locals, and inheritable thread + * locals erased on construction. + */ +public class ManagedLocalsThread extends Thread { + private static final Unsafe UNSAFE; + private static final long THREAD_LOCALS; + private static final long INHERITABLE_THREAD_LOCALS; + + public ManagedLocalsThread () { + super(); + } + + public ManagedLocalsThread(String name) { + super(name); + eraseThreadLocals(); + } + public ManagedLocalsThread(Runnable target) { + super(target); + eraseThreadLocals(); + } + + public ManagedLocalsThread(Runnable target, String name) { + super(target, name); + eraseThreadLocals(); + } + + public ManagedLocalsThread(ThreadGroup group, Runnable target, String name) { + super(group, target, name); + eraseThreadLocals(); + } + + public ManagedLocalsThread(ThreadGroup group, String name) { + super(group, name); + eraseThreadLocals(); + } + + /** + * Drops all thread locals (and inherited thread locals). + */ + public final void eraseThreadLocals() { + UNSAFE.putObject(this, THREAD_LOCALS, null); + UNSAFE.putObject(this, INHERITABLE_THREAD_LOCALS, null); + } + + private static Unsafe getUnsafe() { + PrivilegedAction pa = () -> { + Class unsafeClass = sun.misc.Unsafe.class; + try { + Field f = unsafeClass.getDeclaredField("theUnsafe"); + f.setAccessible(true); + return (Unsafe) f.get(null); + } catch (Exception e) { + throw new Error(e); + } + }; + return AccessController.doPrivileged(pa); + } + + private static long getThreadFieldOffset(String fieldName) { + PrivilegedAction pa = () -> { + Class t = Thread.class; + long fieldOffset; + try { + fieldOffset = UNSAFE.objectFieldOffset(t + .getDeclaredField("inheritableThreadLocals")); + } catch (Exception e) { + throw new Error(e); + } + return fieldOffset; + }; + return AccessController.doPrivileged(pa); + } + + static { + UNSAFE = getUnsafe(); + try { + THREAD_LOCALS = getThreadFieldOffset("threadLocals"); + INHERITABLE_THREAD_LOCALS = getThreadFieldOffset("inheritableThreadLocals"); + } catch (Exception e) { + throw new Error(e); + } + } +} diff --git a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/transport/SelectorImpl.java b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/transport/SelectorImpl.java index 054071b7d8b..4acac0a176e 100644 --- a/corba/src/java.corba/share/classes/com/sun/corba/se/impl/transport/SelectorImpl.java +++ b/corba/src/java.corba/share/classes/com/sun/corba/se/impl/transport/SelectorImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,7 +57,7 @@ import com.sun.corba.se.impl.orbutil.ORBUtility; */ class SelectorImpl extends - Thread + ManagedLocalsThread implements com.sun.corba.se.pept.transport.Selector { diff --git a/corba/src/java.corba/share/classes/javax/activity/package.html b/corba/src/java.corba/share/classes/javax/activity/package.html index bceb353231a..d9696cc090a 100644 --- a/corba/src/java.corba/share/classes/javax/activity/package.html +++ b/corba/src/java.corba/share/classes/javax/activity/package.html @@ -2,7 +2,7 @@ @@ -34,7 +33,7 @@ Provides methods for the input and output of value types, and contains other updates to the org/omg/CORBA/portable package. -

    + @since 1.3 @serial exclude diff --git a/corba/src/java.corba/share/classes/org/omg/CosNaming/NamingContextExtPackage/package.html b/corba/src/java.corba/share/classes/org/omg/CosNaming/NamingContextExtPackage/package.html index 1d5e960eafa..4f4284cff2d 100644 --- a/corba/src/java.corba/share/classes/org/omg/CosNaming/NamingContextExtPackage/package.html +++ b/corba/src/java.corba/share/classes/org/omg/CosNaming/NamingContextExtPackage/package.html @@ -3,7 +3,7 @@ - - - - XPath domapi Package. - -

    Implements DOM Level 3 XPath API

    - - - - diff --git a/jaxp/src/java.xml/share/classes/javax/xml/XMLConstants.java b/jaxp/src/java.xml/share/classes/javax/xml/XMLConstants.java index cca303c5d66..edcf17ae57b 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/XMLConstants.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/XMLConstants.java @@ -26,7 +26,7 @@ package javax.xml; /** - *

    Utility class to contain basic XML values as constants.

    + *

    Utility class to contain basic XML values as constants. * * @author Jeff Suttor * @see Extensible Markup Language (XML) 1.1 @@ -42,15 +42,15 @@ package javax.xml; public final class XMLConstants { /** - *

    Private constructor to prevent instantiation.

    + * Private constructor to prevent instantiation. */ - private XMLConstants() { - } + private XMLConstants() { + } /** - *

    Namespace URI to use to represent that there is no Namespace.

    + * Namespace URI to use to represent that there is no Namespace. * - *

    Defined by the Namespace specification to be "".

    + *

    Defined by the Namespace specification to be "". * * @see * Namespaces in XML, 5.2 Namespace Defaulting @@ -58,9 +58,9 @@ public final class XMLConstants { public static final String NULL_NS_URI = ""; /** - *

    Prefix to use to represent the default XML Namespace.

    + * Prefix to use to represent the default XML Namespace. * - *

    Defined by the XML specification to be "".

    + *

    Defined by the XML specification to be "". * * @see @@ -69,10 +69,10 @@ public final class XMLConstants { public static final String DEFAULT_NS_PREFIX = ""; /** - *

    The official XML Namespace name URI.

    + * The official XML Namespace name URI. * *

    Defined by the XML specification to be - * "{@code http://www.w3.org/XML/1998/namespace}".

    + * "{@code http://www.w3.org/XML/1998/namespace}". * * @see
    @@ -82,23 +82,23 @@ public final class XMLConstants { "http://www.w3.org/XML/1998/namespace"; /** - *

    The official XML Namespace prefix.

    + * The official XML Namespace prefix. * - *

    Defined by the XML specification to be "{@code xml}".

    + *

    Defined by the XML specification to be "{@code xml}". * * @see - * Namespaces in XML, 3. Qualified Names< + * Namespaces in XML, 3. Qualified Names */ public static final String XML_NS_PREFIX = "xml"; /** - *

    The official XML attribute used for specifying XML Namespace + * The official XML attribute used for specifying XML Namespace * declarations, {@link #XMLNS_ATTRIBUTE - * XMLConstants.XMLNS_ATTRIBUTE}, Namespace name URI.

    + * XMLConstants.XMLNS_ATTRIBUTE}, Namespace name URI. * *

    Defined by the XML specification to be - * "{@code http://www.w3.org/2000/xmlns/}".

    + * "{@code http://www.w3.org/2000/xmlns/}". * * @see @@ -111,12 +111,12 @@ public final class XMLConstants { "http://www.w3.org/2000/xmlns/"; /** - *

    The official XML attribute used for specifying XML Namespace - * declarations.

    + * The official XML attribute used for specifying XML Namespace + * declarations. * *

    It is NOT valid to use as a * prefix. Defined by the XML specification to be - * "{@code xmlns}".

    + * "{@code xmlns}". * * @see
    @@ -125,7 +125,7 @@ public final class XMLConstants { public static final String XMLNS_ATTRIBUTE = "xmlns"; /** - *

    W3C XML Schema Namespace URI.

    + * W3C XML Schema Namespace URI. * *

    Defined to be "{@code http://www.w3.org/2001/XMLSchema}". * @@ -138,9 +138,9 @@ public final class XMLConstants { "http://www.w3.org/2001/XMLSchema"; /** - *

    W3C XML Schema Instance Namespace URI.

    + * W3C XML Schema Instance Namespace URI. * - *

    Defined to be "{@code http://www.w3.org/2001/XMLSchema-instance}".

    + *

    Defined to be "{@code http://www.w3.org/2001/XMLSchema-instance}". * * @see @@ -150,33 +150,33 @@ public final class XMLConstants { public static final String W3C_XML_SCHEMA_INSTANCE_NS_URI = "http://www.w3.org/2001/XMLSchema-instance"; - /** - *

    W3C XPath Datatype Namespace URI.

    - * - *

    Defined to be "{@code http://www.w3.org/2003/11/xpath-datatypes}".

    - * - * @see
    XQuery 1.0 and XPath 2.0 Data Model - */ - public static final String W3C_XPATH_DATATYPE_NS_URI = "http://www.w3.org/2003/11/xpath-datatypes"; + /** + * W3C XPath Datatype Namespace URI. + * + *

    Defined to be "{@code http://www.w3.org/2003/11/xpath-datatypes}". + * + * @see XQuery 1.0 and XPath 2.0 Data Model + */ + public static final String W3C_XPATH_DATATYPE_NS_URI = "http://www.w3.org/2003/11/xpath-datatypes"; /** - *

    XML Document Type Declaration Namespace URI as an arbitrary value.

    + * XML Document Type Declaration Namespace URI as an arbitrary value. * *

    Since not formally defined by any existing standard, arbitrarily define to be "{@code http://www.w3.org/TR/REC-xml}". */ public static final String XML_DTD_NS_URI = "http://www.w3.org/TR/REC-xml"; /** - *

    RELAX NG Namespace URI.

    + * RELAX NG Namespace URI. * - *

    Defined to be "{@code http://relaxng.org/ns/structure/1.0}".

    + *

    Defined to be "{@code http://relaxng.org/ns/structure/1.0}". * * @see RELAX NG Specification */ public static final String RELAXNG_NS_URI = "http://relaxng.org/ns/structure/1.0"; /** - *

    Feature for secure processing.

    + * Feature for secure processing. * *
      *
    • @@ -193,14 +193,13 @@ public final class XMLConstants { /** - *

      Property: accessExternalDTD

      + * Property: accessExternalDTD * *

      * Restrict access to external DTDs and external Entity References to the protocols specified. * If access is denied due to the restriction of this property, a runtime exception that * is specific to the context is thrown. In the case of {@link javax.xml.parsers.SAXParser} * for example, {@link org.xml.sax.SAXException} is thrown. - *

      * *

      * Value: a list of protocols separated by comma. A protocol is the scheme portion of a @@ -221,7 +220,6 @@ public final class XMLConstants { * Examples of protocols are file, http, jar:file. * *

    - *

    * *

    * Default value: The default value is implementation specific and therefore not specified. @@ -231,20 +229,19 @@ public final class XMLConstants { *

  • an empty string to deny all access to external references;
  • *
  • a specific protocol, such as file, to give permission to only the protocol;
  • *
  • the keyword "all" to grant permission to all protocols.
  • - *
    + *
    * When FEATURE_SECURE_PROCESSING is enabled, it is recommended that implementations * restrict external connections by default, though this may cause problems for applications * that process XML/XSD/XSL with external references. *
    - *

    * *

    * Granting all access: the keyword "all" grants permission to all protocols. - *

    + * *

    * System Property: The value of this property can be set or overridden by * system property {@code javax.xml.accessExternalDTD}. - *

    + * * *

    * jaxp.properties: This configuration file is in standard @@ -252,11 +249,8 @@ public final class XMLConstants { * directory of the Java installation. If the file exists and the system * property is specified, its value will be used to override the default * of the property. - *

    * - *

    * - *

    * @since 1.7 */ public static final String ACCESS_EXTERNAL_DTD = "http://javax.xml.XMLConstants/property/accessExternalDTD"; @@ -270,7 +264,7 @@ public final class XMLConstants { * due to the restriction of this property, a runtime exception that is specific * to the context is thrown. In the case of {@link javax.xml.validation.SchemaFactory} * for example, org.xml.sax.SAXException is thrown. - *

    + * *

    * Value: a list of protocols separated by comma. A protocol is the scheme portion of a * {@link java.net.URI}, or in the case of the JAR protocol, "jar" plus the scheme portion @@ -290,9 +284,8 @@ public final class XMLConstants { * Examples of protocols are file, http, jar:file. * * - *

    * - *

    + *

    * Default value: The default value is implementation specific and therefore not specified. * The following options are provided for consideration: *

    @@ -300,20 +293,18 @@ public final class XMLConstants { *
  • an empty string to deny all access to external references;
  • *
  • a specific protocol, such as file, to give permission to only the protocol;
  • *
  • the keyword "all" to grant permission to all protocols.
  • - *
    + *
    * When FEATURE_SECURE_PROCESSING is enabled, it is recommended that implementations * restrict external connections by default, though this may cause problems for applications * that process XML/XSD/XSL with external references. *
    - *

    + * *

    * Granting all access: the keyword "all" grants permission to all protocols. - *

    * *

    * System Property: The value of this property can be set or overridden by * system property {@code javax.xml.accessExternalSchema} - *

    * *

    * jaxp.properties: This configuration file is in standard @@ -323,12 +314,11 @@ public final class XMLConstants { * of the property. * * @since 1.7 - *

    */ public static final String ACCESS_EXTERNAL_SCHEMA = "http://javax.xml.XMLConstants/property/accessExternalSchema"; /** - *

    Property: accessExternalStylesheet

    + * Property: accessExternalStylesheet * *

    * Restrict access to the protocols specified for external references set by the @@ -338,7 +328,7 @@ public final class XMLConstants { * {@link javax.xml.transform.Transformer} for example, * {@link javax.xml.transform.TransformerConfigurationException} * will be thrown by the {@link javax.xml.transform.TransformerFactory}. - *

    + * *

    * Value: a list of protocols separated by comma. A protocol is the scheme portion of a * {@link java.net.URI}, or in the case of the JAR protocol, "jar" plus the scheme portion @@ -358,9 +348,8 @@ public final class XMLConstants { * Examples of protocols are file, http, jar:file. * * - *

    * - *

    + *

    * Default value: The default value is implementation specific and therefore not specified. * The following options are provided for consideration: *

    @@ -368,20 +357,18 @@ public final class XMLConstants { *
  • an empty string to deny all access to external references;
  • *
  • a specific protocol, such as file, to give permission to only the protocol;
  • *
  • the keyword "all" to grant permission to all protocols.
  • - *
    + *
    * When FEATURE_SECURE_PROCESSING is enabled, it is recommended that implementations * restrict external connections by default, though this may cause problems for applications * that process XML/XSD/XSL with external references. *
    - *

    + * *

    * Granting all access: the keyword "all" grants permission to all protocols. - *

    * *

    * System Property: The value of this property can be set or overridden by * system property {@code javax.xml.accessExternalStylesheet} - *

    * *

    * jaxp.properties: This configuration file is in standard diff --git a/jaxp/src/java.xml/share/classes/javax/xml/datatype/DatatypeFactory.java b/jaxp/src/java.xml/share/classes/javax/xml/datatype/DatatypeFactory.java index d3afb25888e..001b682e42b 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/datatype/DatatypeFactory.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/datatype/DatatypeFactory.java @@ -32,11 +32,10 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * Factory that creates new javax.xml.datatype Objects that map XML to/from Java Objects. + * Factory that creates new {@code javax.xml.datatype} {@code Object}s that map XML to/from Java {@code Object}s. *

    * A new instance of the {@code DatatypeFactory} is created through the {@link #newInstance()} method * that uses the following implementation resolution mechanisms to determine an implementation: - *

    *

      *
    1. * If the system property specified by {@link #DATATYPEFACTORY_PROPERTY}, "{@code javax.xml.datatype.DatatypeFactory}", @@ -89,9 +88,9 @@ import java.util.regex.Pattern; public abstract class DatatypeFactory { /** - *

      Default property name as defined in JSR 206: Java(TM) API for XML Processing (JAXP) 1.3.

      + * Default property name as defined in JSR 206: Java(TM) API for XML Processing (JAXP) 1.3. * - *

      Default value is {@code javax.xml.datatype.DatatypeFactory}.

      + *

      Default value is {@code javax.xml.datatype.DatatypeFactory}. */ public static final String DATATYPEFACTORY_PROPERTY = // We use a String constant here, rather than calling @@ -100,16 +99,15 @@ public abstract class DatatypeFactory { "javax.xml.datatype.DatatypeFactory"; /** - *

      Default implementation class name as defined in - * JSR 206: Java(TM) API for XML Processing (JAXP) 1.3.

      + * Default implementation class name as defined in + * JSR 206: Java(TM) API for XML Processing (JAXP) 1.3. * *

      Implementers should specify the name of an appropriate class * to be instantiated if no other implementation resolution mechanism - * succeeds.

      + * succeeds. * *

      Users should not refer to this field; it is intended only to * document a factory implementation detail. - *

      */ public static final String DATATYPEFACTORY_IMPLEMENTATION_CLASS = // We use new String() here to prevent javadoc from generating @@ -130,18 +128,18 @@ public abstract class DatatypeFactory { Pattern.compile("[^YM]*[DT].*"); /** - *

      Protected constructor to prevent instantiation outside of package.

      + * Protected constructor to prevent instantiation outside of package. * - *

      Use {@link #newInstance()} to create a {@code DatatypeFactory}.

      + *

      Use {@link #newInstance()} to create a {@code DatatypeFactory}. */ protected DatatypeFactory() { } /** - *

      Obtain a new instance of a {@code DatatypeFactory}.

      + * Obtain a new instance of a {@code DatatypeFactory}. * *

      The implementation resolution mechanisms are defined in this - * Class's documentation.

      + * {@code Class}'s documentation. * * @return New instance of a {@code DatatypeFactory} * @@ -161,33 +159,33 @@ public abstract class DatatypeFactory { } /** - *

      Obtain a new instance of a {@code DatatypeFactory} from class name. + * Obtain a new instance of a {@code DatatypeFactory} from class name. * This function is useful when there are multiple providers in the classpath. * It gives more control to the application as it can specify which provider - * should be loaded.

      + * should be loaded. * *

      Once an application has obtained a reference to a {@code DatatypeFactory} - * it can use the factory to configure and obtain datatype instances.

      + * it can use the factory to configure and obtain datatype instances. * * *

      Tip for Trouble-shooting

      - *

      Setting the jaxp.debug system property will cause + *

      Setting the {@code jaxp.debug} system property will cause * this method to print a lot of debug messages - * to System.err about what it is doing and where it is looking at.

      + * to {@code System.err} about what it is doing and where it is looking at. * - *

      If you have problems try:

      + *

      If you have problems try: *

            * java -Djaxp.debug=1 YourProgram ....
            * 
      * * @param factoryClassName fully qualified factory class name that provides implementation of {@code javax.xml.datatype.DatatypeFactory}. * - * @param classLoader ClassLoader used to load the factory class. If null - * current Thread's context classLoader is used to load the factory class. + * @param classLoader {@code ClassLoader} used to load the factory class. If {@code null} + * current {@code Thread}'s context classLoader is used to load the factory class. * * @return New instance of a {@code DatatypeFactory} * - * @throws DatatypeConfigurationException if factoryClassName is null, or + * @throws DatatypeConfigurationException if {@code factoryClassName} is {@code null}, or * the factory class cannot be loaded, instantiated. * * @see #newInstance() @@ -201,11 +199,11 @@ public abstract class DatatypeFactory { } /** - *

      Obtain a new instance of a Duration - * specifying the Duration as its string representation, "PnYnMnDTnHnMnS", - * as defined in XML Schema 1.0 section 3.2.6.1.

      + * Obtain a new instance of a {@code Duration} + * specifying the {@code Duration} as its string representation, "PnYnMnDTnHnMnS", + * as defined in XML Schema 1.0 section 3.2.6.1. * - *

      XML Schema Part 2: Datatypes, 3.2.6 duration, defines duration as:

      + *

      XML Schema Part 2: Datatypes, 3.2.6 duration, defines {@code duration} as: *

      * duration represents a duration of time. * The value space of duration is a six-dimensional space where the coordinates designate the @@ -213,28 +211,28 @@ public abstract class DatatypeFactory { * These components are ordered in their significance by their order of appearance i.e. as * year, month, day, hour, minute, and second. *
      - *

      All six values are set and available from the created {@link Duration}

      + *

      All six values are set and available from the created {@link Duration} * *

      The XML Schema specification states that values can be of an arbitrary size. * Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values. * An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits - * if implementation capacities are exceeded.

      + * if implementation capacities are exceeded. * - * @param lexicalRepresentation String representation of a Duration. + * @param lexicalRepresentation {@code String} representation of a {@code Duration}. * - * @return New Duration created from parsing the lexicalRepresentation. + * @return New {@code Duration} created from parsing the {@code lexicalRepresentation}. * - * @throws IllegalArgumentException If lexicalRepresentation is not a valid representation of a Duration. + * @throws IllegalArgumentException If {@code lexicalRepresentation} is not a valid representation of a {@code Duration}. * @throws UnsupportedOperationException If implementation cannot support requested values. - * @throws NullPointerException if lexicalRepresentation is null. + * @throws NullPointerException if {@code lexicalRepresentation} is {@code null}. */ public abstract Duration newDuration(final String lexicalRepresentation); /** - *

      Obtain a new instance of a Duration - * specifying the Duration as milliseconds.

      + * Obtain a new instance of a {@code Duration} + * specifying the {@code Duration} as milliseconds. * - *

      XML Schema Part 2: Datatypes, 3.2.6 duration, defines duration as:

      + *

      XML Schema Part 2: Datatypes, 3.2.6 duration, defines {@code duration} as: *

      * duration represents a duration of time. * The value space of duration is a six-dimensional space where the coordinates designate the @@ -243,8 +241,8 @@ public abstract class DatatypeFactory { * year, month, day, hour, minute, and second. *
      *

      All six values are set by computing their values from the specified milliseconds - * and are available using the get methods of the created {@link Duration}. - * The values conform to and are defined by:

      + * and are available using the {@code get} methods of the created {@link Duration}. + * The values conform to and are defined by: *
        *
      • ISO 8601:2000(E) Section 5.5.3.2 Alternative format
      • *
      • @@ -259,38 +257,38 @@ public abstract class DatatypeFactory { * {@link java.util.Calendar#DATE} = 1, etc. * This is important as there are variations in the Gregorian Calendar, * e.g. leap years have different days in the month = {@link java.util.Calendar#FEBRUARY} - * so the result of {@link Duration#getMonths()} and {@link Duration#getDays()} can be influenced.

        + * so the result of {@link Duration#getMonths()} and {@link Duration#getDays()} can be influenced. * * @param durationInMilliSeconds Duration in milliseconds to create. * - * @return New Duration representing durationInMilliSeconds. + * @return New {@code Duration} representing {@code durationInMilliSeconds}. */ public abstract Duration newDuration(final long durationInMilliSeconds); /** - *

        Obtain a new instance of a Duration - * specifying the Duration as isPositive, years, months, days, hours, minutes, seconds.

        + * Obtain a new instance of a {@code Duration} + * specifying the {@code Duration} as isPositive, years, months, days, hours, minutes, seconds. * *

        The XML Schema specification states that values can be of an arbitrary size. * Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values. * An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits - * if implementation capacities are exceeded.

        + * if implementation capacities are exceeded. * - *

        A null value indicates that field is not set.

        + *

        A {@code null} value indicates that field is not set. * - * @param isPositive Set to false to create a negative duration. When the length + * @param isPositive Set to {@code false} to create a negative duration. When the length * of the duration is zero, this parameter will be ignored. - * @param years of this Duration - * @param months of this Duration - * @param days of this Duration - * @param hours of this Duration - * @param minutes of this Duration - * @param seconds of this Duration + * @param years of this {@code Duration} + * @param months of this {@code Duration} + * @param days of this {@code Duration} + * @param hours of this {@code Duration} + * @param minutes of this {@code Duration} + * @param seconds of this {@code Duration} * - * @return New Duration created from the specified values. + * @return New {@code Duration} created from the specified values. * * @throws IllegalArgumentException If the values are not a valid representation of a - * Duration: if all the fields (years, months, ...) are null or + * {@code Duration}: if all the fields (years, months, ...) are null or * if any of the fields is negative. * @throws UnsupportedOperationException If implementation cannot support requested values. */ @@ -304,24 +302,24 @@ public abstract class DatatypeFactory { final BigDecimal seconds); /** - *

        Obtain a new instance of a Duration - * specifying the Duration as isPositive, years, months, days, hours, minutes, seconds.

        + * Obtain a new instance of a {@code Duration} + * specifying the {@code Duration} as isPositive, years, months, days, hours, minutes, seconds. * - *

        A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set.

        + *

        A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set. * - * @param isPositive Set to false to create a negative duration. When the length + * @param isPositive Set to {@code false} to create a negative duration. When the length * of the duration is zero, this parameter will be ignored. - * @param years of this Duration - * @param months of this Duration - * @param days of this Duration - * @param hours of this Duration - * @param minutes of this Duration - * @param seconds of this Duration + * @param years of this {@code Duration} + * @param months of this {@code Duration} + * @param days of this {@code Duration} + * @param hours of this {@code Duration} + * @param minutes of this {@code Duration} + * @param seconds of this {@code Duration} * - * @return New Duration created from the specified values. + * @return New {@code Duration} created from the specified values. * * @throws IllegalArgumentException If the values are not a valid representation of a - * Duration: if any of the fields is negative. + * {@code Duration}: if any of the fields is negative. * * @see #newDuration( * boolean isPositive, @@ -371,28 +369,30 @@ public abstract class DatatypeFactory { } /** - *

        Create a Duration of type xdt:dayTimeDuration by parsing its String representation, + * Create a {@code Duration} of type {@code xdt:dayTimeDuration} + * by parsing its {@code String} representation, * "PnDTnHnMnS", - * XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration.

        + * XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration. * - *

        The datatype xdt:dayTimeDuration is a subtype of xs:duration + *

        The datatype {@code xdt:dayTimeDuration} is a subtype of {@code xs:duration} * whose lexical representation contains only day, hour, minute, and second components. - * This datatype resides in the namespace http://www.w3.org/2003/11/xpath-datatypes.

        + * This datatype resides in the namespace {@code http://www.w3.org/2003/11/xpath-datatypes}. * - *

        All four values are set and available from the created {@link Duration}

        + *

        All four values are set and available from the created {@link Duration} * *

        The XML Schema specification states that values can be of an arbitrary size. * Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values. * An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits - * if implementation capacities are exceeded.

        + * if implementation capacities are exceeded. * * @param lexicalRepresentation Lexical representation of a duration. * - * @return New Duration created using the specified lexicalRepresentation. + * @return New {@code Duration} created using the specified {@code lexicalRepresentation}. * - * @throws IllegalArgumentException If lexicalRepresentation is not a valid representation of a Duration expressed only in terms of days and time. + * @throws IllegalArgumentException If {@code lexicalRepresentation} is + * not a valid representation of a {@code Duration} expressed only in terms of days and time. * @throws UnsupportedOperationException If implementation cannot support requested values. - * @throws NullPointerException If lexicalRepresentation is null. + * @throws NullPointerException If {@code lexicalRepresentation} is {@code null}. */ public Duration newDurationDayTime(final String lexicalRepresentation) { // lexicalRepresentation must be non-null @@ -415,17 +415,18 @@ public abstract class DatatypeFactory { } /** - *

        Create a Duration of type xdt:dayTimeDuration using the specified milliseconds as defined in + * Create a {@code Duration} of type {@code xdt:dayTimeDuration} + * using the specified milliseconds as defined in * - * XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration.

        + * XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration. * - *

        The datatype xdt:dayTimeDuration is a subtype of xs:duration + *

        The datatype {@code xdt:dayTimeDuration} is a subtype of {@code xs:duration} * whose lexical representation contains only day, hour, minute, and second components. - * This datatype resides in the namespace http://www.w3.org/2003/11/xpath-datatypes.

        + * This datatype resides in the namespace {@code http://www.w3.org/2003/11/xpath-datatypes}. * *

        All four values are set by computing their values from the specified milliseconds - * and are available using the get methods of the created {@link Duration}. - * The values conform to and are defined by:

        + * and are available using the {@code get} methods of the created {@link Duration}. + * The values conform to and are defined by: *
          *
        • ISO 8601:2000(E) Section 5.5.3.2 Alternative format
        • *
        • @@ -440,13 +441,13 @@ public abstract class DatatypeFactory { * {@link java.util.Calendar#DATE} = 1, etc. * This is important as there are variations in the Gregorian Calendar, * e.g. leap years have different days in the month = {@link java.util.Calendar#FEBRUARY} - * so the result of {@link Duration#getDays()} can be influenced.

          + * so the result of {@link Duration#getDays()} can be influenced. * - *

          Any remaining milliseconds after determining the day, hour, minute and second are discarded.

          + *

          Any remaining milliseconds after determining the day, hour, minute and second are discarded. * - * @param durationInMilliseconds Milliseconds of Duration to create. + * @param durationInMilliseconds Milliseconds of {@code Duration} to create. * - * @return New Duration created with the specified durationInMilliseconds. + * @return New {@code Duration} created with the specified {@code durationInMilliseconds}. * * @see * XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration @@ -457,34 +458,34 @@ public abstract class DatatypeFactory { } /** - *

          Create a Duration of type xdt:dayTimeDuration using the specified - * day, hour, minute and second as defined in + * Create a {@code Duration} of type {@code xdt:dayTimeDuration} using the specified + * {@code day}, {@code hour}, {@code minute} and {@code second} as defined in * - * XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration.

          + * XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration. * - *

          The datatype xdt:dayTimeDuration is a subtype of xs:duration + *

          The datatype {@code xdt:dayTimeDuration} is a subtype of {@code xs:duration} * whose lexical representation contains only day, hour, minute, and second components. - * This datatype resides in the namespace http://www.w3.org/2003/11/xpath-datatypes.

          + * This datatype resides in the namespace {@code http://www.w3.org/2003/11/xpath-datatypes}. * *

          The XML Schema specification states that values can be of an arbitrary size. * Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values. * An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits - * if implementation capacities are exceeded.

          + * if implementation capacities are exceeded. * - *

          A null value indicates that field is not set.

          + *

          A {@code null} value indicates that field is not set. * - * @param isPositive Set to false to create a negative duration. When the length + * @param isPositive Set to {@code false} to create a negative duration. When the length * of the duration is zero, this parameter will be ignored. - * @param day Day of Duration. - * @param hour Hour of Duration. - * @param minute Minute of Duration. - * @param second Second of Duration. + * @param day Day of {@code Duration}. + * @param hour Hour of {@code Duration}. + * @param minute Minute of {@code Duration}. + * @param second Second of {@code Duration}. * - * @return New Duration created with the specified day, hour, minute - * and second. + * @return New {@code Duration} created with the specified {@code day}, {@code hour}, {@code minute} + * and {@code second}. * * @throws IllegalArgumentException If the values are not a valid representation of a - * Duration: if all the fields (day, hour, ...) are null or + * {@code Duration}: if all the fields (day, hour, ...) are null or * if any of the fields is negative. * @throws UnsupportedOperationException If implementation cannot support requested values. */ @@ -507,29 +508,29 @@ public abstract class DatatypeFactory { } /** - *

          Create a Duration of type xdt:dayTimeDuration using the specified - * day, hour, minute and second as defined in + * Create a {@code Duration} of type {@code xdt:dayTimeDuration} using the specified + * {@code day}, {@code hour}, {@code minute} and {@code second} as defined in * - * XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration.

          + * XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration. * - *

          The datatype xdt:dayTimeDuration is a subtype of xs:duration + *

          The datatype {@code xdt:dayTimeDuration} is a subtype of {@code xs:duration} * whose lexical representation contains only day, hour, minute, and second components. - * This datatype resides in the namespace http://www.w3.org/2003/11/xpath-datatypes.

          + * This datatype resides in the namespace {@code http://www.w3.org/2003/11/xpath-datatypes}. * - *

          A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set.

          + *

          A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set. * - * @param isPositive Set to false to create a negative duration. When the length + * @param isPositive Set to {@code false} to create a negative duration. When the length * of the duration is zero, this parameter will be ignored. - * @param day Day of Duration. - * @param hour Hour of Duration. - * @param minute Minute of Duration. - * @param second Second of Duration. + * @param day Day of {@code Duration}. + * @param hour Hour of {@code Duration}. + * @param minute Minute of {@code Duration}. + * @param second Second of {@code Duration}. * - * @return New Duration created with the specified day, hour, minute - * and second. + * @return New {@code Duration} created with the specified {@code day}, {@code hour}, {@code minute} + * and {@code second}. * * @throws IllegalArgumentException If the values are not a valid representation of a - * Duration: if any of the fields (day, hour, ...) is negative. + * {@code Duration}: if any of the fields (day, hour, ...) is negative. */ public Duration newDurationDayTime( final boolean isPositive, @@ -548,28 +549,30 @@ public abstract class DatatypeFactory { } /** - *

          Create a Duration of type xdt:yearMonthDuration by parsing its String representation, + * Create a {@code Duration} of type {@code xdt:yearMonthDuration} + * by parsing its {@code String} representation, * "PnYnM", - * XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration.

          + * XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration. * - *

          The datatype xdt:yearMonthDuration is a subtype of xs:duration + *

          The datatype {@code xdt:yearMonthDuration} is a subtype of {@code xs:duration} * whose lexical representation contains only year and month components. - * This datatype resides in the namespace {@link javax.xml.XMLConstants#W3C_XPATH_DATATYPE_NS_URI}.

          + * This datatype resides in the namespace {@link javax.xml.XMLConstants#W3C_XPATH_DATATYPE_NS_URI}. * - *

          Both values are set and available from the created {@link Duration}

          + *

          Both values are set and available from the created {@link Duration} * *

          The XML Schema specification states that values can be of an arbitrary size. - * Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values. - * An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits - * if implementation capacities are exceeded.

          + * Implementations may chose not to or be incapable of supporting + * arbitrarily large and/or small values. An {@link UnsupportedOperationException} + * will be thrown with a message indicating implementation limits + * if implementation capacities are exceeded. * * @param lexicalRepresentation Lexical representation of a duration. * - * @return New Duration created using the specified lexicalRepresentation. + * @return New {@code Duration} created using the specified {@code lexicalRepresentation}. * - * @throws IllegalArgumentException If lexicalRepresentation is not a valid representation of a Duration expressed only in terms of years and months. + * @throws IllegalArgumentException If {@code lexicalRepresentation} is not a valid representation of a {@code Duration} expressed only in terms of years and months. * @throws UnsupportedOperationException If implementation cannot support requested values. - * @throws NullPointerException If lexicalRepresentation is null. + * @throws NullPointerException If {@code lexicalRepresentation} is {@code null}. */ public Duration newDurationYearMonth( final String lexicalRepresentation) { @@ -594,17 +597,18 @@ public abstract class DatatypeFactory { } /** - *

          Create a Duration of type xdt:yearMonthDuration using the specified milliseconds as defined in + * Create a {@code Duration} of type {@code xdt:yearMonthDuration} + * using the specified milliseconds as defined in * - * XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration.

          + * XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration. * - *

          The datatype xdt:yearMonthDuration is a subtype of xs:duration + *

          The datatype {@code xdt:yearMonthDuration} is a subtype of {@code xs:duration} * whose lexical representation contains only year and month components. - * This datatype resides in the namespace {@link javax.xml.XMLConstants#W3C_XPATH_DATATYPE_NS_URI}.

          + * This datatype resides in the namespace {@link javax.xml.XMLConstants#W3C_XPATH_DATATYPE_NS_URI}. * *

          Both values are set by computing their values from the specified milliseconds - * and are available using the get methods of the created {@link Duration}. - * The values conform to and are defined by:

          + * and are available using the {@code get} methods of the created {@link Duration}. + * The values conform to and are defined by: *
            *
          • ISO 8601:2000(E) Section 5.5.3.2 Alternative format
          • *
          • @@ -619,13 +623,13 @@ public abstract class DatatypeFactory { * {@link java.util.Calendar#DATE} = 1, etc. * This is important as there are variations in the Gregorian Calendar, * e.g. leap years have different days in the month = {@link java.util.Calendar#FEBRUARY} - * so the result of {@link Duration#getMonths()} can be influenced.

            + * so the result of {@link Duration#getMonths()} can be influenced. * - *

            Any remaining milliseconds after determining the year and month are discarded.

            + *

            Any remaining milliseconds after determining the year and month are discarded. * - * @param durationInMilliseconds Milliseconds of Duration to create. + * @param durationInMilliseconds Milliseconds of {@code Duration} to create. * - * @return New Duration created using the specified durationInMilliseconds. + * @return New {@code Duration} created using the specified {@code durationInMilliseconds}. */ public Duration newDurationYearMonth( final long durationInMilliseconds) { @@ -646,27 +650,27 @@ public abstract class DatatypeFactory { } /** - *

            Create a Duration of type xdt:yearMonthDuration using the specified - * year and month as defined in + * Create a {@code Duration} of type {@code xdt:yearMonthDuration} using the specified + * {@code year} and {@code month} as defined in * - * XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration.

            + * XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration. * *

            The XML Schema specification states that values can be of an arbitrary size. * Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values. * An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits - * if implementation capacities are exceeded.

            + * if implementation capacities are exceeded. * - *

            A null value indicates that field is not set.

            + *

            A {@code null} value indicates that field is not set. * - * @param isPositive Set to false to create a negative duration. When the length + * @param isPositive Set to {@code false} to create a negative duration. When the length * of the duration is zero, this parameter will be ignored. - * @param year Year of Duration. - * @param month Month of Duration. + * @param year Year of {@code Duration}. + * @param month Month of {@code Duration}. * - * @return New Duration created using the specified year and month. + * @return New {@code Duration} created using the specified {@code year} and {@code month}. * * @throws IllegalArgumentException If the values are not a valid representation of a - * Duration: if all of the fields (year, month) are null or + * {@code Duration}: if all of the fields (year, month) are null or * if any of the fields is negative. * @throws UnsupportedOperationException If implementation cannot support requested values. */ @@ -687,22 +691,22 @@ public abstract class DatatypeFactory { } /** - *

            Create a Duration of type xdt:yearMonthDuration using the specified - * year and month as defined in + * Create a {@code Duration} of type {@code xdt:yearMonthDuration} using the specified + * {@code year} and {@code month} as defined in * - * XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration.

            + * XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration. * - *

            A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set.

            + *

            A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set. * - * @param isPositive Set to false to create a negative duration. When the length + * @param isPositive Set to {@code false} to create a negative duration. When the length * of the duration is zero, this parameter will be ignored. - * @param year Year of Duration. - * @param month Month of Duration. + * @param year Year of {@code Duration}. + * @param month Month of {@code Duration}. * - * @return New Duration created using the specified year and month. + * @return New {@code Duration} created using the specified {@code year} and {@code month}. * * @throws IllegalArgumentException If the values are not a valid representation of a - * Duration: if any of the fields (year, month) is negative. + * {@code Duration}: if any of the fields (year, month) is negative. */ public Duration newDurationYearMonth( final boolean isPositive, @@ -716,44 +720,44 @@ public abstract class DatatypeFactory { } /** - *

            Create a new instance of an XMLGregorianCalendar.

            + * Create a new instance of an {@code XMLGregorianCalendar}. * - *

            All date/time datatype fields set to {@link DatatypeConstants#FIELD_UNDEFINED} or null.

            + *

            All date/time datatype fields set to {@link DatatypeConstants#FIELD_UNDEFINED} or null. * - * @return New XMLGregorianCalendar with all date/time datatype fields set to + * @return New {@code XMLGregorianCalendar} with all date/time datatype fields set to * {@link DatatypeConstants#FIELD_UNDEFINED} or null. */ public abstract XMLGregorianCalendar newXMLGregorianCalendar(); /** - *

            Create a new XMLGregorianCalendar by parsing the String as a lexical representation.

            + * Create a new XMLGregorianCalendar by parsing the String as a lexical representation. * *

            Parsing the lexical string representation is defined in * XML Schema 1.0 Part 2, Section 3.2.[7-14].1, - * Lexical Representation.

            + * Lexical Representation. * - *

            The string representation may not have any leading and trailing whitespaces.

            + *

            The string representation may not have any leading and trailing whitespaces. * *

            The parsing is done field by field so that - * the following holds for any lexically correct String x:

            + * the following holds for any lexically correct String x: *
                  * newXMLGregorianCalendar(x).toXMLFormat().equals(x)
                  * 
            *

            Except for the noted lexical/canonical representation mismatches * listed in - * XML Schema 1.0 errata, Section 3.2.7.2.

            + * XML Schema 1.0 errata, Section 3.2.7.2. * * @param lexicalRepresentation Lexical representation of one the eight XML Schema date/time datatypes. * - * @return XMLGregorianCalendar created from the lexicalRepresentation. + * @return {@code XMLGregorianCalendar} created from the {@code lexicalRepresentation}. * - * @throws IllegalArgumentException If the lexicalRepresentation is not a valid XMLGregorianCalendar. - * @throws NullPointerException If lexicalRepresentation is null. + * @throws IllegalArgumentException If the {@code lexicalRepresentation} is not a valid {@code XMLGregorianCalendar}. + * @throws NullPointerException If {@code lexicalRepresentation} is {@code null}. */ public abstract XMLGregorianCalendar newXMLGregorianCalendar(final String lexicalRepresentation); /** - *

            Create an XMLGregorianCalendar from a {@link GregorianCalendar}.

            + * Create an {@code XMLGregorianCalendar} from a {@link GregorianCalendar}. * * * @@ -764,30 +768,30 @@ public abstract class DatatypeFactory { * * * - * - * + * + * * * * * - * + * * * * - * + * * * * - * + * * * * - * + * * * * * * *
            java.util.GregorianCalendar fieldjavax.xml.datatype.XMLGregorianCalendar field{@code java.util.GregorianCalendar} field{@code javax.xml.datatype.XMLGregorianCalendar} field
            ERA == GregorianCalendar.BC ? -YEAR : YEAR{@code ERA == GregorianCalendar.BC ? -YEAR : YEAR}{@link XMLGregorianCalendar#setYear(int year)}
            MONTH + 1{@code MONTH + 1}{@link XMLGregorianCalendar#setMonth(int month)}
            DAY_OF_MONTH{@code DAY_OF_MONTH}{@link XMLGregorianCalendar#setDay(int day)}
            HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND{@code HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND}{@link XMLGregorianCalendar#setTime(int hour, int minute, int second, BigDecimal fractional)}
            - * (ZONE_OFFSET + DST_OFFSET) / (60*1000)
            + * {@code (ZONE_OFFSET + DST_OFFSET) / (60*1000)}
            * (in minutes) *
            {@link XMLGregorianCalendar#setTimezone(int offset)}* @@ -796,49 +800,50 @@ public abstract class DatatypeFactory { *
            *

            *conversion loss of information. It is not possible to represent - * a java.util.GregorianCalendar daylight savings timezone id in the - * XML Schema 1.0 date/time datatype representation.

            + * a {@code java.util.GregorianCalendar} daylight savings timezone id in the + * XML Schema 1.0 date/time datatype representation. * - *

            To compute the return value's TimeZone field, + *

            To compute the return value's {@code TimeZone} field, *

              - *
            • when this.getTimezone() != FIELD_UNDEFINED, - * create a java.util.TimeZone with a custom timezone id - * using the this.getTimezone().
            • - *
            • else use the GregorianCalendar default timezone value + *
            • when {@code this.getTimezone() != FIELD_UNDEFINED}, + * create a {@code java.util.TimeZone} with a custom timezone id + * using the {@code this.getTimezone()}.
            • + *
            • else use the {@code GregorianCalendar} default timezone value * for the host is defined as specified by - * java.util.TimeZone.getDefault().
            • + * {@code java.util.TimeZone.getDefault()}. + *
            * - * @param cal java.util.GregorianCalendar used to create XMLGregorianCalendar + * @param cal {@code java.util.GregorianCalendar} used to create {@code XMLGregorianCalendar} * - * @return XMLGregorianCalendar created from java.util.GregorianCalendar + * @return {@code XMLGregorianCalendar} created from {@code java.util.GregorianCalendar} * - * @throws NullPointerException If cal is null. + * @throws NullPointerException If {@code cal} is {@code null}. */ public abstract XMLGregorianCalendar newXMLGregorianCalendar(final GregorianCalendar cal); /** - *

            Constructor allowing for complete value spaces allowed by + * Constructor allowing for complete value spaces allowed by * W3C XML Schema 1.0 recommendation for xsd:dateTime and related - * builtin datatypes. Note that year parameter supports + * builtin datatypes. Note that {@code year} parameter supports * arbitrarily large numbers and fractionalSecond has infinite - * precision.

            + * precision. * - *

            A null value indicates that field is not set.

            + *

            A {@code null} value indicates that field is not set. * - * @param year of XMLGregorianCalendar to be created. - * @param month of XMLGregorianCalendar to be created. - * @param day of XMLGregorianCalendar to be created. - * @param hour of XMLGregorianCalendar to be created. - * @param minute of XMLGregorianCalendar to be created. - * @param second of XMLGregorianCalendar to be created. - * @param fractionalSecond of XMLGregorianCalendar to be created. - * @param timezone of XMLGregorianCalendar to be created. + * @param year of {@code XMLGregorianCalendar} to be created. + * @param month of {@code XMLGregorianCalendar} to be created. + * @param day of {@code XMLGregorianCalendar} to be created. + * @param hour of {@code XMLGregorianCalendar} to be created. + * @param minute of {@code XMLGregorianCalendar} to be created. + * @param second of {@code XMLGregorianCalendar} to be created. + * @param fractionalSecond of {@code XMLGregorianCalendar} to be created. + * @param timezone of {@code XMLGregorianCalendar} to be created. * - * @return XMLGregorianCalendar created from specified values. + * @return {@code XMLGregorianCalendar} created from specified values. * * @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field * as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar} - * or if the composite values constitute an invalid XMLGregorianCalendar instance + * or if the composite values constitute an invalid {@code XMLGregorianCalendar} instance * as determined by {@link XMLGregorianCalendar#isValid()}. */ public abstract XMLGregorianCalendar newXMLGregorianCalendar( @@ -852,29 +857,29 @@ public abstract class DatatypeFactory { final int timezone); /** - *

            Constructor of value spaces that a - * java.util.GregorianCalendar instance would need to convert to an - * XMLGregorianCalendar instance.

            + * Constructor of value spaces that a + * {@code java.util.GregorianCalendar} instance would need to convert to an + * {@code XMLGregorianCalendar} instance. * - *

            XMLGregorianCalendar eon and - * fractionalSecond are set to null

            + *

            {@code XMLGregorianCalendar eon} and + * {@code fractionalSecond} are set to {@code null} * - *

            A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set.

            + *

            A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set. * - * @param year of XMLGregorianCalendar to be created. - * @param month of XMLGregorianCalendar to be created. - * @param day of XMLGregorianCalendar to be created. - * @param hour of XMLGregorianCalendar to be created. - * @param minute of XMLGregorianCalendar to be created. - * @param second of XMLGregorianCalendar to be created. - * @param millisecond of XMLGregorianCalendar to be created. - * @param timezone of XMLGregorianCalendar to be created. + * @param year of {@code XMLGregorianCalendar} to be created. + * @param month of {@code XMLGregorianCalendar} to be created. + * @param day of {@code XMLGregorianCalendar} to be created. + * @param hour of {@code XMLGregorianCalendar} to be created. + * @param minute of {@code XMLGregorianCalendar} to be created. + * @param second of {@code XMLGregorianCalendar} to be created. + * @param millisecond of {@code XMLGregorianCalendar} to be created. + * @param timezone of {@code XMLGregorianCalendar} to be created. * - * @return XMLGregorianCalendar created from specified values. + * @return {@code XMLGregorianCalendar} created from specified values. * * @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field * as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar} - * or if the composite values constitute an invalid XMLGregorianCalendar instance + * or if the composite values constitute an invalid {@code XMLGregorianCalendar} instance * as determined by {@link XMLGregorianCalendar#isValid()}. */ public XMLGregorianCalendar newXMLGregorianCalendar( @@ -918,26 +923,26 @@ public abstract class DatatypeFactory { } /** - *

            Create a Java representation of XML Schema builtin datatype date or g*.

            + * Create a Java representation of XML Schema builtin datatype {@code date} or {@code g*}. * - *

            For example, an instance of gYear can be created invoking this factory - * with month and day parameters set to - * {@link DatatypeConstants#FIELD_UNDEFINED}.

            + *

            For example, an instance of {@code gYear} can be created invoking this factory + * with {@code month} and {@code day} parameters set to + * {@link DatatypeConstants#FIELD_UNDEFINED}. * - *

            A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set.

            + *

            A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set. * - * @param year of XMLGregorianCalendar to be created. - * @param month of XMLGregorianCalendar to be created. - * @param day of XMLGregorianCalendar to be created. + * @param year of {@code XMLGregorianCalendar} to be created. + * @param month of {@code XMLGregorianCalendar} to be created. + * @param day of {@code XMLGregorianCalendar} to be created. * @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set. * - * @return XMLGregorianCalendar created from parameter values. + * @return {@code XMLGregorianCalendar} created from parameter values. * * @see DatatypeConstants#FIELD_UNDEFINED * * @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field * as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar} - * or if the composite values constitute an invalid XMLGregorianCalendar instance + * or if the composite values constitute an invalid {@code XMLGregorianCalendar} instance * as determined by {@link XMLGregorianCalendar#isValid()}. */ public XMLGregorianCalendar newXMLGregorianCalendarDate( @@ -958,20 +963,20 @@ public abstract class DatatypeFactory { } /** - *

            Create a Java instance of XML Schema builtin datatype time.

            + * Create a Java instance of XML Schema builtin datatype {@code time}. * - *

            A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set.

            + *

            A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set. * * @param hours number of hours * @param minutes number of minutes * @param seconds number of seconds * @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set. * - * @return XMLGregorianCalendar created from parameter values. + * @return {@code XMLGregorianCalendar} created from parameter values. * * @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field * as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar} - * or if the composite values constitute an invalid XMLGregorianCalendar instance + * or if the composite values constitute an invalid {@code XMLGregorianCalendar} instance * as determined by {@link XMLGregorianCalendar#isValid()}. * * @see DatatypeConstants#FIELD_UNDEFINED @@ -994,24 +999,24 @@ public abstract class DatatypeFactory { } /** - *

            Create a Java instance of XML Schema builtin datatype time.

            + * Create a Java instance of XML Schema builtin datatype time. * - *

            A null value indicates that field is not set.

            - *

            A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set.

            + *

            A {@code null} value indicates that field is not set. + *

            A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set. * * @param hours number of hours * @param minutes number of minutes * @param seconds number of seconds - * @param fractionalSecond value of null indicates that this optional field is not set. + * @param fractionalSecond value of {@code null} indicates that this optional field is not set. * @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set. * - * @return XMLGregorianCalendar created from parameter values. + * @return {@code XMLGregorianCalendar} created from parameter values. * * @see DatatypeConstants#FIELD_UNDEFINED * * @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field * as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar} - * or if the composite values constitute an invalid XMLGregorianCalendar instance + * or if the composite values constitute an invalid {@code XMLGregorianCalendar} instance * as determined by {@link XMLGregorianCalendar#isValid()}. */ public XMLGregorianCalendar newXMLGregorianCalendarTime( @@ -1033,9 +1038,9 @@ public abstract class DatatypeFactory { } /** - *

            Create a Java instance of XML Schema builtin datatype time.

            + * Create a Java instance of XML Schema builtin datatype time. * - *

            A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set.

            + *

            A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field is not set. * * @param hours number of hours * @param minutes number of minutes @@ -1043,13 +1048,13 @@ public abstract class DatatypeFactory { * @param milliseconds number of milliseconds * @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set. * - * @return XMLGregorianCalendar created from parameter values. + * @return {@code XMLGregorianCalendar} created from parameter values. * * @see DatatypeConstants#FIELD_UNDEFINED * * @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field * as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar} - * or if the composite values constitute an invalid XMLGregorianCalendar instance + * or if the composite values constitute an invalid {@code XMLGregorianCalendar} instance * as determined by {@link XMLGregorianCalendar#isValid()}. */ public XMLGregorianCalendar newXMLGregorianCalendarTime( diff --git a/jaxp/src/java.xml/share/classes/javax/xml/datatype/Duration.java b/jaxp/src/java.xml/share/classes/javax/xml/datatype/Duration.java index 350f4af01cc..90f016edfed 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/datatype/Duration.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/datatype/Duration.java @@ -35,37 +35,37 @@ import javax.xml.namespace.QName; /** *

            Immutable representation of a time span as defined in - * the W3C XML Schema 1.0 specification.

            + * the W3C XML Schema 1.0 specification. * *

            A Duration object represents a period of Gregorian time, * which consists of six fields (years, months, days, hours, - * minutes, and seconds) plus a sign (+/-) field.

            + * minutes, and seconds) plus a sign (+/-) field. * - *

            The first five fields have non-negative (>=0) integers or null + *

            The first five fields have non-negative ({@literal >=}0) integers or null * (which represents that the field is not set), * and the seconds field has a non-negative decimal or null. - * A negative sign indicates a negative duration.

            + * A negative sign indicates a negative duration. * *

            This class provides a number of methods that make it easy * to use for the duration datatype of XML Schema 1.0 with - * the errata.

            + * the errata. * *

            Order relationship

            *

            Duration objects only have partial order, where two values A and B - * maybe either:

            + * maybe either: *
              - *
            1. A<B (A is shorter than B) - *
            2. A>B (A is longer than B) + *
            3. A{@literal <}B (A is shorter than B) + *
            4. A{@literal >}B (A is longer than B) *
            5. A==B (A and B are of the same duration) - *
            6. A<>B (Comparison between A and B is indeterminate) + *
            7. A{@literal <>}B (Comparison between A and B is indeterminate) *
            * *

            For example, 30 days cannot be meaningfully compared to one month. * The {@link #compare(Duration duration)} method implements this - * relationship.

            + * relationship. * *

            See the {@link #isLongerThan(Duration)} method for details about - * the order relationship among Duration objects.

            + * the order relationship among {@code Duration} objects. * *

            Operations over Duration

            *

            This class provides a set of basic arithmetic operations, such @@ -73,20 +73,20 @@ import javax.xml.namespace.QName; * Because durations don't have total order, an operation could * fail for some combinations of operations. For example, you cannot * subtract 15 days from 1 month. See the javadoc of those methods - * for detailed conditions where this could happen.

            + * for detailed conditions where this could happen. * *

            Also, division of a duration by a number is not provided because - * the Duration class can only deal with finite precision - * decimal numbers. For example, one cannot represent 1 sec divided by 3.

            + * the {@code Duration} class can only deal with finite precision + * decimal numbers. For example, one cannot represent 1 sec divided by 3. * *

            However, you could substitute a division by 3 with multiplying - * by numbers such as 0.3 or 0.333.

            + * by numbers such as 0.3 or 0.333. * *

            Range of allowed values

            *

            - * Because some operations of Duration rely on {@link Calendar} + * Because some operations of {@code Duration} rely on {@link Calendar} * even though {@link Duration} can hold very large or very small values, - * some of the methods may not work correctly on such Durations. + * some of the methods may not work correctly on such {@code Duration}s. * The impacted methods document their dependency on {@link Calendar}. * * @author Joseph Fialli @@ -99,7 +99,7 @@ import javax.xml.namespace.QName; public abstract class Duration { /** - *

            Debugging true or false.

            + * Debugging {@code true} or {@code false}. */ private static final boolean DEBUG = true; @@ -107,24 +107,24 @@ public abstract class Duration { * Default no-arg constructor. * *

            Note: Always use the {@link DatatypeFactory} to - * construct an instance of Duration. + * construct an instance of {@code Duration}. * The constructor on this class cannot be guaranteed to * produce an object with a consistent state and may be - * removed in the future.

            + * removed in the future. */ public Duration() { } /** - *

            Return the name of the XML Schema date/time type that this instance + * Return the name of the XML Schema date/time type that this instance * maps to. Type is computed based on fields that are set, - * i.e. {@link #isSet(DatatypeConstants.Field field)} == true.

            + * i.e. {@link #isSet(DatatypeConstants.Field field)} == {@code true}. * * * * * * @@ -238,16 +238,16 @@ public abstract class Duration { public abstract int getSign(); /** - *

            Get the years value of this Duration as an int or 0 if not present.

            + * Get the years value of this {@code Duration} as an {@code int} or {@code 0} if not present. * - *

            getYears() is a convenience method for - * {@link #getField(DatatypeConstants.Field field) getField(DatatypeConstants.YEARS)}.

            + *

            {@code getYears()} is a convenience method for + * {@link #getField(DatatypeConstants.Field field) getField(DatatypeConstants.YEARS)}. * - *

            As the return value is an int, an incorrect value will be returned for Durations - * with years that go beyond the range of an int. - * Use {@link #getField(DatatypeConstants.Field field) getField(DatatypeConstants.YEARS)} to avoid possible loss of precision.

            + *

            As the return value is an {@code int}, an incorrect value will be returned for {@code Duration}s + * with years that go beyond the range of an {@code int}. + * Use {@link #getField(DatatypeConstants.Field field) getField(DatatypeConstants.YEARS)} to avoid possible loss of precision. * - * @return If the years field is present, return its value as an int, else return 0. + * @return If the years field is present, return its value as an {@code int}, else return {@code 0}. */ public int getYears() { return getField(DatatypeConstants.YEARS).intValue(); @@ -260,7 +260,7 @@ public abstract class Duration { * This method works just like {@link #getYears()} except * that this method works on the MONTHS field. * - * @return Months of this Duration. + * @return Months of this {@code Duration}. */ public int getMonths() { return getField(DatatypeConstants.MONTHS).intValue(); @@ -273,7 +273,7 @@ public abstract class Duration { * This method works just like {@link #getYears()} except * that this method works on the DAYS field. * - * @return Days of this Duration. + * @return Days of this {@code Duration}. */ public int getDays() { return getField(DatatypeConstants.DAYS).intValue(); @@ -286,7 +286,7 @@ public abstract class Duration { * This method works just like {@link #getYears()} except * that this method works on the HOURS field. * - * @return Hours of this Duration. + * @return Hours of this {@code Duration}. * */ public int getHours() { @@ -300,7 +300,7 @@ public abstract class Duration { * This method works just like {@link #getYears()} except * that this method works on the MINUTES field. * - * @return Minutes of this Duration. + * @return Minutes of this {@code Duration}. * */ public int getMinutes() { @@ -323,32 +323,32 @@ public abstract class Duration { } /** - *

            Returns the length of the duration in milli-seconds.

            + * Returns the length of the duration in milli-seconds. * *

            If the seconds field carries more digits than milli-second order, * those will be simply discarded (or in other words, rounded to zero.) - * For example, for any Calendar value x,

            + * For example, for any Calendar value {@code x}, *
            -     * new Duration("PT10.00099S").getTimeInMills(x) == 10000.
            -     * new Duration("-PT10.00099S").getTimeInMills(x) == -10000.
            +     * {@code new Duration("PT10.00099S").getTimeInMills(x) == 10000}
            +     * {@code new Duration("-PT10.00099S").getTimeInMills(x) == -10000}
                  * 
            * *

            * Note that this method uses the {@link #addTo(Calendar)} method, - * which may work incorrectly with Duration objects with + * which may work incorrectly with {@code Duration} objects with * very large values in its fields. See the {@link #addTo(Calendar)} * method for details. * * @param startInstant - * The length of a month/year varies. The startInstant is + * The length of a month/year varies. The {@code startInstant} is * used to disambiguate this variance. Specifically, this method - * returns the difference between startInstant and - * startInstant+duration + * returns the difference between {@code startInstant} and + * {@code startInstant+duration} * - * @return milliseconds between startInstant and - * startInstant plus this Duration + * @return milliseconds between {@code startInstant} and + * {@code startInstant} plus this {@code Duration} * - * @throws NullPointerException if startInstant parameter + * @throws NullPointerException if {@code startInstant} parameter * is null. * */ @@ -360,33 +360,33 @@ public abstract class Duration { } /** - *

            Returns the length of the duration in milli-seconds.

            + * Returns the length of the duration in milli-seconds. * *

            If the seconds field carries more digits than milli-second order, * those will be simply discarded (or in other words, rounded to zero.) - * For example, for any Date value x,

            + * For example, for any {@code Date} value {@code x}, *
            -     * new Duration("PT10.00099S").getTimeInMills(x) == 10000.
            -     * new Duration("-PT10.00099S").getTimeInMills(x) == -10000.
            +     * {@code new Duration("PT10.00099S").getTimeInMills(x) == 10000}
            +     * {@code new Duration("-PT10.00099S").getTimeInMills(x) == -10000}
                  * 
            * *

            * Note that this method uses the {@link #addTo(Date)} method, - * which may work incorrectly with Duration objects with + * which may work incorrectly with {@code Duration} objects with * very large values in its fields. See the {@link #addTo(Date)} * method for details. * * @param startInstant - * The length of a month/year varies. The startInstant is + * The length of a month/year varies. The {@code startInstant} is * used to disambiguate this variance. Specifically, this method - * returns the difference between startInstant and - * startInstant+duration. + * returns the difference between {@code startInstant} and + * {@code startInstant+duration}. * * @throws NullPointerException * If the startInstant parameter is null. * - * @return milliseconds between startInstant and - * startInstant plus this Duration + * @return milliseconds between {@code startInstant} and + * {@code startInstant} plus this {@code Duration} * * @see #getTimeInMillis(Calendar) */ @@ -418,7 +418,7 @@ public abstract class Duration { * returns a {@link java.math.BigInteger} object. For SECONDS, this * method returns a {@link java.math.BigDecimal}. * - * @throws NullPointerException If the field is null. + * @throws NullPointerException If the {@code field} is {@code null}. */ public abstract Number getField(final DatatypeConstants.Field field); @@ -440,9 +440,9 @@ public abstract class Duration { public abstract boolean isSet(final DatatypeConstants.Field field); /** - *

            Computes a new duration whose value is this+rhs.

            + * Computes a new duration whose value is {@code this+rhs}. * - *

            For example,

            + *

            For example, *

                  * "1 day" + "-3 days" = "-2 days"
                  * "1 year" + "1 day" = "1 year and 1 day"
            @@ -453,28 +453,28 @@ public abstract class Duration {
                  *
                  * 

            Since there's no way to meaningfully subtract 1 day from 1 month, * there are cases where the operation fails in - * {@link IllegalStateException}.

            + * {@link IllegalStateException}. * *

            - * Formally, the computation is defined as follows.

            + * Formally, the computation is defined as follows. *

            - * Firstly, we can assume that two Durations to be added + * Firstly, we can assume that two {@code Duration}s to be added * are both positive without losing generality (i.e., - * (-X)+Y=Y-X, X+(-Y)=X-Y, - * (-X)+(-Y)=-(X+Y)) + * {@code (-X)+Y=Y-X}, {@code X+(-Y)=X-Y}, + * {@code (-X)+(-Y)=-(X+Y)}) * *

            - * Addition of two positive Durations are simply defined as + * Addition of two positive {@code Duration}s are simply defined as * field by field addition where missing fields are treated as 0. *

            - * A field of the resulting Duration will be unset if and - * only if respective fields of two input Durations are unset. + * A field of the resulting {@code Duration} will be unset if and + * only if respective fields of two input {@code Duration}s are unset. *

            - * Note that lhs.add(rhs) will be always successful if - * lhs.signum()*rhs.signum()!=-1 or both of them are - * normalized.

            + * Note that {@code lhs.add(rhs)} will be always successful if + * {@code lhs.signum()*rhs.signum()!=-1} or both of them are + * normalized. * - * @param rhs Duration to add to this Duration + * @param rhs {@code Duration} to add to this {@code Duration} * * @return * non-null valid Duration object. @@ -501,25 +501,22 @@ public abstract class Duration { * uses int to hold values, there are cases where this method * won't work correctly (for example if values of fields * exceed the range of int.) - *

            * *

            * Also, since this duration class is a Gregorian duration, this * method will not work correctly if the given {@link Calendar} * object is based on some other calendar systems. - *

            * *

            - * Any fractional parts of this Duration object + * Any fractional parts of this {@code Duration} object * beyond milliseconds will be simply ignored. For example, if * this duration is "P1.23456S", then 1 is added to SECONDS, * 234 is added to MILLISECONDS, and the rest will be unused. - *

            * *

            * Note that because {@link Calendar#add(int, int)} is using - * int, Duration with values beyond the - * range of int in its fields + * {@code int}, {@code Duration} with values beyond the + * range of {@code int} in its fields * will cause overflow/underflow to the given {@link Calendar}. * {@link XMLGregorianCalendar#add(Duration)} provides the same * basic operation as this method while avoiding @@ -571,9 +568,9 @@ public abstract class Duration { } /** - *

            Computes a new duration whose value is this-rhs.

            + * Computes a new duration whose value is {@code this-rhs}. * - *

            For example:

            + *

            For example: *

                  * "1 day" - "-3 days" = "4 days"
                  * "1 year" - "1 day" = IllegalStateException
            @@ -583,31 +580,31 @@ public abstract class Duration {
                  * 
            * *

            Since there's no way to meaningfully subtract 1 day from 1 month, - * there are cases where the operation fails in {@link IllegalStateException}.

            + * there are cases where the operation fails in {@link IllegalStateException}. * *

            Formally the computation is defined as follows. - * First, we can assume that two Durations are both positive + * First, we can assume that two {@code Duration}s are both positive * without losing generality. (i.e., - * (-X)-Y=-(X+Y), X-(-Y)=X+Y, - * (-X)-(-Y)=-(X-Y))

            + * {@code (-X)-Y=-(X+Y)}, {@code X-(-Y)=X+Y}, + * {@code (-X)-(-Y)=-(X-Y)}) * *

            Then two durations are subtracted field by field. - * If the sign of any non-zero field F is different from + * If the sign of any non-zero field {@code F} is different from * the sign of the most significant field, - * 1 (if F is negative) or -1 (otherwise) - * will be borrowed from the next bigger unit of F.

            + * 1 (if {@code F} is negative) or -1 (otherwise) + * will be borrowed from the next bigger unit of {@code F}. * *

            This process is repeated until all the non-zero fields have - * the same sign.

            + * the same sign. * *

            If a borrow occurs in the days field (in other words, if * the computation needs to borrow 1 or -1 month to compensate * days), then the computation fails by throwing an - * {@link IllegalStateException}.

            + * {@link IllegalStateException}. * - * @param rhs Duration to subtract from this Duration. + * @param rhs {@code Duration} to subtract from this {@code Duration}. * - * @return New Duration created from subtracting rhs from this Duration. + * @return New {@code Duration} created from subtracting {@code rhs} from this {@code Duration}. * * @throws IllegalStateException * If two durations cannot be meaningfully subtracted. For @@ -624,18 +621,18 @@ public abstract class Duration { } /** - *

            Computes a new duration whose value is factor times - * longer than the value of this duration.

            + * Computes a new duration whose value is {@code factor} times + * longer than the value of this duration. * *

            This method is provided for the convenience. - * It is functionally equivalent to the following code:

            + * It is functionally equivalent to the following code: *
                  * multiply(new BigDecimal(String.valueOf(factor)))
                  * 
            * - * @param factor Factor times longer of new Duration to create. + * @param factor Factor times longer of new {@code Duration} to create. * - * @return New Duration that is factortimes longer than this Duration. + * @return New {@code Duration} that is {@code factor}times longer than this {@code Duration}. * * @see #multiply(BigDecimal) */ @@ -644,7 +641,7 @@ public abstract class Duration { } /** - * Computes a new duration whose value is factor times + * Computes a new duration whose value is {@code factor} times * longer than the value of this duration. * *

            @@ -656,7 +653,7 @@ public abstract class Duration { *

            * *

            - * Since the Duration class is immutable, this method + * Since the {@code Duration} class is immutable, this method * doesn't change the value of this object. It simply computes * a new Duration object and returns it. * @@ -671,7 +668,7 @@ public abstract class Duration { * When fractions of month cannot be meaningfully carried down * to days, or year to months, this will cause an * {@link IllegalStateException} to be thrown. - * For example if you multiple one month by 0.5.

            + * For example if you multiple one month by 0.5. * *

            * To avoid {@link IllegalStateException}, use @@ -681,39 +678,39 @@ public abstract class Duration { * @param factor to multiply by * * @return - * returns a non-null valid Duration object + * returns a non-null valid {@code Duration} object * * @throws IllegalStateException if operation produces fraction in * the months field. * - * @throws NullPointerException if the factor parameter is - * null. + * @throws NullPointerException if the {@code factor} parameter is + * {@code null}. * */ public abstract Duration multiply(final BigDecimal factor); /** - * Returns a new Duration object whose - * value is -this. + * Returns a new {@code Duration} object whose + * value is {@code -this}. * *

            - * Since the Duration class is immutable, this method + * Since the {@code Duration} class is immutable, this method * doesn't change the value of this object. It simply computes * a new Duration object and returns it. * * @return - * always return a non-null valid Duration object. + * always return a non-null valid {@code Duration} object. */ public abstract Duration negate(); /** - *

            Converts the years and months fields into the days field - * by using a specific time instant as the reference point.

            + * Converts the years and months fields into the days field + * by using a specific time instant as the reference point. * *

            For example, duration of one month normalizes to 31 days - * given the start time instance "July 8th 2003, 17:40:32".

            + * given the start time instance "July 8th 2003, 17:40:32". * - *

            Formally, the computation is done as follows:

            + *

            Formally, the computation is done as follows: *

              *
            1. the given Calendar object is cloned
            2. *
            3. the years, months and days fields will be added to the {@link Calendar} object @@ -725,37 +722,37 @@ public abstract class Duration { * Duration object.
            4. *
            * - *

            Note that since the Calendar class uses int to + *

            Note that since the Calendar class uses {@code int} to * hold the value of year and month, this method may produce * an unexpected result if this duration object holds - * a very large value in the years or months fields.

            + * a very large value in the years or months fields. * - * @param startTimeInstant Calendar reference point. + * @param startTimeInstant {@code Calendar} reference point. * - * @return Duration of years and months of this Duration as days. + * @return {@code Duration} of years and months of this {@code Duration} as days. * * @throws NullPointerException If the startTimeInstant parameter is null. */ public abstract Duration normalizeWith(final Calendar startTimeInstant); /** - *

            Partial order relation comparison with this Duration instance.

            + * Partial order relation comparison with this {@code Duration} instance. * *

            Comparison result must be in accordance with * W3C XML Schema 1.0 Part 2, Section 3.2.7.6.2, - * Order relation on duration.

            + * Order relation on duration. * - *

            Return:

            + *

            Return: *

              - *
            • {@link DatatypeConstants#LESSER} if this Duration is shorter than duration parameter
            • - *
            • {@link DatatypeConstants#EQUAL} if this Duration is equal to duration parameter
            • - *
            • {@link DatatypeConstants#GREATER} if this Duration is longer than duration parameter
            • + *
            • {@link DatatypeConstants#LESSER} if this {@code Duration} is shorter than {@code duration} parameter
            • + *
            • {@link DatatypeConstants#EQUAL} if this {@code Duration} is equal to {@code duration} parameter
            • + *
            • {@link DatatypeConstants#GREATER} if this {@code Duration} is longer than {@code duration} parameter
            • *
            • {@link DatatypeConstants#INDETERMINATE} if a conclusive partial order relation cannot be determined
            • *
            * * @param duration to compare * - * @return the relationship between thisDurationand duration parameter as + * @return the relationship between {@code this Duration} and {@code duration} parameter as * {@link DatatypeConstants#LESSER}, {@link DatatypeConstants#EQUAL}, {@link DatatypeConstants#GREATER} * or {@link DatatypeConstants#INDETERMINATE}. * @@ -763,7 +760,7 @@ public abstract class Duration { * cannot reasonably process the request, e.g. W3C XML Schema allows for * arbitrarily large/small/precise values, the request may be beyond the * implementations capability. - * @throws NullPointerException if duration is null. + * @throws NullPointerException if {@code duration} is {@code null}. * * @see #isShorterThan(Duration) * @see #isLongerThan(Duration) @@ -771,23 +768,23 @@ public abstract class Duration { public abstract int compare(final Duration duration); /** - *

            Checks if this duration object is strictly longer than - * another Duration object.

            + * Checks if this duration object is strictly longer than + * another {@code Duration} object. * - *

            Duration X is "longer" than Y if and only if X>Y + *

            Duration X is "longer" than Y if and only if X {@literal >} Y * as defined in the section 3.2.6.2 of the XML Schema 1.0 - * specification.

            + * specification. * - *

            For example, "P1D" (one day) > "PT12H" (12 hours) and - * "P2Y" (two years) > "P23M" (23 months).

            + *

            For example, "P1D" (one day) {@literal >} "PT12H" (12 hours) and + * "P2Y" (two years) {@literal >} "P23M" (23 months). * - * @param duration Duration to test this Duration against. + * @param duration {@code Duration} to test this {@code Duration} against. * * @throws UnsupportedOperationException If the underlying implementation * cannot reasonably process the request, e.g. W3C XML Schema allows for * arbitrarily large/small/precise values, the request may be beyond the * implementations capability. - * @throws NullPointerException If duration is null. + * @throws NullPointerException If {@code duration} is null. * * @return * true if the duration represented by this object @@ -801,19 +798,19 @@ public abstract class Duration { } /** - *

            Checks if this duration object is strictly shorter than - * another Duration object.

            + * Checks if this duration object is strictly shorter than + * another {@code Duration} object. * - * @param duration Duration to test this Duration against. + * @param duration {@code Duration} to test this {@code Duration} against. * - * @return true if duration parameter is shorter than this Duration, - * else false. + * @return {@code true} if {@code duration} parameter is shorter than this {@code Duration}, + * else {@code false}. * * @throws UnsupportedOperationException If the underlying implementation * cannot reasonably process the request, e.g. W3C XML Schema allows for * arbitrarily large/small/precise values, the request may be beyond the * implementations capability. - * @throws NullPointerException if duration is null. + * @throws NullPointerException if {@code duration} is null. * * @see #isLongerThan(Duration duration) * @see #compare(Duration duration) @@ -823,19 +820,19 @@ public abstract class Duration { } /** - *

            Checks if this duration object has the same duration - * as another Duration object.

            + * Checks if this duration object has the same duration + * as another {@code Duration} object. * - *

            For example, "P1D" (1 day) is equal to "PT24H" (24 hours).

            + *

            For example, "P1D" (1 day) is equal to "PT24H" (24 hours). * *

            Duration X is equal to Y if and only if time instant * t+X and t+Y are the same for all the test time instants * specified in the section 3.2.6.2 of the XML Schema 1.0 - * specification.

            + * specification. * - *

            Note that there are cases where two Durations are + *

            Note that there are cases where two {@code Duration}s are * "incomparable" to each other, like one month and 30 days. - * For example,

            + * For example, *
                  * !new Duration("P1M").isShorterThan(new Duration("P30D"))
                  * !new Duration("P1M").isLongerThan(new Duration("P30D"))
            @@ -843,14 +840,14 @@ public abstract class Duration {
                  * 
            * * @param duration - * The object to compare this Duration against. + * The object to compare this {@code Duration} against. * * @return - * true if this duration is the same length as - * duration. - * false if duration is null, + * {@code true} if this duration is the same length as + * {@code duration}. + * {@code false} if {@code duration} is {@code null}, * is not a - * Duration object, + * {@code Duration} object, * or its length is different from this duration. * * @throws UnsupportedOperationException If the underlying implementation @@ -877,18 +874,19 @@ public abstract class Duration { public abstract int hashCode(); /** - *

            Returns a String representation of this Duration Object.

            + * Returns a {@code String} representation of this {@code Duration Object}. * - *

            The result is formatted according to the XML Schema 1.0 spec and can be always parsed back later into the - * equivalent Duration Object by {@link DatatypeFactory#newDuration(String lexicalRepresentation)}.

            + *

            The result is formatted according to the XML Schema 1.0 spec + * and can be always parsed back later into the + * equivalent {@code Duration Object} by {@link DatatypeFactory#newDuration(String lexicalRepresentation)}. * - *

            Formally, the following holds for any Duration - * Object x:

            + *

            Formally, the following holds for any {@code Duration} + * {@code Object} x: *

                  * new Duration(x.toString()).equals(x)
                  * 
            * - * @return A non-null valid String representation of this Duration. + * @return A non-{@code null} valid {@code String} representation of this {@code Duration}. */ public String toString() { @@ -934,14 +932,14 @@ public abstract class Duration { } /** - *

            Turns {@link BigDecimal} to a string representation.

            + * Turns {@link BigDecimal} to a string representation. * *

            Due to a behavior change in the {@link BigDecimal#toString()} - * method in JDK1.5, this had to be implemented here.

            + * method in JDK1.5, this had to be implemented here. * - * @param bd BigDecimal to format as a String + * @param bd {@code BigDecimal} to format as a {@code String} * - * @return String representation of BigDecimal + * @return {@code String} representation of {@code BigDecimal} */ private String toString(BigDecimal bd) { String intString = bd.unscaledValue().toString(); @@ -972,15 +970,15 @@ public abstract class Duration { /** - *

            Calls the {@link Calendar#getTimeInMillis} method. + * Calls the {@link Calendar#getTimeInMillis} method. * Prior to JDK1.4, this method was protected and therefore - * cannot be invoked directly.

            + * cannot be invoked directly. * - *

            TODO: In future, this should be replaced by cal.getTimeInMillis().

            + *

            TODO: In future, this should be replaced by {@code cal.getTimeInMillis()}. * - * @param cal Calendar to get time in milliseconds. + * @param cal {@code Calendar} to get time in milliseconds. * - * @return Milliseconds of cal. + * @return Milliseconds of {@code cal}. */ private static long getCalendarTimeInMillis(final Calendar cal) { return cal.getTime().getTime(); diff --git a/jaxp/src/java.xml/share/classes/javax/xml/datatype/XMLGregorianCalendar.java b/jaxp/src/java.xml/share/classes/javax/xml/datatype/XMLGregorianCalendar.java index ce16b9c9e1b..35355075b13 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/datatype/XMLGregorianCalendar.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/datatype/XMLGregorianCalendar.java @@ -43,17 +43,17 @@ import java.util.GregorianCalendar; * {@link DatatypeConstants#GMONTH}, and * {@link DatatypeConstants#GDAY} * defined in the XML Namespace - * "http://www.w3.org/2001/XMLSchema". + * {@code "http://www.w3.org/2001/XMLSchema"}. * These datatypes are normatively defined in - * W3C XML Schema 1.0 Part 2, Section 3.2.7-14.

            + * W3C XML Schema 1.0 Part 2, Section 3.2.7-14. * *

            The table below defines the mapping between XML Schema 1.0 * date/time datatype fields and this class' fields. It also summarizes * the value constraints for the date and time fields defined in * W3C XML Schema 1.0 Part 2, Appendix D, - * ISO 8601 Date and Time Formats.

            + * ISO 8601 Date and Time Formats. * - * + * *
            - * Required fields for XML Schema 1.0 Date/Time Datatypes.
            + * Required fields for XML Schema 1.0 Date/Time Datatypes.
            * (timezone is optional for all date/time datatypes) *
            * * @@ -64,22 +64,22 @@ import java.util.GregorianCalendar; * * * - * - * + * * * * - * - * + * - * * * - * + * * * * * - * + * * - * * * - * + * * * * * - * + * * * * * - * + * * * * * - * + * * *
            XML Schema 1.0
            - * datatype
            + *
            XML Schema 1.0
            + * datatype
            * field
            Related
            XMLGregorianCalendar
            Accessor(s)
            Related
            XMLGregorianCalendar
            Accessor(s)
            Value Range
            year {@link #getYear()} + {@link #getEon()} or
            + *
            year {@link #getYear()} + {@link #getEon()} or
            * {@link #getEonAndYear} *
            getYear() is a value between -(10^9-1) to (10^9)-1 - * or {@link DatatypeConstants#FIELD_UNDEFINED}.
            - * {@link #getEon()} is high order year value in billion of years.
            - * getEon() has values greater than or equal to (10^9) or less than or equal to -(10^9). - * A value of null indicates field is undefined.
            + *
            {@code getYear()} is a value between -(10^9-1) to (10^9)-1 + * or {@link DatatypeConstants#FIELD_UNDEFINED}.
            + * {@link #getEon()} is high order year value in billion of years.
            + * {@code getEon()} has values greater than or equal to (10^9) or less than or equal to -(10^9). + * A value of null indicates field is undefined.
            * Given that XML Schema 1.0 errata states that the year zero * will be a valid lexical value in a future version of XML Schema, * this class allows the year field to be set to zero. Otherwise, @@ -89,20 +89,20 @@ import java.util.GregorianCalendar; *
            monthmonth {@link #getMonth()} 1 to 12 or {@link DatatypeConstants#FIELD_UNDEFINED}
            dayday {@link #getDay()} Independent of month, max range is 1 to 31 or {@link DatatypeConstants#FIELD_UNDEFINED}.
            + *
            Independent of month, max range is 1 to 31 or {@link DatatypeConstants#FIELD_UNDEFINED}.
            * The normative value constraint stated relative to month * field's value is in W3C XML Schema 1.0 Part 2, Appendix D. *
            hourhour{@link #getHour()} * 0 to 23 or {@link DatatypeConstants#FIELD_UNDEFINED}. @@ -114,28 +114,28 @@ import java.util.GregorianCalendar; *
            minuteminute {@link #getMinute()} 0 to 59 or {@link DatatypeConstants#FIELD_UNDEFINED}
            secondsecond - * {@link #getSecond()} + {@link #getMillisecond()}/1000 or
            + * {@link #getSecond()} + {@link #getMillisecond()}/1000 or
            * {@link #getSecond()} + {@link #getFractionalSecond()} *
            - * {@link #getSecond()} from 0 to 60 or {@link DatatypeConstants#FIELD_UNDEFINED}.
            - * (Note: 60 only allowable for leap second.)
            + * {@link #getSecond()} from 0 to 60 or {@link DatatypeConstants#FIELD_UNDEFINED}.
            + * (Note: 60 only allowable for leap second.)
            * {@link #getFractionalSecond()} allows for infinite precision over the range from 0.0 to 1.0 when - * the {@link #getSecond()} is defined.
            - * FractionalSecond is optional and has a value of null when it is undefined.
            + * the {@link #getSecond()} is defined.
            + * {@code FractionalSecond} is optional and has a value of {@code null} when it is undefined.
            * {@link #getMillisecond()} is the convenience * millisecond precision of value of {@link #getFractionalSecond()}. *
            timezonetimezone {@link #getTimezone()} Number of minutes or {@link DatatypeConstants#FIELD_UNDEFINED}. * Value range from -14 hours (-14 * 60 minutes) to 14 hours (14 * 60 minutes). @@ -145,14 +145,13 @@ import java.util.GregorianCalendar; *
            * *

            All maximum value space constraints listed for the fields in the table - * above are checked by factory methods, @{link DatatypeFactory}, + * above are checked by factory methods, {@link DatatypeFactory}, * setter methods and parse methods of - * this class. IllegalArgumentException is thrown when a + * this class. {@code IllegalArgumentException} is thrown when a * parameter's value is outside the value constraint for the field or * if the composite * values constitute an invalid XMLGregorianCalendar instance (for example, if * the 31st of June is specified). - *

            * *

            The following operations are defined for this class: *

              @@ -169,7 +168,6 @@ import java.util.GregorianCalendar; * W3C XML Schema 1.0 Part 2, Appendix E, Adding durations to dateTimes. * *
            - *

            * * @author Joseph Fialli * @author Kohsuke Kawaguchi @@ -187,26 +185,26 @@ public abstract class XMLGregorianCalendar * Default no-arg constructor. * *

            Note: Always use the {@link DatatypeFactory} to - * construct an instance of XMLGregorianCalendar. + * construct an instance of {@code XMLGregorianCalendar}. * The constructor on this class cannot be guaranteed to * produce an object with a consistent state and may be - * removed in the future.

            + * removed in the future. */ public XMLGregorianCalendar() { } /** - *

            Unset all fields to undefined.

            + * Unset all fields to undefined. * *

            Set all int fields to {@link DatatypeConstants#FIELD_UNDEFINED} and reference fields - * to null.

            + * to null. */ public abstract void clear(); /** - *

            Reset this XMLGregorianCalendar to its original values.

            + * Reset this {@code XMLGregorianCalendar} to its original values. * - *

            XMLGregorianCalendar is reset to the same values as when it was created with + *

            {@code XMLGregorianCalendar} is reset to the same values as when it was created with * {@link DatatypeFactory#newXMLGregorianCalendar()}, * {@link DatatypeFactory#newXMLGregorianCalendar(String lexicalRepresentation)}, * {@link DatatypeFactory#newXMLGregorianCalendar( @@ -250,83 +248,82 @@ public abstract class XMLGregorianCalendar * int seconds, * int milliseconds, * int timezone)}. - *

            * - *

            reset() is designed to allow the reuse of existing XMLGregorianCalendars - * thus saving resources associated with the creation of new XMLGregorianCalendars.

            + *

            {@code reset()} is designed to allow the reuse of existing {@code XMLGregorianCalendar}s + * thus saving resources associated with the creation of new {@code XMLGregorianCalendar}s. */ public abstract void reset(); /** - *

            Set low and high order component of XSD dateTime year field.

            + * Set low and high order component of XSD {@code dateTime} year field. * - *

            Unset this field by invoking the setter with a parameter value of null.

            + *

            Unset this field by invoking the setter with a parameter value of {@code null}. * * @param year value constraints summarized in year field of date/time field mapping table. * - * @throws IllegalArgumentException if year parameter is + * @throws IllegalArgumentException if {@code year} parameter is * outside value constraints for the field as specified in * date/time field mapping table. */ public abstract void setYear(BigInteger year); /** - *

            Set year of XSD dateTime year field.

            + * Set year of XSD {@code dateTime} year field. * *

            Unset this field by invoking the setter with a parameter value of - * {@link DatatypeConstants#FIELD_UNDEFINED}.

            + * {@link DatatypeConstants#FIELD_UNDEFINED}. * - *

            Note: if the absolute value of the year parameter + *

            Note: if the absolute value of the {@code year} parameter * is less than 10^9, the eon component of the XSD year field is set to - * null by this method.

            + * {@code null} by this method. * * @param year value constraints are summarized in year field of date/time field mapping table. - * If year is {@link DatatypeConstants#FIELD_UNDEFINED}, then eon is set to null. + * If year is {@link DatatypeConstants#FIELD_UNDEFINED}, then eon is set to {@code null}. */ public abstract void setYear(int year); /** - *

            Set month.

            + * Set month. * - *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}.

            + *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}. * * @param month value constraints summarized in month field of date/time field mapping table. * - * @throws IllegalArgumentException if month parameter is + * @throws IllegalArgumentException if {@code month} parameter is * outside value constraints for the field as specified in * date/time field mapping table. */ public abstract void setMonth(int month); /** - *

            Set days in month.

            + * Set days in month. * - *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}.

            + *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}. * * @param day value constraints summarized in day field of date/time field mapping table. * - * @throws IllegalArgumentException if day parameter is + * @throws IllegalArgumentException if {@code day} parameter is * outside value constraints for the field as specified in * date/time field mapping table. */ public abstract void setDay(int day); /** - *

            Set the number of minutes in the timezone offset.

            + * Set the number of minutes in the timezone offset. * - *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}.

            + *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}. * * @param offset value constraints summarized in * timezone field of date/time field mapping table. * - * @throws IllegalArgumentException if offset parameter is + * @throws IllegalArgumentException if {@code offset} parameter is * outside value constraints for the field as specified in * date/time field mapping table. */ public abstract void setTimezone(int offset); /** - *

            Set time as one unit.

            + * Set time as one unit. * * @param hour value constraints are summarized in * hour field of date/time field mapping table. @@ -352,71 +349,71 @@ public abstract class XMLGregorianCalendar } /** - *

            Set hours.

            + * Set hours. * - *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}.

            + *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}. * * @param hour value constraints summarized in hour field of date/time field mapping table. * - * @throws IllegalArgumentException if hour parameter is outside value constraints for the field as specified in + * @throws IllegalArgumentException if {@code hour} parameter is outside value constraints for the field as specified in * date/time field mapping table. */ public abstract void setHour(int hour); /** - *

            Set minutes.

            + * Set minutes. * - *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}.

            + *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}. * * @param minute value constraints summarized in minute field of date/time field mapping table. * - * @throws IllegalArgumentException if minute parameter is outside value constraints for the field as specified in + * @throws IllegalArgumentException if {@code minute} parameter is outside value constraints for the field as specified in * date/time field mapping table. */ public abstract void setMinute(int minute); /** - *

            Set seconds.

            + * Set seconds. * - *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}.

            + *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}. * * @param second value constraints summarized in second field of date/time field mapping table. * - * @throws IllegalArgumentException if second parameter is outside value constraints for the field as specified in + * @throws IllegalArgumentException if {@code second} parameter is outside value constraints for the field as specified in * date/time field mapping table. */ public abstract void setSecond(int second); /** - *

            Set milliseconds.

            + * Set milliseconds. * - *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}.

            + *

            Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}. * * @param millisecond value constraints summarized in * second field of date/time field mapping table. * - * @throws IllegalArgumentException if millisecond parameter is outside value constraints for the field as specified + * @throws IllegalArgumentException if {@code millisecond} parameter is outside value constraints for the field as specified * in date/time field mapping table. */ public abstract void setMillisecond(int millisecond); /** - *

            Set fractional seconds.

            + * Set fractional seconds. * - *

            Unset this field by invoking the setter with a parameter value of null.

            + *

            Unset this field by invoking the setter with a parameter value of {@code null}. * * @param fractional value constraints summarized in * second field of date/time field mapping table. * - * @throws IllegalArgumentException if fractional parameter is outside value constraints for the field as specified + * @throws IllegalArgumentException if {@code fractional} parameter is outside value constraints for the field as specified * in date/time field mapping table. */ public abstract void setFractionalSecond(BigDecimal fractional); /** - *

            Set time as one unit, including the optional infinite precision - * fractional seconds.

            + * Set time as one unit, including the optional infinite precision + * fractional seconds. * * @param hour value constraints are summarized in * hour field of date/time field mapping table. @@ -424,7 +421,7 @@ public abstract class XMLGregorianCalendar * minute field of date/time field mapping table. * @param second value constraints are summarized in * second field of date/time field mapping table. - * @param fractional value of null indicates this optional + * @param fractional value of {@code null} indicates this optional * field is not set. * * @throws IllegalArgumentException if any parameter is @@ -445,7 +442,7 @@ public abstract class XMLGregorianCalendar /** - *

            Set time as one unit, including optional milliseconds.

            + * Set time as one unit, including optional milliseconds. * * @param hour value constraints are summarized in * hour field of date/time field mapping table. @@ -469,13 +466,13 @@ public abstract class XMLGregorianCalendar } /** - *

            Return high order component for XML Schema 1.0 dateTime datatype field for - * year. - * null if this optional part of the year field is not defined.

            + * Return high order component for XML Schema 1.0 dateTime datatype field for + * {@code year}. + * {@code null} if this optional part of the year field is not defined. * *

            Value constraints for this value are summarized in - * year field of date/time field mapping table.

            - * @return eon of this XMLGregorianCalendar. The value + * year field of date/time field mapping table. + * @return eon of this {@code XMLGregorianCalendar}. The value * returned is an integer multiple of 10^9. * * @see #getYear() @@ -484,13 +481,13 @@ public abstract class XMLGregorianCalendar public abstract BigInteger getEon(); /** - *

            Return low order component for XML Schema 1.0 dateTime datatype field for - * year or {@link DatatypeConstants#FIELD_UNDEFINED}.

            + * Return low order component for XML Schema 1.0 dateTime datatype field for + * {@code year} or {@link DatatypeConstants#FIELD_UNDEFINED}. * *

            Value constraints for this value are summarized in - * year field of date/time field mapping table.

            + * year field of date/time field mapping table. * - * @return year of this XMLGregorianCalendar. + * @return year of this {@code XMLGregorianCalendar}. * * @see #getEon() * @see #getEonAndYear() @@ -498,16 +495,16 @@ public abstract class XMLGregorianCalendar public abstract int getYear(); /** - *

            Return XML Schema 1.0 dateTime datatype field for - * year.

            + * Return XML Schema 1.0 dateTime datatype field for + * {@code year}. * *

            Value constraints for this value are summarized in - * year field of date/time field mapping table.

            + * year field of date/time field mapping table. * - * @return sum of eon and BigInteger.valueOf(year) - * when both fields are defined. When only year is defined, - * return it. When both eon and year are not - * defined, return null. + * @return sum of {@code eon} and {@code BigInteger.valueOf(year)} + * when both fields are defined. When only {@code year} is defined, + * return it. When both {@code eon} and {@code year} are not + * defined, return {@code null}. * * @see #getEon() * @see #getYear() @@ -515,21 +512,21 @@ public abstract class XMLGregorianCalendar public abstract BigInteger getEonAndYear(); /** - *

            Return number of month or {@link DatatypeConstants#FIELD_UNDEFINED}.

            + * Return number of month or {@link DatatypeConstants#FIELD_UNDEFINED}. * *

            Value constraints for this value are summarized in - * month field of date/time field mapping table.

            + * month field of date/time field mapping table. * - * @return year of this XMLGregorianCalendar. + * @return year of this {@code XMLGregorianCalendar}. * */ public abstract int getMonth(); /** - * Return day in month or {@link DatatypeConstants#FIELD_UNDEFINED}.

            + * Return day in month or {@link DatatypeConstants#FIELD_UNDEFINED}. * *

            Value constraints for this value are summarized in - * day field of date/time field mapping table.

            + * day field of date/time field mapping table. * * @see #setDay(int) */ @@ -540,7 +537,7 @@ public abstract class XMLGregorianCalendar * {@link DatatypeConstants#FIELD_UNDEFINED} if this optional field is not defined. * *

            Value constraints for this value are summarized in - * timezone field of date/time field mapping table.

            + * timezone field of date/time field mapping table. * * @see #setTimezone(int) */ @@ -551,34 +548,34 @@ public abstract class XMLGregorianCalendar * Returns {@link DatatypeConstants#FIELD_UNDEFINED} if this field is not defined. * *

            Value constraints for this value are summarized in - * hour field of date/time field mapping table.

            + * hour field of date/time field mapping table. * @see #setTime(int, int, int) */ public abstract int getHour(); /** - * Return minutes or {@link DatatypeConstants#FIELD_UNDEFINED}.

            + * Return minutes or {@link DatatypeConstants#FIELD_UNDEFINED}. * Returns {@link DatatypeConstants#FIELD_UNDEFINED} if this field is not defined. * *

            Value constraints for this value are summarized in - * minute field of date/time field mapping table.

            + * minute field of date/time field mapping table. * @see #setTime(int, int, int) */ public abstract int getMinute(); /** - *

            Return seconds or {@link DatatypeConstants#FIELD_UNDEFINED}.

            + * Return seconds or {@link DatatypeConstants#FIELD_UNDEFINED}. * *

            Returns {@link DatatypeConstants#FIELD_UNDEFINED} if this field is not defined. * When this field is not defined, the optional xs:dateTime * fractional seconds field, represented by * {@link #getFractionalSecond()} and {@link #getMillisecond()}, - * must not be defined.

            + * must not be defined. * *

            Value constraints for this value are summarized in - * second field of date/time field mapping table.

            + * second field of date/time field mapping table. * - * @return Second of this XMLGregorianCalendar. + * @return Second of this {@code XMLGregorianCalendar}. * * @see #getFractionalSecond() * @see #getMillisecond() @@ -587,20 +584,20 @@ public abstract class XMLGregorianCalendar public abstract int getSecond(); /** - *

            Return millisecond precision of {@link #getFractionalSecond()}.

            + * Return millisecond precision of {@link #getFractionalSecond()}. * *

            This method represents a convenience accessor to infinite * precision fractional second value returned by * {@link #getFractionalSecond()}. The returned value is the rounded * down to milliseconds value of * {@link #getFractionalSecond()}. When {@link #getFractionalSecond()} - * returns null, this method must return - * {@link DatatypeConstants#FIELD_UNDEFINED}.

            + * returns {@code null}, this method must return + * {@link DatatypeConstants#FIELD_UNDEFINED}. * *

            Value constraints for this value are summarized in - * second field of date/time field mapping table.

            + * second field of date/time field mapping table. * - * @return Millisecond of this XMLGregorianCalendar. + * @return Millisecond of this {@code XMLGregorianCalendar}. * * @see #getFractionalSecond() * @see #setTime(int, int, int) @@ -618,18 +615,18 @@ public abstract class XMLGregorianCalendar } /** - *

            Return fractional seconds.

            + * Return fractional seconds. * - *

            null is returned when this optional field is not defined.

            + *

            {@code null} is returned when this optional field is not defined. * *

            Value constraints are detailed in - * second field of date/time field mapping table.

            + * second field of date/time field mapping table. * *

            This optional field can only have a defined value when the * xs:dateTime second field, represented by {@link #getSecond()}, - * does not return {@link DatatypeConstants#FIELD_UNDEFINED}.

            + * does not return {@link DatatypeConstants#FIELD_UNDEFINED}. * - * @return fractional seconds of this XMLGregorianCalendar. + * @return fractional seconds of this {@code XMLGregorianCalendar}. * * @see #getSecond() * @see #setTime(int, int, int, BigDecimal) @@ -638,51 +635,51 @@ public abstract class XMLGregorianCalendar // comparisons /** - *

            Compare two instances of W3C XML Schema 1.0 date/time datatypes + * Compare two instances of W3C XML Schema 1.0 date/time datatypes * according to partial order relation defined in * W3C XML Schema 1.0 Part 2, Section 3.2.7.3, - * Order relation on dateTime.

            + * Order relation on dateTime. * - *

            xsd:dateTime datatype field mapping to accessors of + *

            {@code xsd:dateTime} datatype field mapping to accessors of * this class are defined in - * date/time field mapping table.

            + * date/time field mapping table. * - * @param xmlGregorianCalendar Instance of XMLGregorianCalendar to compare + * @param xmlGregorianCalendar Instance of {@code XMLGregorianCalendar} to compare * - * @return The relationship between this XMLGregorianCalendar and - * the specified xmlGregorianCalendar as + * @return The relationship between {@code this} {@code XMLGregorianCalendar} and + * the specified {@code xmlGregorianCalendar} as * {@link DatatypeConstants#LESSER}, * {@link DatatypeConstants#EQUAL}, * {@link DatatypeConstants#GREATER} or * {@link DatatypeConstants#INDETERMINATE}. * - * @throws NullPointerException if xmlGregorianCalendar is null. + * @throws NullPointerException if {@code xmlGregorianCalendar} is null. */ public abstract int compare(XMLGregorianCalendar xmlGregorianCalendar); /** - *

            Normalize this instance to UTC.

            + * Normalize this instance to UTC. * - *

            2000-03-04T23:00:00+03:00 normalizes to 2000-03-04T20:00:00Z

            - *

            Implements W3C XML Schema Part 2, Section 3.2.7.3 (A).

            + *

            2000-03-04T23:00:00+03:00 normalizes to 2000-03-04T20:00:00Z + *

            Implements W3C XML Schema Part 2, Section 3.2.7.3 (A). * - * @return this XMLGregorianCalendar normalized to UTC. + * @return {@code this} {@code XMLGregorianCalendar} normalized to UTC. */ public abstract XMLGregorianCalendar normalize(); /** - *

            Compares this calendar to the specified object. The result is - * true if and only if the argument is not null and is an - * XMLGregorianCalendar object that represents the same - * instant in time as this object.

            + * Compares this calendar to the specified object. The result is + * {@code true} if and only if the argument is not null and is an + * {@code XMLGregorianCalendar} object that represents the same + * instant in time as this object. * * @param obj to compare. * - * @return true when obj is an instance of - * XMLGregorianCalendar and + * @return {@code true} when {@code obj} is an instance of + * {@code XMLGregorianCalendar} and * {@link #compare(XMLGregorianCalendar obj)} * returns {@link DatatypeConstants#EQUAL}, - * otherwise false. + * otherwise {@code false}. */ public boolean equals(Object obj) { @@ -693,7 +690,7 @@ public abstract class XMLGregorianCalendar } /** - *

            Returns a hash code consistent with the definition of the equals method.

            + * Returns a hash code consistent with the definition of the equals method. * * @return hash code of this object. */ @@ -721,15 +718,15 @@ public abstract class XMLGregorianCalendar } /** - *

            Return the lexical representation of this instance. + * Return the lexical representation of {@code this} instance. * The format is specified in * XML Schema 1.0 Part 2, Section 3.2.[7-14].1, - * Lexical Representation".

            + * Lexical Representation". * *

            Specific target lexical representation format is determined by - * {@link #getXMLSchemaType()}.

            + * {@link #getXMLSchemaType()}. * - * @return XML, as String, representation of this XMLGregorianCalendar + * @return XML, as {@code String}, representation of this {@code XMLGregorianCalendar} * * @throws IllegalStateException if the combination of set fields * does not match one of the eight defined XML Schema builtin date/time datatypes. @@ -737,14 +734,14 @@ public abstract class XMLGregorianCalendar public abstract String toXMLFormat(); /** - *

            Return the name of the XML Schema date/time type that this instance - * maps to. Type is computed based on fields that are set.

            + * Return the name of the XML Schema date/time type that this instance + * maps to. Type is computed based on fields that are set. * * * * * * @@ -850,11 +847,11 @@ public abstract class XMLGregorianCalendar public abstract QName getXMLSchemaType(); /** - *

            Returns a String representation of this XMLGregorianCalendar Object.

            + * Returns a {@code String} representation of this {@code XMLGregorianCalendar} {@code Object}. * - *

            The result is a lexical representation generated by {@link #toXMLFormat()}.

            + *

            The result is a lexical representation generated by {@link #toXMLFormat()}. * - * @return A non-null valid String representation of this XMLGregorianCalendar. + * @return A non-{@code null} valid {@code String} representation of this {@code XMLGregorianCalendar}. * * @throws IllegalStateException if the combination of set fields * does not match one of the eight defined XML Schema builtin date/time datatypes. @@ -867,89 +864,89 @@ public abstract class XMLGregorianCalendar } /** - * Validate instance by getXMLSchemaType() constraints. + * Validate instance by {@code getXMLSchemaType()} constraints. * @return true if data values are valid. */ public abstract boolean isValid(); /** - *

            Add duration to this instance.

            + * Add {@code duration} to this instance. * *

            The computation is specified in * XML Schema 1.0 Part 2, Appendix E, - * Adding durations to dateTimes>. + * Adding durations to dateTimes. * date/time field mapping table - * defines the mapping from XML Schema 1.0 dateTime fields - * to this class' representation of those fields.

            + * defines the mapping from XML Schema 1.0 {@code dateTime} fields + * to this class' representation of those fields. * - * @param duration Duration to add to this XMLGregorianCalendar. + * @param duration Duration to add to this {@code XMLGregorianCalendar}. * - * @throws NullPointerException when duration parameter is null. + * @throws NullPointerException when {@code duration} parameter is {@code null}. */ public abstract void add(Duration duration); /** - *

            Convert this XMLGregorianCalendar to a {@link GregorianCalendar}.

            + * Convert this {@code XMLGregorianCalendar} to a {@link GregorianCalendar}. * - *

            When this instance has an undefined field, this - * conversion relies on the java.util.GregorianCalendar default + *

            When {@code this} instance has an undefined field, this + * conversion relies on the {@code java.util.GregorianCalendar} default * for its corresponding field. A notable difference between - * XML Schema 1.0 date/time datatypes and java.util.GregorianCalendar + * XML Schema 1.0 date/time datatypes and {@code java.util.GregorianCalendar} * is that Timezone value is optional for date/time datatypes and it is - * a required field for java.util.GregorianCalendar. See javadoc - * for java.util.TimeZone.getDefault() on how the default - * is determined. To explicitly specify the TimeZone + * a required field for {@code java.util.GregorianCalendar}. See javadoc + * for {@code java.util.TimeZone.getDefault()} on how the default + * is determined. To explicitly specify the {@code TimeZone} * instance, see - * {@link #toGregorianCalendar(TimeZone, Locale, XMLGregorianCalendar)}.

            + * {@link #toGregorianCalendar(TimeZone, Locale, XMLGregorianCalendar)}. * *
            - * Required fields for XML Schema 1.0 Date/Time Datatypes.
            + * Required fields for XML Schema 1.0 Date/Time Datatypes.
            * (timezone is optional for all date/time datatypes) *
            * * * * * * * - * - * + * + * * * - * - * + * + * * * - * - * + * + * * * - * + * * * * - * + * * * * - * + * * * * - * + * * * * - * + * * * * - * + * * * * - * + * * * * @@ -958,74 +955,74 @@ public abstract class XMLGregorianCalendar * to source datatype having higher precision than target datatype. * *

            To ensure consistency in conversion implementations, the new - * GregorianCalendar should be instantiated in following + * {@code GregorianCalendar} should be instantiated in following * manner. *

              - *
            • Using timeZone value as defined above, create a new - * java.util.GregorianCalendar(timeZone,Locale.getDefault()). + *
            • Using {@code timeZone} value as defined above, create a new + * {@code java.util.GregorianCalendar(timeZone,Locale.getDefault())}. *
            • *
            • Initialize all GregorianCalendar fields by calling {@link java.util.GregorianCalendar#clear()}.
            • *
            • Obtain a pure Gregorian Calendar by invoking - * GregorianCalendar.setGregorianChange( - * new Date(Long.MIN_VALUE)).
            • + * {@code GregorianCalendar.setGregorianChange( + * new Date(Long.MIN_VALUE))}. *
            • Its fields ERA, YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY, * MINUTE, SECOND and MILLISECOND are set using the method - * Calendar.set(int,int)
            • + * {@code Calendar.set(int,int)} *
            - *

            * * @see #toGregorianCalendar(java.util.TimeZone, java.util.Locale, XMLGregorianCalendar) */ public abstract GregorianCalendar toGregorianCalendar(); /** - *

            Convert this XMLGregorianCalendar along with provided parameters - * to a {@link GregorianCalendar} instance.

            + * Convert this {@code XMLGregorianCalendar} along with provided parameters + * to a {@link GregorianCalendar} instance. * *

            Since XML Schema 1.0 date/time datetypes has no concept of * timezone ids or daylight savings timezone ids, this conversion operation * allows the user to explicitly specify one with - * timezone parameter.

            + * {@code timezone} parameter. * - *

            To compute the return value's TimeZone field, + *

            To compute the return value's {@code TimeZone} field, *

              - *
            • when parameter timeZone is non-null, + *
            • when parameter {@code timeZone} is non-null, * it is the timezone field.
            • - *
            • else when this.getTimezone() != FIELD_UNDEFINED, - * create a java.util.TimeZone with a custom timezone id - * using the this.getTimezone().
            • - *
            • else when defaults.getTimezone() != FIELD_UNDEFINED, - * create a java.util.TimeZone with a custom timezone id - * using defaults.getTimezone().
            • - *
            • else use the GregorianCalendar default timezone value + *
            • else when {@code this.getTimezone() != FIELD_UNDEFINED}, + * create a {@code java.util.TimeZone} with a custom timezone id + * using the {@code this.getTimezone()}.
            • + *
            • else when {@code defaults.getTimezone() != FIELD_UNDEFINED}, + * create a {@code java.util.TimeZone} with a custom timezone id + * using {@code defaults.getTimezone()}.
            • + *
            • else use the {@code GregorianCalendar} default timezone value * for the host is defined as specified by - * java.util.TimeZone.getDefault().
            • + * {@code java.util.TimeZone.getDefault()}. + *
            * *

            To ensure consistency in conversion implementations, the new - * GregorianCalendar should be instantiated in following + * {@code GregorianCalendar} should be instantiated in following * manner. *

              - *
            • Create a new java.util.GregorianCalendar(TimeZone, - * Locale) with TimeZone set as specified above and the - * Locale parameter. + *
            • Create a new {@code java.util.GregorianCalendar(TimeZone, + * Locale)} with TimeZone set as specified above and the + * {@code Locale} parameter. *
            • *
            • Initialize all GregorianCalendar fields by calling {@link GregorianCalendar#clear()}
            • *
            • Obtain a pure Gregorian Calendar by invoking - * GregorianCalendar.setGregorianChange( - * new Date(Long.MIN_VALUE)).
            • + * {@code GregorianCalendar.setGregorianChange( + * new Date(Long.MIN_VALUE))}. *
            • Its fields ERA, YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY, * MINUTE, SECOND and MILLISECOND are set using the method - * Calendar.set(int,int)
            • + * {@code Calendar.set(int,int)} *
            * - * @param timezone provide Timezone. null is a legal value. + * @param timezone provide Timezone. {@code null} is a legal value. * @param aLocale provide explicit Locale. Use default GregorianCalendar locale if - * value is null. + * value is {@code null}. * @param defaults provide default field values to use when corresponding * field for this instance is FIELD_UNDEFINED or null. - * If defaultsis null or a field - * within the specified defaults is undefined, - * just use java.util.GregorianCalendar defaults. + * If {@code defaults}is {@code null} or a field + * within the specified {@code defaults} is undefined, + * just use {@code java.util.GregorianCalendar} defaults. * @return a java.util.GregorianCalendar conversion of this instance. */ public abstract GregorianCalendar toGregorianCalendar( @@ -1034,7 +1031,7 @@ public abstract class XMLGregorianCalendar XMLGregorianCalendar defaults); /** - *

            Returns a java.util.TimeZone for this class.

            + * Returns a {@code java.util.TimeZone} for this class. * *

            If timezone field is defined for this instance, * returns TimeZone initialized with custom timezone id @@ -1042,7 +1039,7 @@ public abstract class XMLGregorianCalendar * try the defaultZoneoffset that was passed in. * If defaultZoneoffset is FIELD_UNDEFINED, return * default timezone for this host. - * (Same default as java.util.GregorianCalendar).

            + * (Same default as java.util.GregorianCalendar). * * @param defaultZoneoffset default zoneoffset if this zoneoffset is * {@link DatatypeConstants#FIELD_UNDEFINED}. @@ -1054,9 +1051,9 @@ public abstract class XMLGregorianCalendar /** - *

            Creates and returns a copy of this object.

            + * Creates and returns a copy of this object. * - * @return copy of this Object + * @return copy of this {@code Object} */ public abstract Object clone(); } diff --git a/jaxp/src/java.xml/share/classes/javax/xml/namespace/NamespaceContext.java b/jaxp/src/java.xml/share/classes/javax/xml/namespace/NamespaceContext.java index f1ce6932144..09e46e7dfbf 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/namespace/NamespaceContext.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/namespace/NamespaceContext.java @@ -28,44 +28,44 @@ package javax.xml.namespace; import java.util.Iterator; /** - *

            Interface for read only XML Namespace context processing.

            + * Interface for read only XML Namespace context processing. * - *

            An XML Namespace has the properties:

            + *

            An XML Namespace has the properties: *

              *
            • Namespace URI: * Namespace name expressed as a URI to which the prefix is bound
            • *
            • prefix: syntactically, this is the part of the attribute name - * following the XMLConstants.XMLNS_ATTRIBUTE + * following the {@code XMLConstants.XMLNS_ATTRIBUTE} * ("xmlns") in the Namespace declaration
            • *
            *

            example: - * <element xmlns:prefix="http://Namespace-name-URI">

            + * {@code } * - *

            All get*(*) methods operate in the current scope - * for Namespace URI and prefix resolution.

            + *

            All {@code get*(*)} methods operate in the current scope + * for Namespace URI and prefix resolution. * *

            Note that a Namespace URI can be bound to * multiple prefixes in the current scope. This can - * occur when multiple XMLConstants.XMLNS_ATTRIBUTE + * occur when multiple {@code XMLConstants.XMLNS_ATTRIBUTE} * ("xmlns") Namespace declarations occur in the same Start-Tag and - * refer to the same Namespace URI. e.g.
            - *

            - * <element xmlns:prefix1="http://Namespace-name-URI"
            - *          xmlns:prefix2="http://Namespace-name-URI">
            + * refer to the same Namespace URI. e.g.
            + *
             {@code
            + *  }
              * 
            * This can also occur when the same Namespace URI is used in multiple - * XMLConstants.XMLNS_ATTRIBUTE ("xmlns") Namespace - * declarations in the logical parent element hierarchy. e.g.
            - *
            - * <parent xmlns:prefix1="http://Namespace-name-URI">
            - *   <child xmlns:prefix2="http://Namespace-name-URI">
            + * {@code XMLConstants.XMLNS_ATTRIBUTE} ("xmlns") Namespace
            + * declarations in the logical parent element hierarchy.  e.g.
            + *
             {@code
            + * 
            + *   
              *     ...
            - *   </child>
            - * </parent>
            - * 

            + * + * } + *
            * *

            A prefix can only be bound to a single - * Namespace URI in the current scope.

            + * Namespace URI in the current scope. * * @author Jeff Suttor * @see javax.xml.XMLConstants @@ -82,17 +82,17 @@ import java.util.Iterator; public interface NamespaceContext { /** - *

            Get Namespace URI bound to a prefix in the current scope.

            + * Get Namespace URI bound to a prefix in the current scope. * *

            When requesting a Namespace URI by prefix, the following * table describes the returned Namespace URI value for all - * possible prefix values:

            + * possible prefix values: * *
            * Field by Field Conversion from this class to - * java.util.GregorianCalendar + * {@code java.util.GregorianCalendar} *
            java.util.GregorianCalendar fieldjavax.xml.datatype.XMLGregorianCalendar field{@code java.util.GregorianCalendar} field{@code javax.xml.datatype.XMLGregorianCalendar} field
            ERA{@link #getEonAndYear()}.signum() < 0 ? GregorianCalendar.BC : GregorianCalendar.AD{@code ERA}{@link #getEonAndYear()}{@code .signum() < 0 ? GregorianCalendar.BC : GregorianCalendar.AD}
            YEAR{@link #getEonAndYear()}.abs().intValue()*{@code YEAR}{@link #getEonAndYear()}{@code .abs().intValue()}*
            MONTH{@code MONTH}{@link #getMonth()} - {@link DatatypeConstants#JANUARY} + {@link GregorianCalendar#JANUARY}
            DAY_OF_MONTH{@code DAY_OF_MONTH}{@link #getDay()}
            HOUR_OF_DAY{@code HOUR_OF_DAY}{@link #getHour()}
            MINUTE{@code MINUTE}{@link #getMinute()}
            SECOND{@code SECOND}{@link #getSecond()}
            MILLISECOND{@code MILLISECOND}get millisecond order from {@link #getFractionalSecond()}*
            GregorianCalendar.setTimeZone(TimeZone){@code GregorianCalendar.setTimeZone(TimeZone)}{@link #getTimezone()} formatted into Custom timezone id
            * * * * @@ -103,9 +103,9 @@ public interface NamespaceContext { * * * - * + * * @@ -117,24 +117,24 @@ public interface NamespaceContext { * * * * * - * - * + * * * - * - * + * * * - * - * + * + * * * *
            - * getNamespaceURI(prefix) + * {@code getNamespaceURI(prefix)} * return value for specified prefixes *
            DEFAULT_NS_PREFIX (""){@code DEFAULT_NS_PREFIX} ("")default Namespace URI in the current scope or - * {@link + * {@link * javax.xml.XMLConstants#NULL_NS_URI XMLConstants.NULL_NS_URI("")} * * when there is no default Namespace URI in the current scope
            unbound prefix - * {@link + * {@link * javax.xml.XMLConstants#NULL_NS_URI XMLConstants.NULL_NS_URI("")} * *
            XMLConstants.XML_NS_PREFIX ("xml")XMLConstants.XML_NS_URI + * {@code XMLConstants.XML_NS_PREFIX} ("xml"){@code XMLConstants.XML_NS_URI} * ("http://www.w3.org/XML/1998/namespace")
            XMLConstants.XMLNS_ATTRIBUTE ("xmlns")XMLConstants.XMLNS_ATTRIBUTE_NS_URI + * {@code XMLConstants.XMLNS_ATTRIBUTE} ("xmlns"){@code XMLConstants.XMLNS_ATTRIBUTE_NS_URI} * ("http://www.w3.org/2000/xmlns/")
            nullIllegalArgumentException is thrown{@code null}{@code IllegalArgumentException} is thrown
            @@ -143,26 +143,26 @@ public interface NamespaceContext { * * @return Namespace URI bound to prefix in the current scope * - * @throws IllegalArgumentException When prefix is - * null + * @throws IllegalArgumentException When {@code prefix} is + * {@code null} */ String getNamespaceURI(String prefix); /** - *

            Get prefix bound to Namespace URI in the current scope.

            + * Get prefix bound to Namespace URI in the current scope. * *

            To get all prefixes bound to a Namespace URI in the current - * scope, use {@link #getPrefixes(String namespaceURI)}.

            + * scope, use {@link #getPrefixes(String namespaceURI)}. * *

            When requesting a prefix by Namespace URI, the following * table describes the returned prefix value for all Namespace URI - * values:

            + * values: * * * * * * @@ -173,8 +173,8 @@ public interface NamespaceContext { * * * - * - * + * * * @@ -186,21 +186,21 @@ public interface NamespaceContext { * * * - * + * * * - * - * + * * * - * - * + * * * - * - * + * + * * * *
            - * getPrefix(namespaceURI) return value for + * {@code getPrefix(namespaceURI)} return value for * specified Namespace URIs *
            <default Namespace URI>XMLConstants.DEFAULT_NS_PREFIX ("") + * {@code }{@code XMLConstants.DEFAULT_NS_PREFIX} ("") *
            unbound Namespace URInull{@code null}
            XMLConstants.XML_NS_URI + * {@code XMLConstants.XML_NS_URI} * ("http://www.w3.org/XML/1998/namespace")XMLConstants.XML_NS_PREFIX ("xml"){@code XMLConstants.XML_NS_PREFIX} ("xml")
            XMLConstants.XMLNS_ATTRIBUTE_NS_URI + * {@code XMLConstants.XMLNS_ATTRIBUTE_NS_URI} * ("http://www.w3.org/2000/xmlns/")XMLConstants.XMLNS_ATTRIBUTE ("xmlns"){@code XMLConstants.XMLNS_ATTRIBUTE} ("xmlns")
            nullIllegalArgumentException is thrown{@code null}{@code IllegalArgumentException} is thrown
            @@ -209,32 +209,32 @@ public interface NamespaceContext { * * @return prefix bound to Namespace URI in current context * - * @throws IllegalArgumentException When namespaceURI is - * null + * @throws IllegalArgumentException When {@code namespaceURI} is + * {@code null} */ String getPrefix(String namespaceURI); /** - *

            Get all prefixes bound to a Namespace URI in the current - * scope.

            + * Get all prefixes bound to a Namespace URI in the current + * scope. * *

            An Iterator over String elements is returned in an arbitrary, - * implementation dependent, order.

            + * implementation dependent, order. * - *

            The Iterator is + *

            The {@code Iterator} is * not modifiable. e.g. the - * remove() method will throw - * UnsupportedOperationException.

            + * {@code remove()} method will throw + * {@code UnsupportedOperationException}. * *

            When requesting prefixes by Namespace URI, the following * table describes the returned prefixes value for all Namespace - * URI values:

            + * URI values: * * * * - * * * @@ -245,9 +245,9 @@ public interface NamespaceContext { * * * + * including the {@code } * * * - * + * * * - * - * + * * * - * - * + * * * - * - * + * + * * * *
            - * getPrefixes(namespaceURI) return value for + * {@code + * getPrefixes(namespaceURI)} return value for * specified Namespace URIs
            bound Namespace URI, - * including the <default Namespace URI> - * Iterator over prefixes bound to Namespace URI in + * {@code Iterator} over prefixes bound to Namespace URI in * the current scope in an arbitrary, * implementation dependent, * order @@ -255,34 +255,34 @@ public interface NamespaceContext { *
            unbound Namespace URIempty Iteratorempty {@code Iterator}
            XMLConstants.XML_NS_URI + * {@code XMLConstants.XML_NS_URI} * ("http://www.w3.org/XML/1998/namespace")Iterator with one element set to - * XMLConstants.XML_NS_PREFIX ("xml"){@code Iterator} with one element set to + * {@code XMLConstants.XML_NS_PREFIX} ("xml")
            XMLConstants.XMLNS_ATTRIBUTE_NS_URI + * {@code XMLConstants.XMLNS_ATTRIBUTE_NS_URI} * ("http://www.w3.org/2000/xmlns/")Iterator with one element set to - * XMLConstants.XMLNS_ATTRIBUTE ("xmlns"){@code Iterator} with one element set to + * {@code XMLConstants.XMLNS_ATTRIBUTE} ("xmlns")
            nullIllegalArgumentException is thrown{@code null}{@code IllegalArgumentException} is thrown
            * * @param namespaceURI URI of Namespace to lookup * - * @return Iterator for all prefixes bound to the + * @return {@code Iterator} for all prefixes bound to the * Namespace URI in the current scope * - * @throws IllegalArgumentException When namespaceURI is - * null + * @throws IllegalArgumentException When {@code namespaceURI} is + * {@code null} */ Iterator getPrefixes(String namespaceURI); } diff --git a/jaxp/src/java.xml/share/classes/javax/xml/parsers/DocumentBuilderFactory.java b/jaxp/src/java.xml/share/classes/javax/xml/parsers/DocumentBuilderFactory.java index c500869cd7f..71fed6c2c15 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/parsers/DocumentBuilderFactory.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/parsers/DocumentBuilderFactory.java @@ -47,8 +47,8 @@ public abstract class DocumentBuilderFactory { private boolean coalescing = false; /** - *

            Protected constructor to prevent instantiation. - * Use {@link #newInstance()}.

            + * Protected constructor to prevent instantiation. + * Use {@link #newInstance()}. */ protected DocumentBuilderFactory () { } @@ -60,7 +60,6 @@ public abstract class DocumentBuilderFactory { * This method uses the following ordered lookup procedure to determine * the {@code DocumentBuilderFactory} implementation class to * load: - *

            *

              *
            • * Use the {@code javax.xml.parsers.DocumentBuilderFactory} system @@ -131,7 +130,7 @@ public abstract class DocumentBuilderFactory { } /** - *

              Obtain a new instance of a {@code DocumentBuilderFactory} from class name. + * Obtain a new instance of a {@code DocumentBuilderFactory} from class name. * This function is useful when there are multiple providers in the classpath. * It gives more control to the application as it can specify which provider * should be loaded. @@ -143,21 +142,22 @@ public abstract class DocumentBuilderFactory { *

              Tip for Trouble-shooting

              *

              Setting the {@code jaxp.debug} system property will cause * this method to print a lot of debug messages - * to {@code System.err} about what it is doing and where it is looking at.

              + * to {@code System.err} about what it is doing and where it is looking at. * - *

              If you have problems try:

              + *

              If you have problems try: *

                    * java -Djaxp.debug=1 YourProgram ....
                    * 
              * - * @param factoryClassName fully qualified factory class name that provides implementation of {@code javax.xml.parsers.DocumentBuilderFactory}. + * @param factoryClassName fully qualified factory class name that provides + * implementation of {@code javax.xml.parsers.DocumentBuilderFactory}. * - * @param classLoader ClassLoader used to load the factory class. If null - * current Thread's context classLoader is used to load the factory class. + * @param classLoader {@code ClassLoader} used to load the factory class. If {@code null} + * current {@code Thread}'s context classLoader is used to load the factory class. * * @return New instance of a {@code DocumentBuilderFactory} * - * @throws FactoryConfigurationError if factoryClassName is null, or + * @throws FactoryConfigurationError if {@code factoryClassName} is {@code null}, or * the factory class cannot be loaded, instantiated. * * @see #newInstance() @@ -187,7 +187,7 @@ public abstract class DocumentBuilderFactory { /** * Specifies that the parser produced by this code will * provide support for XML namespaces. By default the value of this is set - * to false + * to {@code false} * * @param awareness true if the parser produced will provide support * for XML namespaces; false otherwise. @@ -200,7 +200,7 @@ public abstract class DocumentBuilderFactory { /** * Specifies that the parser produced by this code will * validate documents as they are parsed. By default the value of this - * is set to false. + * is set to {@code false}. * *

              * Note that "the validation" here means @@ -208,15 +208,13 @@ public abstract class DocumentBuilderFactory { * parser as defined in the XML recommendation. * In other words, it essentially just controls the DTD validation. * (except the legacy two properties defined in JAXP 1.2.) - *

              * *

              * To use modern schema languages such as W3C XML Schema or * RELAX NG instead of DTD, you can configure your parser to be * a non-validating parser by leaving the {@link #setValidating(boolean)} - * method false, then use the {@link #setSchema(Schema)} + * method {@code false}, then use the {@link #setSchema(Schema)} * method to associate a schema to a parser. - *

              * * @param validating true if the parser produced will validate documents * as they are parsed; false otherwise. @@ -234,7 +232,7 @@ public abstract class DocumentBuilderFactory { * element content that has an element only content model (see XML * Rec 3.2.1) will be eliminated. Due to reliance on the content model * this setting requires the parser to be in validating mode. By default - * the value of this is set to false. + * the value of this is set to {@code false}. * * @param whitespace true if the parser created must eliminate whitespace * in the element content when parsing XML documents; @@ -248,7 +246,7 @@ public abstract class DocumentBuilderFactory { /** * Specifies that the parser produced by this code will * expand entity reference nodes. By default the value of this is set to - * true + * {@code true} * * @param expandEntityRef true if the parser produced will expand entity * reference nodes; false otherwise. @@ -259,11 +257,10 @@ public abstract class DocumentBuilderFactory { } /** - *

              Specifies that the parser produced by this code will - * ignore comments. By default the value of this is set to false - * .

              + * Specifies that the parser produced by this code will + * ignore comments. By default the value of this is set to {@code false}. * - * @param ignoreComments boolean value to ignore comments during processing + * @param ignoreComments {@code boolean} value to ignore comments during processing */ public void setIgnoringComments(boolean ignoreComments) { @@ -274,7 +271,7 @@ public abstract class DocumentBuilderFactory { * Specifies that the parser produced by this code will * convert CDATA nodes to Text nodes and append it to the * adjacent (if any) text node. By default the value of this is set to - * false + * {@code false} * * @param coalescing true if the parser produced will convert CDATA nodes * to Text nodes and append it to the adjacent (if any) @@ -367,25 +364,23 @@ public abstract class DocumentBuilderFactory { * All implementations that implement JAXP 1.5 or newer are required to * support the {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_DTD} and * {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_SCHEMA} properties. - *

              + * *
                *
              • - *

                * Setting the {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_DTD} property * restricts the access to external DTDs, external Entity References to the * protocols specified by the property. * If access is denied during parsing due to the restriction of this property, * {@link org.xml.sax.SAXException} will be thrown by the parse methods defined by * {@link javax.xml.parsers.DocumentBuilder}. - *

                - *

                + *

              • + *
              • * Setting the {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_SCHEMA} property * restricts the access to external Schema set by the schemaLocation attribute to * the protocols specified by the property. If access is denied during parsing * due to the restriction of this property, {@link org.xml.sax.SAXException} * will be thrown by the parse methods defined by * {@link javax.xml.parsers.DocumentBuilder}. - *

                *
              • *
              * @@ -413,61 +408,61 @@ public abstract class DocumentBuilderFactory { throws IllegalArgumentException; /** - *

              Set a feature for this {@code DocumentBuilderFactory} and DocumentBuilders created by this factory.

              + * Set a feature for this {@code DocumentBuilderFactory} + * and {@code DocumentBuilder}s created by this factory. * *

              * Feature names are fully qualified {@link java.net.URI}s. * Implementations may define their own features. * A {@link ParserConfigurationException} is thrown if this {@code DocumentBuilderFactory} or the - * DocumentBuilders it creates cannot support the feature. + * {@code DocumentBuilder}s it creates cannot support the feature. * It is possible for a {@code DocumentBuilderFactory} to expose a feature value but be unable to change its state. - *

              + * * *

              * All implementations are required to support the {@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} feature. - * When the feature is:

              + * When the feature is: *
                *
              • - * true: the implementation will limit XML processing to conform to implementation limits. + * {@code true}: the implementation will limit XML processing to conform to implementation limits. * Examples include entity expansion limits and XML Schema constructs that would consume large amounts of resources. * If XML processing is limited for security reasons, it will be reported via a call to the registered * {@link org.xml.sax.ErrorHandler#fatalError(SAXParseException exception)}. * See {@link DocumentBuilder#setErrorHandler(org.xml.sax.ErrorHandler errorHandler)}. *
              • *
              • - * false: the implementation will processing XML according to the XML specifications without + * {@code false}: the implementation will processing XML according to the XML specifications without * regard to possible implementation limits. *
              • *
              * * @param name Feature name. - * @param value Is feature state true or false. + * @param value Is feature state {@code true} or {@code false}. * - * @throws ParserConfigurationException if this {@code DocumentBuilderFactory} or the DocumentBuilders + * @throws ParserConfigurationException if this {@code DocumentBuilderFactory} or the {@code DocumentBuilder}s * it creates cannot support this feature. - * @throws NullPointerException If the name parameter is null. + * @throws NullPointerException If the {@code name} parameter is null. * @since 1.5 */ public abstract void setFeature(String name, boolean value) throws ParserConfigurationException; /** - *

              Get the state of the named feature.

              + * Get the state of the named feature. * *

              * Feature names are fully qualified {@link java.net.URI}s. * Implementations may define their own features. * An {@link ParserConfigurationException} is thrown if this {@code DocumentBuilderFactory} or the - * DocumentBuilders it creates cannot support the feature. + * {@code DocumentBuilder}s it creates cannot support the feature. * It is possible for an {@code DocumentBuilderFactory} to expose a feature value but be unable to change its state. - *

              * * @param name Feature name. * * @return State of the named feature. * * @throws ParserConfigurationException if this {@code DocumentBuilderFactory} - * or the DocumentBuilders it creates cannot support this feature. + * or the {@code DocumentBuilder}s it creates cannot support this feature. * @since 1.5 */ public abstract boolean getFeature(String name) @@ -501,7 +496,7 @@ public abstract class DocumentBuilderFactory { } /** - *

              Set the {@link Schema} to be used by parsers created + * Set the {@link Schema} to be used by parsers created * from this factory. * *

              @@ -529,26 +524,26 @@ public abstract class DocumentBuilderFactory { * *

              * This processing will take effect even if - * the {@link #isValidating()} method returns false. + * the {@link #isValidating()} method returns {@code false}. * *

              It is an error to use - * the http://java.sun.com/xml/jaxp/properties/schemaSource - * property and/or the http://java.sun.com/xml/jaxp/properties/schemaLanguage + * the {@code http://java.sun.com/xml/jaxp/properties/schemaSource} + * property and/or the {@code http://java.sun.com/xml/jaxp/properties/schemaLanguage} * property in conjunction with a {@link Schema} object. * Such configuration will cause a {@link ParserConfigurationException} - * exception when the {@link #newDocumentBuilder()} is invoked.

              + * exception when the {@link #newDocumentBuilder()} is invoked. * * - *

              Note for implementors

              + *

              Note for implementors

              * *

              * A parser must be able to work with any {@link Schema} * implementation. However, parsers and schemas are allowed * to use implementation-specific custom mechanisms * as long as they yield the result described in the specification. - *

              * - * @param schema Schema to use or null + * + * @param schema {@code Schema} to use or {@code null} * to remove a schema. * * @throws UnsupportedOperationException When implementation does not @@ -569,16 +564,16 @@ public abstract class DocumentBuilderFactory { /** - *

              Set state of XInclude processing.

              + * Set state of XInclude processing. * *

              If XInclude markup is found in the document instance, should it be * processed as specified in - * XML Inclusions (XInclude) Version 1.0.

              + * XML Inclusions (XInclude) Version 1.0. * - *

              XInclude processing defaults to false.

              + *

              XInclude processing defaults to {@code false}. * - * @param state Set XInclude processing to true or - * false + * @param state Set XInclude processing to {@code true} or + * {@code false} * * @throws UnsupportedOperationException When implementation does not * override this method. @@ -594,7 +589,7 @@ public abstract class DocumentBuilderFactory { } /** - *

              Get state of XInclude processing.

              + * Get state of XInclude processing. * * @return current state of XInclude processing * diff --git a/jaxp/src/java.xml/share/classes/javax/xml/parsers/SAXParserFactory.java b/jaxp/src/java.xml/share/classes/javax/xml/parsers/SAXParserFactory.java index 1160a62edf4..1732047ee5e 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/parsers/SAXParserFactory.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/parsers/SAXParserFactory.java @@ -42,17 +42,17 @@ import org.xml.sax.SAXNotSupportedException; public abstract class SAXParserFactory { /** - *

              Should Parsers be validating?

              + * Should Parsers be validating? */ private boolean validating = false; /** - *

              Should Parsers be namespace aware?

              + * Should Parsers be namespace aware? */ private boolean namespaceAware = false; /** - *

              Protected constructor to force use of {@link #newInstance()}.

              + * Protected constructor to force use of {@link #newInstance()}. */ protected SAXParserFactory () { @@ -64,7 +64,6 @@ public abstract class SAXParserFactory { * This method uses the following ordered lookup procedure to determine * the {@code SAXParserFactory} implementation class to * load: - *

              *

                *
              • * Use the {@code javax.xml.parsers.SAXParserFactory} system @@ -138,19 +137,19 @@ public abstract class SAXParserFactory { } /** - *

                Obtain a new instance of a {@code SAXParserFactory} from class name. + * Obtain a new instance of a {@code SAXParserFactory} from class name. * This function is useful when there are multiple providers in the classpath. * It gives more control to the application as it can specify which provider - * should be loaded.

                + * should be loaded. * *

                Once an application has obtained a reference to a {@code SAXParserFactory} - * it can use the factory to configure and obtain parser instances.

                + * it can use the factory to configure and obtain parser instances. * * *

                Tip for Trouble-shooting

                *

                Setting the {@code jaxp.debug} system property will cause * this method to print a lot of debug messages - * to {@code System.err} about what it is doing and where it is looking at.

                + * to {@code System.err} about what it is doing and where it is looking at. * *

                * If you have problems, try: @@ -160,12 +159,12 @@ public abstract class SAXParserFactory { * * @param factoryClassName fully qualified factory class name that provides implementation of {@code javax.xml.parsers.SAXParserFactory}. * - * @param classLoader ClassLoader used to load the factory class. If null - * current Thread's context classLoader is used to load the factory class. + * @param classLoader {@code ClassLoader} used to load the factory class. If {@code null} + * current {@code Thread}'s context classLoader is used to load the factory class. * * @return New instance of a {@code SAXParserFactory} * - * @throws FactoryConfigurationError if factoryClassName is null, or + * @throws FactoryConfigurationError if {@code factoryClassName} is {@code null}, or * the factory class cannot be loaded, instantiated. * * @see #newInstance() @@ -179,8 +178,8 @@ public abstract class SAXParserFactory { } /** - *

                Creates a new instance of a SAXParser using the currently - * configured factory parameters.

                + * Creates a new instance of a SAXParser using the currently + * configured factory parameters. * * @return A new instance of a SAXParser. * @@ -196,7 +195,7 @@ public abstract class SAXParserFactory { /** * Specifies that the parser produced by this code will * provide support for XML namespaces. By default the value of this is set - * to false. + * to {@code false}. * * @param awareness true if the parser produced by this code will * provide support for XML namespaces; false otherwise. @@ -209,7 +208,7 @@ public abstract class SAXParserFactory { /** * Specifies that the parser produced by this code will * validate documents as they are parsed. By default the value of this is - * set to false. + * set to {@code false}. * *

                * Note that "the validation" here means @@ -217,15 +216,13 @@ public abstract class SAXParserFactory { * parser as defined in the XML recommendation. * In other words, it essentially just controls the DTD validation. * (except the legacy two properties defined in JAXP 1.2.) - *

                * *

                * To use modern schema languages such as W3C XML Schema or * RELAX NG instead of DTD, you can configure your parser to be * a non-validating parser by leaving the {@link #setValidating(boolean)} - * method false, then use the {@link #setSchema(Schema)} + * method {@code false}, then use the {@link #setSchema(Schema)} * method to associate a schema to a parser. - *

                * * @param validating true if the parser produced by this code will * validate documents as they are parsed; false otherwise. @@ -260,24 +257,23 @@ public abstract class SAXParserFactory { } /** - * - *

                Sets the particular feature in the underlying implementation of + * Sets the particular feature in the underlying implementation of * org.xml.sax.XMLReader. * A list of the core features and properties can be found at - * http://www.saxproject.org/

                + * http://www.saxproject.org/ * *

                All implementations are required to support the {@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} feature. - * When the feature is

                + * When the feature is *
                  *
                • - * true: the implementation will limit XML processing to conform to implementation limits. + * {@code true}: the implementation will limit XML processing to conform to implementation limits. * Examples include entity expansion limits and XML Schema constructs that would consume large amounts of resources. * If XML processing is limited for security reasons, it will be reported via a call to the registered * {@link org.xml.sax.ErrorHandler#fatalError(SAXParseException exception)}. - * See {@link SAXParser} parse methods for handler specification. + * See {@link SAXParser} {@code parse} methods for handler specification. *
                • *
                • - * When the feature is false, the implementation will processing XML according to the XML specifications without + * When the feature is {@code false}, the implementation will processing XML according to the XML specifications without * regard to possible implementation limits. *
                • *
                @@ -292,7 +288,7 @@ public abstract class SAXParserFactory { * @throws SAXNotSupportedException When the underlying XMLReader * recognizes the property name but doesn't support the * property. - * @throws NullPointerException If the name parameter is null. + * @throws NullPointerException If the {@code name} parameter is null. * * @see org.xml.sax.XMLReader#setFeature */ @@ -302,8 +298,8 @@ public abstract class SAXParserFactory { /** * - *

                Returns the particular property requested for in the underlying - * implementation of org.xml.sax.XMLReader.

                + * Returns the particular property requested for in the underlying + * implementation of org.xml.sax.XMLReader. * * @param name The name of the property to be retrieved. * @@ -347,12 +343,12 @@ public abstract class SAXParserFactory { } /** - *

                Set the {@link Schema} to be used by parsers created - * from this factory.

                + * Set the {@link Schema} to be used by parsers created + * from this factory. * *

                When a {@link Schema} is non-null, a parser will use a validator * created from it to validate documents before it passes information - * down to the application.

                + * down to the application. * *

                When warnings/errors/fatal errors are found by the validator, the parser must * handle them as if those errors were found by the parser itself. @@ -364,29 +360,28 @@ public abstract class SAXParserFactory { *

                A validator may modify the SAX event stream (for example by * adding default values that were missing in documents), and a parser * is responsible to make sure that the application will receive - * those modified event stream.

                + * those modified event stream. * - *

                Initially, null is set as the {@link Schema}.

                + *

                Initially, {@code null} is set as the {@link Schema}. * *

                This processing will take effect even if - * the {@link #isValidating()} method returns false. + * the {@link #isValidating()} method returns {@code false}. * *

                It is an error to use - * the http://java.sun.com/xml/jaxp/properties/schemaSource - * property and/or the http://java.sun.com/xml/jaxp/properties/schemaLanguage + * the {@code http://java.sun.com/xml/jaxp/properties/schemaSource} + * property and/or the {@code http://java.sun.com/xml/jaxp/properties/schemaLanguage} * property in conjunction with a non-null {@link Schema} object. * Such configuration will cause a {@link SAXException} - * exception when those properties are set on a {@link SAXParser}.

                + * exception when those properties are set on a {@link SAXParser}. * - *

                Note for implementors

                + *

                Note for implementors

                *

                * A parser must be able to work with any {@link Schema} * implementation. However, parsers and schemas are allowed * to use implementation-specific custom mechanisms * as long as they yield the result described in the specification. - *

                * - * @param schema Schema to use, null to remove a schema. + * @param schema {@code Schema} to use, {@code null} to remove a schema. * * @throws UnsupportedOperationException When implementation does not * override this method @@ -404,16 +399,16 @@ public abstract class SAXParserFactory { } /** - *

                Set state of XInclude processing.

                + * Set state of XInclude processing. * *

                If XInclude markup is found in the document instance, should it be * processed as specified in - * XML Inclusions (XInclude) Version 1.0.

                + * XML Inclusions (XInclude) Version 1.0. * - *

                XInclude processing defaults to false.

                + *

                XInclude processing defaults to {@code false}. * - * @param state Set XInclude processing to true or - * false + * @param state Set XInclude processing to {@code true} or + * {@code false} * * @throws UnsupportedOperationException When implementation does not * override this method @@ -429,7 +424,7 @@ public abstract class SAXParserFactory { } /** - *

                Get state of XInclude processing.

                + * Get state of XInclude processing. * * @return current state of XInclude processing * diff --git a/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLEventFactory.java b/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLEventFactory.java index fc14bc620bc..1ec4d382711 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLEventFactory.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLEventFactory.java @@ -70,7 +70,6 @@ public abstract class XMLEventFactory { * This static method creates a new factory instance. * This method uses the following ordered lookup procedure to determine * the XMLEventFactory implementation class to load: - *

                *

                  *
                • * Use the javax.xml.stream.XMLEventFactory system property. @@ -158,7 +157,6 @@ public abstract class XMLEventFactory { *

                  * This method uses the following ordered lookup procedure to determine * the XMLEventFactory implementation class to load: - *

                  *

                    *
                  • * Use the value of the system property identified by {@code factoryId}. diff --git a/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLInputFactory.java b/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLInputFactory.java index 90030378467..191a6df6f19 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLInputFactory.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLInputFactory.java @@ -160,7 +160,7 @@ public abstract class XMLInputFactory { * This static method creates a new factory instance. * This method uses the following ordered lookup procedure to determine * the XMLInputFactory implementation class to load: - *

                    + * *
                      *
                    • *

                      Use the javax.xml.stream.XMLInputFactory system property. @@ -201,12 +201,11 @@ public abstract class XMLInputFactory { *

                      * Once an application has obtained a reference to a XMLInputFactory it * can use the factory to configure and obtain stream instances. - *

                      *

                      * Note that this is a new method that replaces the deprecated newInstance() method. * No changes in behavior are defined by this replacement method relative to * the deprecated method. - *

                      + * * @throws FactoryConfigurationError in case of {@linkplain * java.util.ServiceConfigurationError service configuration error} or if * the implementation is not available or cannot be instantiated. @@ -245,7 +244,6 @@ public abstract class XMLInputFactory { *

                      * This method uses the following ordered lookup procedure to determine * the XMLInputFactory implementation class to load: - *

                      *

                        *
                      • *

                        @@ -488,7 +486,6 @@ public abstract class XMLInputFactory { *

                        * All implementations that implement JAXP 1.5 or newer are required to * support the {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_DTD} property. - *

                        *
                          *
                        • *

                          @@ -497,7 +494,7 @@ public abstract class XMLInputFactory { * due to the restriction of this property, {@link javax.xml.stream.XMLStreamException} * will be thrown by the {@link javax.xml.stream.XMLStreamReader#next()} or * {@link javax.xml.stream.XMLEventReader#nextEvent()} method. - *

                          + * *
                        • *
                        * @param name The name of the property (may not be null) diff --git a/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLOutputFactory.java b/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLOutputFactory.java index 4524a4e8315..caa230594db 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLOutputFactory.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLOutputFactory.java @@ -54,17 +54,18 @@ import javax.xml.transform.Result; * Default Value * Required * - * javax.xml.stream.isRepairingNamespacesdefaults prefixes on the output sideBooleanFalseYes + * javax.xml.stream.isRepairingNamespacesdefaults prefixes + * on the output sideBooleanFalseYes * * * - *

                        The following paragraphs describe the namespace and prefix repair algorithm:

                        + *

                        The following paragraphs describe the namespace and prefix repair algorithm: * *

                        The property can be set with the following code line: - * setProperty("javax.xml.stream.isRepairingNamespaces",new Boolean(true|false));

                        + * {@code setProperty("javax.xml.stream.isRepairingNamespaces", new Boolean(true|false));} * *

                        This property specifies that the writer default namespace prefix declarations. - * The default value is false.

                        + * The default value is false. * *

                        If a writer isRepairingNamespaces it will create a namespace declaration * on the current StartElement for @@ -74,11 +75,11 @@ import javax.xml.transform.Result; * has not been declared in a parent of the current StartElement it will be declared * on the current StartElement. If the defaultNamespace is bound and in scope * and the default namespace matches the URI of the attribute or StartElement - * QName no prefix will be assigned.

                        + * QName no prefix will be assigned. * *

                        If an element or attribute name has a prefix, but is not * bound to any namespace URI, then the prefix will be removed - * during serialization.

                        + * during serialization. * *

                        If element and/or attribute names in the same start or * empty-element tag are bound to different namespace URIs and @@ -86,20 +87,20 @@ import javax.xml.transform.Result; * occurring attribute retains the original prefix and the * following attributes have their prefixes replaced with a * new prefix that is bound to the namespace URIs of those - * attributes.

                        + * attributes. * *

                        If an element or attribute name uses a prefix that is * bound to a different URI than that inherited from the * namespace context of the parent of that element and there * is no namespace declaration in the context of the current - * element then such a namespace declaration is added.

                        + * element then such a namespace declaration is added. * *

                        If an element or attribute name is bound to a prefix and * there is a namespace declaration that binds that prefix * to a different URI then that namespace declaration is * either removed if the correct mapping is inherited from * the parent context of that element, or changed to the - * namespace URI of the element or attribute using that prefix.

                        + * namespace URI of the element or attribute using that prefix. * * @version 1.2 * @author Copyright (c) 2009, 2015 by Oracle Corporation. All Rights Reserved. @@ -136,7 +137,6 @@ public abstract class XMLOutputFactory { * This static method creates a new factory instance. This method uses the * following ordered lookup procedure to determine the XMLOutputFactory * implementation class to load: - *

                        *

                          *
                        • * Use the javax.xml.stream.XMLOutputFactory system property. @@ -177,6 +177,7 @@ public abstract class XMLOutputFactory { *

                          * Otherwise, the system-default implementation is returned. *

                        • + *
                        *

                        * Once an application has obtained a reference to a XMLOutputFactory it * can use the factory to configure and obtain stream instances. @@ -222,7 +223,6 @@ public abstract class XMLOutputFactory { *

                        * This method uses the following ordered lookup procedure to determine * the XMLOutputFactory implementation class to load: - *

                        *

                          *
                        • * Use the value of the system property identified by {@code factoryId}. diff --git a/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLStreamReader.java b/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLStreamReader.java index fd15819f3d8..e92e979ed08 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLStreamReader.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLStreamReader.java @@ -57,9 +57,9 @@ import javax.xml.namespace.QName; * javax.xml.stream.notations and javax.xml.stream.entities. * When the current event is a DTD the following call will return a * list of Notations - * List l = (List) getProperty("javax.xml.stream.notations"); + * {@code List l = (List) getProperty("javax.xml.stream.notations");} * The following call will return a list of entity declarations: - * List l = (List) getProperty("javax.xml.stream.entities"); + * {@code List l = (List) getProperty("javax.xml.stream.entities");} * These properties can only be accessed during a DTD event and * are defined to return null if the information is not available. * @@ -97,12 +97,13 @@ import javax.xml.namespace.QName; * getElementText(), nextTag() * * + * * ATTRIBUTE * next(), nextTag() * getAttributeXXX(), isAttributeSpecified(), * * - * + * * NAMESPACE * next(), nextTag() * getNamespaceXXX() @@ -184,7 +185,7 @@ public interface XMLStreamReader extends XMLStreamConstants { * If element content is empty (i.e. content is "") then no CHARACTERS event will be reported. * *

                          Given the following XML:
                          - * <foo><!--description-->content text<![CDATA[<greeting>Hello</greeting>]]>other content</foo>
                          + * {@code content textHello>/greeting>]]>other content>/foo>}
                          * The behavior of calling next() when being on foo will be:
                          * 1- the comment (COMMENT)
                          * 2- then the characters section (CHARACTERS)
                          @@ -192,14 +193,14 @@ public interface XMLStreamReader extends XMLStreamConstants { * 4- then the next characters section (another CHARACTERS)
                          * 5- then the END_ELEMENT
                          * - *

                          NOTE: empty element (such as <tag/>) will be reported + *

                          NOTE: empty element (such as {@code }) will be reported * with two separate events: START_ELEMENT, END_ELEMENT - This preserves - * parsing equivalency of empty element to <tag></tag>. + * parsing equivalency of empty element to {@code }. * * This method will throw an IllegalStateException if it is called after hasNext() returns false. * @see javax.xml.stream.events.XMLEvent * @return the integer code corresponding to the current parse event - * @throws NoSuchElementException if this is called when hasNext() returns false + * @throws java.util.NoSuchElementException if this is called when hasNext() returns false * @throws XMLStreamException if there is an error processing the underlying XML source */ public int next() throws XMLStreamException; @@ -219,38 +220,39 @@ public interface XMLStreamReader extends XMLStreamConstants { * Reads the content of a text-only element, an exception is thrown if this is * not a text-only element. * Regardless of value of javax.xml.stream.isCoalescing this method always returns coalesced content. - *
                          Precondition: the current event is START_ELEMENT. - *
                          Postcondition: the current event is the corresponding END_ELEMENT. + *
                          Precondition: the current event is START_ELEMENT. + *
                          Postcondition: the current event is the corresponding END_ELEMENT. * - *
                          The method does the following (implementations are free to optimized + *
                          The method does the following (implementations are free to optimized * but must do equivalent processing): *

                              * if(getEventType() != XMLStreamConstants.START_ELEMENT) {
                          -   * throw new XMLStreamException(
                          -   * "parser must be on START_ELEMENT to read next text", getLocation());
                          +   *     throw new XMLStreamException(
                          +   *     "parser must be on START_ELEMENT to read next text", getLocation());
                              * }
                          +   *
                              * int eventType = next();
                              * StringBuffer content = new StringBuffer();
                          -   * while(eventType != XMLStreamConstants.END_ELEMENT ) {
                          -   * if(eventType == XMLStreamConstants.CHARACTERS
                          -   * || eventType == XMLStreamConstants.CDATA
                          -   * || eventType == XMLStreamConstants.SPACE
                          -   * || eventType == XMLStreamConstants.ENTITY_REFERENCE) {
                          -   * buf.append(getText());
                          -   * } else if(eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
                          -   * || eventType == XMLStreamConstants.COMMENT) {
                          -   * // skipping
                          -   * } else if(eventType == XMLStreamConstants.END_DOCUMENT) {
                          -   * throw new XMLStreamException(
                          -   * "unexpected end of document when reading element text content", this);
                          -   * } else if(eventType == XMLStreamConstants.START_ELEMENT) {
                          -   * throw new XMLStreamException(
                          -   * "element text content may not contain START_ELEMENT", getLocation());
                          -   * } else {
                          -   * throw new XMLStreamException(
                          -   * "Unexpected event type "+eventType, getLocation());
                          -   * }
                          -   * eventType = next();
                          +   * while(eventType != XMLStreamConstants.END_ELEMENT) {
                          +   *     if(eventType == XMLStreamConstants.CHARACTERS
                          +   *        || eventType == XMLStreamConstants.CDATA
                          +   *        || eventType == XMLStreamConstants.SPACE
                          +   *        || eventType == XMLStreamConstants.ENTITY_REFERENCE) {
                          +   *           buf.append(getText());
                          +   *     } else if(eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
                          +   *               || eventType == XMLStreamConstants.COMMENT) {
                          +   *         // skipping
                          +   *     } else if(eventType == XMLStreamConstants.END_DOCUMENT) {
                          +   *         throw new XMLStreamException(
                          +   *         "unexpected end of document when reading element text content", this);
                          +   *     } else if(eventType == XMLStreamConstants.START_ELEMENT) {
                          +   *         throw new XMLStreamException(
                          +   *         "element text content may not contain START_ELEMENT", getLocation());
                          +   *     } else {
                          +   *         throw new XMLStreamException(
                          +   *         "Unexpected event type "+eventType, getLocation());
                          +   *     }
                          +   *     eventType = next();
                              * }
                              * return buf.toString();
                              * 
                          @@ -268,33 +270,33 @@ public interface XMLStreamReader extends XMLStreamConstants { * are encountered, an exception is thrown. This method should * be used when processing element-only content seperated by white space. * - *
                          Precondition: none - *
                          Postcondition: the current event is START_ELEMENT or END_ELEMENT + *
                          Precondition: none + *
                          Postcondition: the current event is START_ELEMENT or END_ELEMENT * and cursor may have moved over any whitespace event. * - *
                          Essentially it does the following (implementations are free to optimized + *
                          Essentially it does the following (implementations are free to optimized * but must do equivalent processing): - *
                          +   * 
                           {@code
                              * int eventType = next();
                          -   * while((eventType == XMLStreamConstants.CHARACTERS && isWhiteSpace()) // skip whitespace
                          -   * || (eventType == XMLStreamConstants.CDATA && isWhiteSpace())
                          +   * while((eventType == XMLStreamConstants.CHARACTERS && isWhiteSpace()) // skip whitespace
                          +   * || (eventType == XMLStreamConstants.CDATA && isWhiteSpace())
                              * // skip whitespace
                              * || eventType == XMLStreamConstants.SPACE
                              * || eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
                              * || eventType == XMLStreamConstants.COMMENT
                              * ) {
                          -   * eventType = next();
                          +   *     eventType = next();
                              * }
                          -   * if (eventType != XMLStreamConstants.START_ELEMENT && eventType != XMLStreamConstants.END_ELEMENT) {
                          -   * throw new String XMLStreamException("expected start or end tag", getLocation());
                          +   * if (eventType != XMLStreamConstants.START_ELEMENT && eventType != XMLStreamConstants.END_ELEMENT) {
                          +   *     throw new String XMLStreamException("expected start or end tag", getLocation());
                              * }
                          -   * return eventType;
                          +   * return eventType; }
                              * 
                          * * @return the event type of the element read (START_ELEMENT or END_ELEMENT) * @throws XMLStreamException if the current event is not white space, PROCESSING_INSTRUCTION, * START_ELEMENT or END_ELEMENT - * @throws NoSuchElementException if this is called when hasNext() returns false + * @throws java.util.NoSuchElementException if this is called when hasNext() returns false */ public int nextTag() throws XMLStreamException; @@ -309,7 +311,7 @@ public interface XMLStreamReader extends XMLStreamConstants { public boolean hasNext() throws XMLStreamException; /** - * Frees any resources associated with this Reader. This method does not close the + * Frees any resources associated with this Reader. This method does not close the * underlying input source. * @throws XMLStreamException if there are errors freeing associated resources */ @@ -542,7 +544,7 @@ public interface XMLStreamReader extends XMLStreamConstants { * If the number of characters actually copied is less than the "length", then there is no more text. * Otherwise, subsequent calls need to be made until all text has been retrieved. For example: * - * + *
                          {@code
                              * int length = 1024;
                              * char[] myBuffer = new char[ length ];
                              *
                          @@ -553,7 +555,7 @@ public interface XMLStreamReader extends XMLStreamConstants {
                              *   if (nCopied < length)
                              *       break;
                              * }
                          -   * 
                          +   * } 
                          * XMLStreamException may be thrown if there are any XML errors in the underlying source. * The "targetStart" argument must be greater than or equal to 0 and less than the length of "target", * Length must be greater than 0 and "targetStart + length" must be less than or equal to length of "target". @@ -564,8 +566,8 @@ public interface XMLStreamReader extends XMLStreamConstants { * @param length the number of characters to copy * @return the number of characters actually copied * @throws XMLStreamException if the underlying XML source is not well-formed - * @throws IndexOutOfBoundsException if targetStart < 0 or > than the length of target - * @throws IndexOutOfBoundsException if length < 0 or targetStart + length > length of target + * @throws IndexOutOfBoundsException if targetStart {@literal <} 0 or {@literal >} than the length of target + * @throws IndexOutOfBoundsException if length {@literal <} 0 or targetStart + length {@literal >} length of target * @throws UnsupportedOperationException if this method is not supported * @throws NullPointerException is if target is null */ diff --git a/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLStreamWriter.java b/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLStreamWriter.java index f3615892b7a..ca05fc083be 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLStreamWriter.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLStreamWriter.java @@ -33,9 +33,9 @@ import javax.xml.namespace.NamespaceContext; /** * The XMLStreamWriter interface specifies how to write XML. The XMLStreamWriter does * not perform well formedness checking on its input. However - * the writeCharacters method is required to escape & , < and > + * the writeCharacters method is required to escape {@literal &, < and >} * For attribute values the writeAttribute method will escape the - * above characters plus " to ensure that all character content + * above characters plus {@literal "} to ensure that all character content * and attribute values are well formed. * * Each NAMESPACE @@ -44,12 +44,12 @@ import javax.xml.namespace.NamespaceContext; * * * - * + * * * * - * - * + * + * * * * @@ -62,7 +62,7 @@ import javax.xml.namespace.NamespaceContext; * * * - * + * * * * * * * - * + * * * * * * * - * + * * * * * * * * * * - * + * * * * * * * * * @@ -175,10 +175,14 @@ import javax.xml.namespace.NamespaceContext; * Notes: *
                            *
                          • [1] if namespaceURI == default Namespace URI, then no prefix is written
                          • - *
                          • [2] if prefix == "" || null && namespaceURI == "", then no prefix or Namespace declaration is generated or written
                          • + *
                          • [2] if prefix == "" || null {@literal &&} namespaceURI == "", then + * no prefix or Namespace declaration is generated or written
                          • *
                          • [3] if prefix == "" || null, then a prefix is randomly generated
                          • - *
                          • [4] if prefix == "" || null, then it is treated as the default Namespace and no prefix is generated or written, an xmlns declaration is generated and written if the namespaceURI is unbound
                          • - *
                          • [5] if prefix == "" || null, then it is treated as an invalid attempt to define the default Namespace and an XMLStreamException is thrown
                          • + *
                          • [4] if prefix == "" || null, then it is treated as the default Namespace and + * no prefix is generated or written, an xmlns declaration is generated + * and written if the namespaceURI is unbound
                          • + *
                          • [5] if prefix == "" || null, then it is treated as an invalid attempt to + * define the default Namespace and an XMLStreamException is thrown
                          • *
                          * * diff --git a/jaxp/src/java.xml/share/classes/javax/xml/transform/Result.java b/jaxp/src/java.xml/share/classes/javax/xml/transform/Result.java index fb5a42ee923..dab8dcde123 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/transform/Result.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/transform/Result.java @@ -27,7 +27,7 @@ package javax.xml.transform; /** *

                          An object that implements this interface contains the information - * needed to build a transformation result tree.

                          + * needed to build a transformation result tree. * * @author Jeff Suttor * @since 1.4 @@ -38,7 +38,7 @@ public interface Result { * The name of the processing instruction that is sent if the * result tree disables output escaping. * - *

                          Normally, result tree serialization escapes & and < (and + *

                          Normally, result tree serialization escapes{@literal & and <} (and * possibly other characters) when outputting text nodes. * This ensures that the output is well-formed XML. However, * it is sometimes convenient to be able to produce output that is @@ -46,10 +46,10 @@ public interface Result { * the output may include ill-formed sections that will * be transformed into well-formed XML by a subsequent non-XML aware * process. If a processing instruction is sent with this name, - * serialization should be output without any escaping.

                          + * serialization should be output without any escaping. * *

                          Result DOM trees may also have PI_DISABLE_OUTPUT_ESCAPING and - * PI_ENABLE_OUTPUT_ESCAPING inserted into the tree.

                          + * PI_ENABLE_OUTPUT_ESCAPING inserted into the tree. * * @see disable-output-escaping in XSLT Specification */ @@ -71,7 +71,7 @@ public interface Result { * *

                          If the Result is not to be written to a file, the system identifier is optional. * The application may still want to provide one, however, for use in error messages - * and warnings, or to resolve relative output identifiers.

                          + * and warnings, or to resolve relative output identifiers. * * @param systemId The system identifier as a URI string. */ diff --git a/jaxp/src/java.xml/share/classes/javax/xml/transform/TransformerFactory.java b/jaxp/src/java.xml/share/classes/javax/xml/transform/TransformerFactory.java index 2fd931df891..b0957826a0b 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/transform/TransformerFactory.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/transform/TransformerFactory.java @@ -28,13 +28,13 @@ package javax.xml.transform; /** *

                          A TransformerFactory instance can be used to create * {@link javax.xml.transform.Transformer} and - * {@link javax.xml.transform.Templates} objects.

                          + * {@link javax.xml.transform.Templates} objects. * *

                          The system property that determines which Factory implementation - * to create is named "javax.xml.transform.TransformerFactory". + * to create is named {@code "javax.xml.transform.TransformerFactory"}. * This property names a concrete subclass of the * {@code TransformerFactory} abstract class. If the property is not - * defined, a platform default is be used.

                          + * defined, a platform default is be used. * * @author Jeff Suttor * @author Neeraj Bajaj @@ -51,14 +51,11 @@ public abstract class TransformerFactory { /** - *

                          * Obtain a new instance of a {@code TransformerFactory}. * This static method creates a new factory instance. *

                          * This method uses the following ordered lookup procedure to determine - * the {@code TransformerFactory} implementation class to - * load: - *

                          + * the {@code TransformerFactory} implementation class to load: *

                            *
                          • * Use the {@code javax.xml.transform.TransformerFactory} system @@ -118,34 +115,34 @@ public abstract class TransformerFactory { } /** - *

                            Obtain a new instance of a {@code TransformerFactory} from factory class name. + * Obtain a new instance of a {@code TransformerFactory} from factory class name. * This function is useful when there are multiple providers in the classpath. * It gives more control to the application as it can specify which provider - * should be loaded.

                            + * should be loaded. * *

                            Once an application has obtained a reference to a * {@code TransformerFactory} it can use the factory to configure - * and obtain transformer instances.

                            + * and obtain transformer instances. * *

                            Tip for Trouble-shooting

                            - *

                            Setting the jaxp.debug system property will cause + *

                            Setting the {@code jaxp.debug} system property will cause * this method to print a lot of debug messages - * to System.err about what it is doing and where it is looking at.

                            + * to {@code System.err} about what it is doing and where it is looking at. * - *

                            If you have problems try:

                            + *

                            If you have problems try: *

                                  * java -Djaxp.debug=1 YourProgram ....
                                  * 
                            * * @param factoryClassName fully qualified factory class name that provides implementation of {@code javax.xml.transform.TransformerFactory}. * - * @param classLoader ClassLoader used to load the factory class. If null - * current Thread's context classLoader is used to load the factory class. + * @param classLoader {@code ClassLoader} used to load the factory class. If {@code null} + * current {@code Thread}'s context classLoader is used to load the factory class. * * @return new TransformerFactory instance, never null. * * @throws TransformerFactoryConfigurationError - * if factoryClassName is null, or + * if {@code factoryClassName} is {@code null}, or * the factory class cannot be loaded, instantiated. * * @see #newInstance() @@ -160,29 +157,29 @@ public abstract class TransformerFactory { factoryClassName, classLoader, false, false); } /** - *

                            Process the Source into a Transformer - * Object. The Source is an XSLT document that + * Process the {@code Source} into a {@code Transformer} + * {@code Object}. The {@code Source} is an XSLT document that * conforms to * XSL Transformations (XSLT) Version 1.0. Care must - * be taken not to use this Transformer in multiple - * Threads running concurrently. - * Different TransformerFactories can be used concurrently by - * different Threads.

                            + * be taken not to use this {@code Transformer} in multiple + * {@code Thread}s running concurrently. + * Different {@code TransformerFactories} can be used concurrently by + * different {@code Thread}s. * - * @param source Source of XSLT document used to create - * Transformer. - * Examples of XML Sources include + * @param source {@code Source } of XSLT document used to create + * {@code Transformer}. + * Examples of XML {@code Source}s include * {@link javax.xml.transform.dom.DOMSource DOMSource}, * {@link javax.xml.transform.sax.SAXSource SAXSource}, and * {@link javax.xml.transform.stream.StreamSource StreamSource}. * - * @return A Transformer object that may be used to perform - * a transformation in a single Thread, never - * null. + * @return A {@code Transformer} object that may be used to perform + * a transformation in a single {@code Thread}, never + * {@code null}. * * @throws TransformerConfigurationException Thrown if there are errors when - * parsing the Source or it is not possible to create a - * Transformer instance. + * parsing the {@code Source} or it is not possible to create a + * {@code Transformer} instance. * * @see * XSL Transformations (XSLT) Version 1.0 @@ -191,15 +188,15 @@ public abstract class TransformerFactory { throws TransformerConfigurationException; /** - *

                            Create a new Transformer that performs a copy - * of the Source to the Result. - * i.e. the "identity transform".

                            + * Create a new {@code Transformer} that performs a copy + * of the {@code Source} to the {@code Result}. + * i.e. the "identity transform". * * @return A Transformer object that may be used to perform a transformation * in a single thread, never null. * * @throws TransformerConfigurationException When it is not - * possible to create a Transformer instance. + * possible to create a {@code Transformer} instance. */ public abstract Transformer newTransformer() throws TransformerConfigurationException; @@ -215,7 +212,7 @@ public abstract class TransformerFactory { * @param source An object that holds a URL, input stream, etc. * * @return A Templates object capable of being used for transformation - * purposes, never null. + * purposes, never {@code null}. * * @throws TransformerConfigurationException When parsing to * construct the Templates object fails. @@ -224,13 +221,13 @@ public abstract class TransformerFactory { throws TransformerConfigurationException; /** - *

                            Get the stylesheet specification(s) associated with the - * XML Source document via the + * Get the stylesheet specification(s) associated with the + * XML {@code Source} document via the * * xml-stylesheet processing instruction that match the given criteria. * Note that it is possible to return several stylesheets, in which case * they are applied as if they were a list of imports or cascades in a - * single stylesheet.

                            + * single stylesheet. * * @param source The XML source document. * @param media The media attribute to be matched. May be null, in which @@ -238,12 +235,12 @@ public abstract class TransformerFactory { * @param title The value of the title attribute to match. May be null. * @param charset The value of the charset attribute to match. May be null. * - * @return A Source Object suitable for passing + * @return A {@code Source} {@code Object} suitable for passing * to the {@code TransformerFactory}. * - * @throws TransformerConfigurationException An Exception + * @throws TransformerConfigurationException An {@code Exception} * is thrown if an error occurings during parsing of the - * source. + * {@code source}. * * @see * Associating Style Sheets with XML documents Version 1.0 @@ -275,22 +272,21 @@ public abstract class TransformerFactory { //======= CONFIGURATION METHODS ======= /** - *

                            Set a feature for this {@code TransformerFactory} and Transformers - * or Templates created by this factory.

                            + *

                            Set a feature for this {@code TransformerFactory} and {@code Transformer}s + * or {@code Template}s created by this factory. * *

                            * Feature names are fully qualified {@link java.net.URI}s. * Implementations may define their own features. * An {@link TransformerConfigurationException} is thrown if this {@code TransformerFactory} or the - * Transformers or Templates it creates cannot support the feature. + * {@code Transformer}s or {@code Template}s it creates cannot support the feature. * It is possible for an {@code TransformerFactory} to expose a feature value but be unable to change its state. - *

                            * *

                            All implementations are required to support the {@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} feature. - * When the feature is:

                            + * When the feature is: *
                              *
                            • - * true: the implementation will limit XML processing to conform to implementation limits + * {@code true}: the implementation will limit XML processing to conform to implementation limits * and behave in a secure fashion as defined by the implementation. * Examples include resolving user defined style sheets and functions. * If XML processing is limited for security reasons, it will be reported via a call to the registered @@ -298,17 +294,17 @@ public abstract class TransformerFactory { * See {@link #setErrorListener(ErrorListener listener)}. *
                            • *
                            • - * false: the implementation will processing XML according to the XML specifications without + * {@code false}: the implementation will processing XML according to the XML specifications without * regard to possible implementation limits. *
                            • *
                            * * @param name Feature name. - * @param value Is feature state true or false. + * @param value Is feature state {@code true} or {@code false}. * * @throws TransformerConfigurationException if this {@code TransformerFactory} - * or the Transformers or Templates it creates cannot support this feature. - * @throws NullPointerException If the name parameter is null. + * or the {@code Transformer}s or {@code Template}s it creates cannot support this feature. + * @throws NullPointerException If the {@code name} parameter is null. */ public abstract void setFeature(String name, boolean value) throws TransformerConfigurationException; @@ -319,16 +315,15 @@ public abstract class TransformerFactory { *

                            * Feature names are fully qualified {@link java.net.URI}s. * Implementations may define their own features. - * false is returned if this {@code TransformerFactory} or the - * Transformers or Templates it creates cannot support the feature. + * {@code false} is returned if this {@code TransformerFactory} or the + * {@code Transformer}s or {@code Template}s it creates cannot support the feature. * It is possible for an {@code TransformerFactory} to expose a feature value but be unable to change its state. - *

                            * * @param name Feature name. * - * @return The current state of the feature, true or false. + * @return The current state of the feature, {@code true} or {@code false}. * - * @throws NullPointerException If the name parameter is null. + * @throws NullPointerException If the {@code name} parameter is null. */ public abstract boolean getFeature(String name); @@ -336,13 +331,13 @@ public abstract class TransformerFactory { * Allows the user to set specific attributes on the underlying * implementation. An attribute in this context is defined to * be an option that the implementation provides. - * An IllegalArgumentException is thrown if the underlying + * An {@code IllegalArgumentException} is thrown if the underlying * implementation doesn't recognize the attribute. *

                            * All implementations that implement JAXP 1.5 or newer are required to * support the {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_DTD} and * {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_STYLESHEET} properties. - *

                            + * *
                              *
                            • *

                              @@ -351,7 +346,7 @@ public abstract class TransformerFactory { * If access is denied during transformation due to the restriction of this property, * {@link javax.xml.transform.TransformerException} will be thrown by * {@link javax.xml.transform.Transformer#transform(Source, Result)}. - *

                              + * *

                              * Access to external DTDs in the stylesheet is restricted to the protocols * specified by the {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_DTD} property. @@ -359,7 +354,7 @@ public abstract class TransformerFactory { * restriction of this property, * {@link javax.xml.transform.TransformerConfigurationException} will be thrown * by the {@link #newTransformer(Source)} method. - *

                              + * *

                              * Access to external reference set by the stylesheet processing instruction, * Import and Include element is restricted to the protocols specified by the @@ -368,14 +363,14 @@ public abstract class TransformerFactory { * restriction of this property, * {@link javax.xml.transform.TransformerConfigurationException} will be thrown * by the {@link #newTransformer(Source)} method. - *

                              + * *

                              * Access to external document through XSLT document function is restricted * to the protocols specified by the property. If access is denied during * the transformation due to the restriction of this property, * {@link javax.xml.transform.TransformerException} will be thrown by the * {@link javax.xml.transform.Transformer#transform(Source, Result)} method. - *

                              + * *
                            • *
                            * @@ -390,7 +385,7 @@ public abstract class TransformerFactory { /** * Allows the user to retrieve specific attributes on the underlying * implementation. - * An IllegalArgumentException is thrown if the underlying + * An {@code IllegalArgumentException} is thrown if the underlying * implementation doesn't recognize the attribute. * * @param name The name of the attribute. @@ -406,13 +401,13 @@ public abstract class TransformerFactory { * Set the error event listener for the TransformerFactory, which * is used for the processing of transformation instructions, * and not for the transformation itself. - * An IllegalArgumentException is thrown if the - * ErrorListener listener is null. + * An {@code IllegalArgumentException} is thrown if the + * {@code ErrorListener} listener is {@code null}. * * @param listener The new error listener. * - * @throws IllegalArgumentException When listener is - * null + * @throws IllegalArgumentException When {@code listener} is + * {@code null} */ public abstract void setErrorListener(ErrorListener listener); diff --git a/jaxp/src/java.xml/share/classes/javax/xml/transform/dom/DOMResult.java b/jaxp/src/java.xml/share/classes/javax/xml/transform/dom/DOMResult.java index 67ec2418740..8c4a1b789f9 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/transform/dom/DOMResult.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/transform/dom/DOMResult.java @@ -29,29 +29,32 @@ import javax.xml.transform.Result; import org.w3c.dom.Node; /** - *

                            Acts as a holder for a transformation result tree in the form of a Document Object Model (DOM) tree.

                            + * Acts as a holder for a transformation result tree + * in the form of a Document Object Model (DOM) tree. * - *

                            If no output DOM source is set, the transformation will create a Document node as the holder for the result of the transformation, - * which may be retrieved with {@link #getNode()}.

                            + *

                            If no output DOM source is set, the transformation will create + * a Document node as the holder for the result of the transformation, + * which may be retrieved with {@link #getNode()}. * * @author Jeff Suttor * @since 1.4 */ public class DOMResult implements Result { - /**

                            If {@link javax.xml.transform.TransformerFactory#getFeature} - * returns true when passed this value as an argument, - * the Transformer supports Result output of this type.

                            + /** + * If {@link javax.xml.transform.TransformerFactory#getFeature} + * returns {@code true} when passed this value as an argument, + * the {@code Transformer} supports {@code Result} output of this type. */ public static final String FEATURE = "http://javax.xml.transform.dom.DOMResult/feature"; /** - *

                            Zero-argument default constructor.

                            + * Zero-argument default constructor. * - *

                            node, - * siblingNode and - * systemId - * will be set to null.

                            + *

                            {@code node}, + * {@code siblingNode} and + * {@code systemId} + * will be set to {@code null}. */ public DOMResult() { setNode(null); @@ -60,17 +63,17 @@ public class DOMResult implements Result { } /** - *

                            Use a DOM node to create a new output target.

                            + * Use a DOM node to create a new output target. * *

                            In practice, the node should be * a {@link org.w3c.dom.Document} node, * a {@link org.w3c.dom.DocumentFragment} node, or * a {@link org.w3c.dom.Element} node. - * In other words, a node that accepts children.

                            + * In other words, a node that accepts children. * - *

                            siblingNode and - * systemId - * will be set to null.

                            + *

                            {@code siblingNode} and + * {@code systemId} + * will be set to {@code null}. * * @param node The DOM node that will contain the result tree. */ @@ -81,15 +84,15 @@ public class DOMResult implements Result { } /** - *

                            Use a DOM node to create a new output target with the specified System ID.

                            + * Use a DOM node to create a new output target with the specified System ID. * *

                            In practice, the node should be * a {@link org.w3c.dom.Document} node, * a {@link org.w3c.dom.DocumentFragment} node, or * a {@link org.w3c.dom.Element} node. - * In other words, a node that accepts children.

                            + * In other words, a node that accepts children. * - *

                            siblingNode will be set to null.

                            + *

                            {@code siblingNode} will be set to {@code null}. * * @param node The DOM node that will contain the result tree. * @param systemId The system identifier which may be used in association with this node. @@ -101,32 +104,33 @@ public class DOMResult implements Result { } /** - *

                            Use a DOM node to create a new output target specifying the child node where the result nodes should be inserted before.

                            + * Use a DOM node to create a new output target specifying + * the child node where the result nodes should be inserted before. * - *

                            In practice, node and nextSibling should be + *

                            In practice, {@code node} and {@code nextSibling} should be * a {@link org.w3c.dom.Document} node, * a {@link org.w3c.dom.DocumentFragment} node, or * a {@link org.w3c.dom.Element} node. - * In other words, a node that accepts children.

                            + * In other words, a node that accepts children. * - *

                            Use nextSibling to specify the child node + *

                            Use {@code nextSibling} to specify the child node * where the result nodes should be inserted before. - * If nextSibling is not a sibling of node, - * then an IllegalArgumentException is thrown. - * If node is null and nextSibling is not null, - * then an IllegalArgumentException is thrown. - * If nextSibling is null, + * If {@code nextSibling} is not a sibling of {@code node}, + * then an {@code IllegalArgumentException} is thrown. + * If {@code node} is {@code null} and {@code nextSibling} is not {@code null}, + * then an {@code IllegalArgumentException} is thrown. + * If {@code nextSibling} is {@code null}, * then the behavior is the same as calling {@link #DOMResult(Node node)}, - * i.e. append the result nodes as the last child of the specified node.

                            + * i.e. append the result nodes as the last child of the specified {@code node}. * - *

                            systemId will be set to null.

                            + *

                            {@code systemId} will be set to {@code null}. * * @param node The DOM node that will contain the result tree. * @param nextSibling The child node where the result nodes should be inserted before. * - * @throws IllegalArgumentException If nextSibling is not a sibling of node or - * node is null and nextSibling - * is not null. + * @throws IllegalArgumentException If {@code nextSibling} is not a sibling of {@code node} or + * {@code node} is {@code null} and {@code nextSibling} + * is not {@code null}. * * @since 1.5 */ @@ -151,33 +155,35 @@ public class DOMResult implements Result { } /** - *

                            Use a DOM node to create a new output target specifying the child node where the result nodes should be inserted before and - * the specified System ID.

                            + * Use a DOM node to create a new output target specifying the child + * node where the result nodes should be inserted before and + * the specified System ID. * - *

                            In practice, node and nextSibling should be + *

                            In practice, {@code node} and {@code nextSibling} should be * a {@link org.w3c.dom.Document} node, * a {@link org.w3c.dom.DocumentFragment} node, or a * {@link org.w3c.dom.Element} node. - * In other words, a node that accepts children.

                            + * In other words, a node that accepts children. * - *

                            Use nextSibling to specify the child node + *

                            Use {@code nextSibling} to specify the child node * where the result nodes should be inserted before. - * If nextSibling is not a sibling of node, - * then an IllegalArgumentException is thrown. - * If node is null and nextSibling is not null, - * then an IllegalArgumentException is thrown. - * If nextSibling is null, + * If {@code nextSibling} is not a sibling of {@code node}, + * then an {@code IllegalArgumentException} is thrown. + * If {@code node} is {@code null} and {@code nextSibling} is not {@code null}, + * then an {@code IllegalArgumentException} is thrown. + * If {@code nextSibling} is {@code null}, * then the behavior is the same as calling {@link #DOMResult(Node node, String systemId)}, - * i.e. append the result nodes as the last child of the specified node and use the specified System ID.

                            + * i.e. append the result nodes as the last child of the specified + * node and use the specified System ID. * * @param node The DOM node that will contain the result tree. * @param nextSibling The child node where the result nodes should be inserted before. * @param systemId The system identifier which may be used in association with this node. * - * @throws IllegalArgumentException If nextSibling is not a - * sibling of node or - * node is null and nextSibling - * is not null. + * @throws IllegalArgumentException If {@code nextSibling} is not a + * sibling of {@code node} or + * {@code node} is {@code null} and {@code nextSibling} + * is not {@code null}. * * @since 1.5 */ @@ -202,27 +208,27 @@ public class DOMResult implements Result { } /** - *

                            Set the node that will contain the result DOM tree.

                            + * Set the node that will contain the result DOM tree. * *

                            In practice, the node should be * a {@link org.w3c.dom.Document} node, * a {@link org.w3c.dom.DocumentFragment} node, or * a {@link org.w3c.dom.Element} node. - * In other words, a node that accepts children.

                            + * In other words, a node that accepts children. * - *

                            An IllegalStateException is thrown if - * nextSibling is not null and - * node is not a parent of nextSibling. - * An IllegalStateException is thrown if node is null and - * nextSibling is not null.

                            + *

                            An {@code IllegalStateException} is thrown if + * {@code nextSibling} is not {@code null} and + * {@code node} is not a parent of {@code nextSibling}. + * An {@code IllegalStateException} is thrown if {@code node} is {@code null} and + * {@code nextSibling} is not {@code null}. * * @param node The node to which the transformation will be appended. * - * @throws IllegalStateException If nextSibling is not - * null and - * nextSibling is not a child of node or - * node is null and - * nextSibling is not null. + * @throws IllegalStateException If {@code nextSibling} is not + * {@code null} and + * {@code nextSibling} is not a child of {@code node} or + * {@code node} is {@code null} and + * {@code nextSibling} is not {@code null}. */ public void setNode(Node node) { // does the corrent parent/child relationship exist? @@ -242,7 +248,7 @@ public class DOMResult implements Result { } /** - *

                            Get the node that will contain the result DOM tree.

                            + * Get the node that will contain the result DOM tree. * *

                            If no node was set via * {@link #DOMResult(Node node)}, @@ -251,7 +257,7 @@ public class DOMResult implements Result { * {@link #DOMResult(Node node, Node nextSibling, String systemId)} or * {@link #setNode(Node node)}, * then the node will be set by the transformation, and may be obtained from this method once the transformation is complete. - * Calling this method before the transformation will return null.

                            + * Calling this method before the transformation will return {@code null}. * * @return The node to which the transformation will be appended. */ @@ -260,24 +266,24 @@ public class DOMResult implements Result { } /** - *

                            Set the child node before which the result nodes will be inserted.

                            + * Set the child node before which the result nodes will be inserted. * - *

                            Use nextSibling to specify the child node + *

                            Use {@code nextSibling} to specify the child node * before which the result nodes should be inserted. - * If nextSibling is not a descendant of node, - * then an IllegalArgumentException is thrown. - * If node is null and nextSibling is not null, - * then an IllegalStateException is thrown. - * If nextSibling is null, + * If {@code nextSibling} is not a descendant of {@code node}, + * then an {@code IllegalArgumentException} is thrown. + * If {@code node} is {@code null} and {@code nextSibling} is not {@code null}, + * then an {@code IllegalStateException} is thrown. + * If {@code nextSibling} is {@code null}, * then the behavior is the same as calling {@link #DOMResult(Node node)}, - * i.e. append the result nodes as the last child of the specified node.

                            + * i.e. append the result nodes as the last child of the specified {@code node}. * * @param nextSibling The child node before which the result nodes will be inserted. * - * @throws IllegalArgumentException If nextSibling is not a - * descendant of node. - * @throws IllegalStateException If node is null - * and nextSibling is not null. + * @throws IllegalArgumentException If {@code nextSibling} is not a + * descendant of {@code node}. + * @throws IllegalStateException If {@code node} is {@code null} + * and {@code nextSibling} is not {@code null}. * * @since 1.5 */ @@ -300,13 +306,13 @@ public class DOMResult implements Result { } /** - *

                            Get the child node before which the result nodes will be inserted.

                            + * Get the child node before which the result nodes will be inserted. * *

                            If no node was set via * {@link #DOMResult(Node node, Node nextSibling)}, * {@link #DOMResult(Node node, Node nextSibling, String systemId)} or * {@link #setNextSibling(Node nextSibling)}, - * then null will be returned.

                            + * then {@code null} will be returned. * * @return The child node before which the result nodes will be inserted. * @@ -317,7 +323,7 @@ public class DOMResult implements Result { } /** - *

                            Set the systemId that may be used in association with the node.

                            + * Set the systemId that may be used in association with the node. * * @param systemId The system identifier as a URI string. */ @@ -326,13 +332,13 @@ public class DOMResult implements Result { } /** - *

                            Get the System Identifier.

                            + * Get the System Identifier. * *

                            If no System ID was set via * {@link #DOMResult(Node node, String systemId)}, * {@link #DOMResult(Node node, Node nextSibling, String systemId)} or * {@link #setSystemId(String systemId)}, - * then null will be returned.

                            + * then {@code null} will be returned. * * @return The system identifier. */ @@ -345,19 +351,19 @@ public class DOMResult implements Result { ////////////////////////////////////////////////////////////////////// /** - *

                            The node to which the transformation will be appended.

                            + * The node to which the transformation will be appended. */ private Node node = null; /** - *

                            The child node before which the result nodes will be inserted.

                            + * The child node before which the result nodes will be inserted. * * @since 1.5 */ private Node nextSibling = null; /** - *

                            The System ID that may be used in association with the node.

                            + * The System ID that may be used in association with the node. */ private String systemId = null; } diff --git a/jaxp/src/java.xml/share/classes/javax/xml/transform/stax/package.html b/jaxp/src/java.xml/share/classes/javax/xml/transform/stax/package.html index d07e037142b..abdd5ecd846 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/transform/stax/package.html +++ b/jaxp/src/java.xml/share/classes/javax/xml/transform/stax/package.html @@ -65,9 +65,6 @@ questions.
                          • @see XMLEventReader
                          -

                          - @since 1.6 -

                          - + @since 1.6 diff --git a/jaxp/src/java.xml/share/classes/javax/xml/validation/SchemaFactory.java b/jaxp/src/java.xml/share/classes/javax/xml/validation/SchemaFactory.java index ad7e61f9a7f..8152b675c7e 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/validation/SchemaFactory.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/validation/SchemaFactory.java @@ -37,7 +37,7 @@ import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; /** - * Factory that creates {@link Schema} objects. Entry-point to + * Factory that creates {@link Schema} objects. Entry-point to * the validation API. * *

                          @@ -49,12 +49,12 @@ import org.xml.sax.SAXParseException; * it is the application's responsibility to ensure that at most * one thread is using a {@link SchemaFactory} object at any * given moment. Implementations are encouraged to mark methods - * as synchronized to protect themselves from broken clients. + * as {@code synchronized} to protect themselves from broken clients. * *

                          * {@link SchemaFactory} is not re-entrant. While one of the - * newSchema methods is being invoked, applications - * may not attempt to recursively invoke the newSchema method, + * {@code newSchema} methods is being invoked, applications + * may not attempt to recursively invoke the {@code newSchema} method, * even from the same thread. * *

                          Schema Language

                          @@ -92,11 +92,11 @@ import org.xml.sax.SAXParseException; * * * - * + * * * * - * + * * * * @@ -112,24 +112,24 @@ public abstract class SchemaFactory { private static SecuritySupport ss = new SecuritySupport(); /** - *

                          Constructor for derived classes.

                          + * Constructor for derived classes. * - *

                          The constructor does nothing.

                          + *

                          The constructor does nothing. * *

                          Derived classes must create {@link SchemaFactory} objects that have - * null {@link ErrorHandler} and - * null {@link LSResourceResolver}.

                          + * {@code null} {@link ErrorHandler} and + * {@code null} {@link LSResourceResolver}. */ protected SchemaFactory() { } /** - *

                          Lookup an implementation of the SchemaFactory that supports the specified - * schema language and return it.

                          + * Lookup an implementation of the {@code SchemaFactory} that supports the specified + * schema language and return it. * - *

                          To find a SchemaFactory object for a given schema language, + *

                          To find a {@code SchemaFactory} object for a given schema language, * this method looks the following places in the following order - * where "the class loader" refers to the context class loader:

                          + * where "the class loader" refers to the context class loader: *
                            *
                          1. *

                            @@ -178,9 +178,9 @@ public abstract class SchemaFactory { *

                          2. *
                          3. *

                            - * Platform default SchemaFactory is located + * Platform default {@code SchemaFactory} is located * in a implementation specific way. There must be a platform default - * SchemaFactory for W3C XML Schema. + * {@code SchemaFactory} for W3C XML Schema. *

                          4. *
                          * @@ -201,12 +201,12 @@ public abstract class SchemaFactory { * the list of available * schema languages for the possible values. * - * @return New instance of a SchemaFactory + * @return New instance of a {@code SchemaFactory} * * @throws IllegalArgumentException * If no implementation of the schema language is available. * @throws NullPointerException - * If the schemaLanguage parameter is null. + * If the {@code schemaLanguage} parameter is null. * @throws SchemaFactoryConfigurationError * If a configuration error is encountered. * @@ -233,42 +233,42 @@ public abstract class SchemaFactory { } /** - *

                          Obtain a new instance of a SchemaFactory from class name. SchemaFactory + * Obtain a new instance of a {@code SchemaFactory} from class name. {@code SchemaFactory} * is returned if specified factory class name supports the specified schema language. * This function is useful when there are multiple providers in the classpath. * It gives more control to the application as it can specify which provider - * should be loaded.

                          + * should be loaded. * *

                          Tip for Trouble-shooting

                          - *

                          Setting the jaxp.debug system property will cause + *

                          Setting the {@code jaxp.debug} system property will cause * this method to print a lot of debug messages - * to System.err about what it is doing and where it is looking at.

                          + * to {@code System.err} about what it is doing and where it is looking at. * - *

                          If you have problems try:

                          + *

                          If you have problems try: *

                                * java -Djaxp.debug=1 YourProgram ....
                                * 
                          * * @param schemaLanguage Specifies the schema language which the returned - * SchemaFactory will understand. See + * {@code SchemaFactory} will understand. See * the list of available * schema languages for the possible values. * - * @param factoryClassName fully qualified factory class name that provides implementation of javax.xml.validation.SchemaFactory. + * @param factoryClassName fully qualified factory class name that provides implementation of {@code javax.xml.validation.SchemaFactory}. * - * @param classLoader ClassLoader used to load the factory class. If null - * current Thread's context classLoader is used to load the factory class. + * @param classLoader {@code ClassLoader} used to load the factory class. If {@code null} + * current {@code Thread}'s context classLoader is used to load the factory class. * - * @return New instance of a SchemaFactory + * @return New instance of a {@code SchemaFactory} * * @throws IllegalArgumentException - * if factoryClassName is null, or + * if {@code factoryClassName} is {@code null}, or * the factory class cannot be loaded, instantiated or doesn't - * support the schema language specified in schemLanguage + * support the schema language specified in {@code schemLanguage} * parameter. * * @throws NullPointerException - * If the schemaLanguage parameter is null. + * If the {@code schemaLanguage} parameter is null. * * @see #newInstance(String schemaLanguage) * @@ -299,16 +299,16 @@ public abstract class SchemaFactory { } /** - *

                          Is specified schema supported by this SchemaFactory?

                          + * Is specified schema supported by this {@code SchemaFactory}? * - * @param schemaLanguage Specifies the schema language which the returned SchemaFactory will understand. - * schemaLanguage must specify a valid schema language. + * @param schemaLanguage Specifies the schema language which the returned {@code SchemaFactory} will understand. + * {@code schemaLanguage} must specify a valid schema language. * - * @return true if SchemaFactory supports schemaLanguage, else false. + * @return {@code true} if {@code SchemaFactory} supports {@code schemaLanguage}, else {@code false}. * - * @throws NullPointerException If schemaLanguage is null. - * @throws IllegalArgumentException If schemaLanguage.length() == 0 - * or schemaLanguage does not specify a valid schema language. + * @throws NullPointerException If {@code schemaLanguage} is {@code null}. + * @throws IllegalArgumentException If {@code schemaLanguage.length() == 0} + * or {@code schemaLanguage} does not specify a valid schema language. */ public abstract boolean isSchemaLanguageSupported(String schemaLanguage); @@ -320,7 +320,7 @@ public abstract class SchemaFactory { * temporarily be unable to return its value. * *

                          Implementors are free (and encouraged) to invent their own features, - * using names built on their own URIs.

                          + * using names built on their own URIs. * * @param name The feature name, which is a non-null fully-qualified URI. * @@ -331,7 +331,7 @@ public abstract class SchemaFactory { * @throws SAXNotSupportedException When the * {@link SchemaFactory} recognizes the feature name but * cannot determine its value at this time. - * @throws NullPointerException If name is null. + * @throws NullPointerException If {@code name} is {@code null}. * * @see #setFeature(String, boolean) */ @@ -345,38 +345,37 @@ public abstract class SchemaFactory { } /** - *

                          Set a feature for this SchemaFactory, + * Set a feature for this {@code SchemaFactory}, * {@link Schema}s created by this factory, and by extension, * {@link Validator}s and {@link ValidatorHandler}s created by * those {@link Schema}s. - *

                          * *

                          Implementors and developers should pay particular attention * to how the special {@link Schema} object returned by {@link * #newSchema()} is processed. In some cases, for example, when the - * SchemaFactory and the class actually loading the + * {@code SchemaFactory} and the class actually loading the * schema come from different implementations, it may not be possible - * for SchemaFactory features to be inherited automatically. + * for {@code SchemaFactory} features to be inherited automatically. * Developers should * make sure that features, such as secure processing, are explicitly - * set in both places.

                          + * set in both places. * *

                          The feature name is any fully-qualified URI. It is * possible for a {@link SchemaFactory} to expose a feature value but - * to be unable to change the current value.

                          + * to be unable to change the current value. * *

                          All implementations are required to support the {@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} feature. - * When the feature is:

                          + * When the feature is: *
                            *
                          • - * true: the implementation will limit XML processing to conform to implementation limits. + * {@code true}: the implementation will limit XML processing to conform to implementation limits. * Examples include entity expansion limits and XML Schema constructs that would consume large amounts of resources. * If XML processing is limited for security reasons, it will be reported via a call to the registered * {@link ErrorHandler#fatalError(SAXParseException exception)}. * See {@link #setErrorHandler(ErrorHandler errorHandler)}. *
                          • *
                          • - * false: the implementation will processing XML according to the XML specifications without + * {@code false}: the implementation will processing XML according to the XML specifications without * regard to possible implementation limits. *
                          • *
                          @@ -389,7 +388,7 @@ public abstract class SchemaFactory { * @throws SAXNotSupportedException When the * {@link SchemaFactory} recognizes the feature name but * cannot set the requested value. - * @throws NullPointerException If name is null. + * @throws NullPointerException If {@code name} is {@code null}. * * @see #getFeature(String) */ @@ -405,15 +404,15 @@ public abstract class SchemaFactory { /** * Set the value of a property. * - *

                          The property name is any fully-qualified URI. It is + *

                          The property name is any fully-qualified URI. It is * possible for a {@link SchemaFactory} to recognize a property name but - * to be unable to change the current value.

                          + * to be unable to change the current value. * *

                          * All implementations that implement JAXP 1.5 or newer are required to * support the {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_DTD} and * {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_SCHEMA} properties. - *

                          + * *
                            *
                          • *

                            Access to external DTDs in Schema files is restricted to the protocols @@ -421,14 +420,14 @@ public abstract class SchemaFactory { * If access is denied during the creation of new Schema due to the restriction * of this property, {@link org.xml.sax.SAXException} will be thrown by the * {@link #newSchema(Source)} or {@link #newSchema(File)} - * or {@link #newSchema(URL)} or or {@link #newSchema(Source[])} method.

                            + * or {@link #newSchema(URL)} or {@link #newSchema(Source[])} method. * *

                            Access to external DTDs in xml source files is restricted to the protocols * specified by the {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_DTD} property. * If access is denied during validation due to the restriction * of this property, {@link org.xml.sax.SAXException} will be thrown by the * {@link javax.xml.validation.Validator#validate(Source)} or - * {@link javax.xml.validation.Validator#validate(Source, Result)} method.

                            + * {@link javax.xml.validation.Validator#validate(Source, Result)} method. * *

                            Access to external reference set by the schemaLocation attribute is * restricted to the protocols specified by the @@ -436,7 +435,7 @@ public abstract class SchemaFactory { * If access is denied during validation due to the restriction of this property, * {@link org.xml.sax.SAXException} will be thrown by the * {@link javax.xml.validation.Validator#validate(Source)} or - * {@link javax.xml.validation.Validator#validate(Source, Result)} method.

                            + * {@link javax.xml.validation.Validator#validate(Source, Result)} method. * *

                            Access to external reference set by the Import * and Include element is restricted to the protocols specified by the @@ -444,7 +443,7 @@ public abstract class SchemaFactory { * If access is denied during the creation of new Schema due to the restriction * of this property, {@link org.xml.sax.SAXException} will be thrown by the * {@link #newSchema(Source)} or {@link #newSchema(File)} - * or {@link #newSchema(URL)} or {@link #newSchema(Source[])} method.

                            + * or {@link #newSchema(URL)} or {@link #newSchema(Source[])} method. *
                          • *
                          * @@ -456,7 +455,7 @@ public abstract class SchemaFactory { * @throws SAXNotSupportedException When the * {@link SchemaFactory} recognizes the property name but * cannot set the requested value. - * @throws NullPointerException If name is null. + * @throws NullPointerException If {@code name} is {@code null}. */ public void setProperty(String name, Object object) throws SAXNotRecognizedException, SAXNotSupportedException { @@ -472,13 +471,13 @@ public abstract class SchemaFactory { * *

                          The property name is any fully-qualified URI. It is * possible for a {@link SchemaFactory} to recognize a property name but - * temporarily be unable to return its value.

                          + * temporarily be unable to return its value. * *

                          {@link SchemaFactory}s are not required to recognize any specific - * property names.

                          + * property names. * *

                          Implementors are free (and encouraged) to invent their own properties, - * using names built on their own URIs.

                          + * using names built on their own URIs. * * @param name The property name, which is a non-null fully-qualified URI. * @@ -489,7 +488,7 @@ public abstract class SchemaFactory { * @throws SAXNotSupportedException When the * XMLReader recognizes the property name but * cannot determine its value at this time. - * @throws NullPointerException If name is null. + * @throws NullPointerException If {@code name} is {@code null}. * * @see #setProperty(String, Object) */ @@ -504,7 +503,7 @@ public abstract class SchemaFactory { /** * Sets the {@link ErrorHandler} to receive errors encountered - * during the newSchema method invocation. + * during the {@code newSchema} method invocation. * *

                          * Error handler can be used to customize the error handling process @@ -521,7 +520,7 @@ public abstract class SchemaFactory { *

                          * If any {@link Throwable} (or instances of its derived classes) * is thrown from an {@link ErrorHandler}, - * the caller of the newSchema method will be thrown + * the caller of the {@code newSchema} method will be thrown * the same {@link Throwable} object. * *

                          @@ -557,7 +556,7 @@ public abstract class SchemaFactory { * {@link ValidatorHandler}s that are created from this {@link SchemaFactory}. * * @param errorHandler A new error handler to be set. - * This parameter can be null. + * This parameter can be {@code null}. */ public abstract void setErrorHandler(ErrorHandler errorHandler); @@ -583,7 +582,7 @@ public abstract class SchemaFactory { * when it needs to locate external resources while parsing schemas, * although exactly what constitutes "locating external resources" is * up to each schema language. For example, for W3C XML Schema, - * this includes files <include>d or <import>ed, + * this includes files {@code }d or {@code }ed, * and DTD referenced from schema files, etc. * *

                          @@ -607,7 +606,7 @@ public abstract class SchemaFactory { * If a {@link LSResourceResolver} throws a {@link RuntimeException} * (or instances of its derived classes), * then the {@link SchemaFactory} will abort the parsing and - * the caller of the newSchema method will receive + * the caller of the {@code newSchema} method will receive * the same {@link RuntimeException}. * *

                          @@ -635,48 +634,48 @@ public abstract class SchemaFactory { public abstract LSResourceResolver getResourceResolver(); /** - *

                          Parses the specified source as a schema and returns it as a schema.

                          + * Parses the specified source as a schema and returns it as a schema. * - *

                          This is a convenience method for {@link #newSchema(Source[] schemas)}.

                          + *

                          This is a convenience method for {@link #newSchema(Source[] schemas)}. * * @param schema Source that represents a schema. * - * @return New Schema from parsing schema. + * @return New {@code Schema} from parsing {@code schema}. * * @throws SAXException If a SAX error occurs during parsing. - * @throws NullPointerException if schema is null. + * @throws NullPointerException if {@code schema} is null. */ public Schema newSchema(Source schema) throws SAXException { return newSchema(new Source[]{schema}); } /** - *

                          Parses the specified File as a schema and returns it as a Schema.

                          + * Parses the specified {@code File} as a schema and returns it as a {@code Schema}. * - *

                          This is a convenience method for {@link #newSchema(Source schema)}.

                          + *

                          This is a convenience method for {@link #newSchema(Source schema)}. * * @param schema File that represents a schema. * - * @return New Schema from parsing schema. + * @return New {@code Schema} from parsing {@code schema}. * * @throws SAXException If a SAX error occurs during parsing. - * @throws NullPointerException if schema is null. + * @throws NullPointerException if {@code schema} is null. */ public Schema newSchema(File schema) throws SAXException { return newSchema(new StreamSource(schema)); } /** - *

                          Parses the specified URL as a schema and returns it as a Schema.

                          + * Parses the specified {@code URL} as a schema and returns it as a {@code Schema}. * - *

                          This is a convenience method for {@link #newSchema(Source schema)}.

                          + *

                          This is a convenience method for {@link #newSchema(Source schema)}. * - * @param schema URL that represents a schema. + * @param schema {@code URL} that represents a schema. * - * @return New Schema from parsing schema. + * @return New {@code Schema} from parsing {@code schema}. * * @throws SAXException If a SAX error occurs during parsing. - * @throws NullPointerException if schema is null. + * @throws NullPointerException if {@code schema} is null. */ public Schema newSchema(URL schema) throws SAXException { return newSchema(new StreamSource(schema.toExternalForm())); @@ -710,7 +709,7 @@ public abstract class SchemaFactory { * regard. While a processor should be consistent in its treatment of * JAXP schema sources and XML Schema imports, the behaviour between * JAXP-compliant parsers may vary; in particular, parsers may choose - * to ignore all but the first <import> for a given namespace, + * to ignore all but the first {@code } for a given namespace, * regardless of information provided in schemaLocation. * *

                          @@ -721,7 +720,7 @@ public abstract class SchemaFactory { *

                          RELAX NG

                          * *

                          For RELAX NG, this method must throw {@link UnsupportedOperationException} - * if schemas.length!=1. + * if {@code schemas.length!=1}. * * * @param schemas @@ -748,7 +747,7 @@ public abstract class SchemaFactory { * When an {@link ErrorHandler} is set, errors are reported to * there first. See {@link #setErrorHandler(ErrorHandler)}. * @throws NullPointerException - * If the schemas parameter itself is null or + * If the {@code schemas} parameter itself is null or * any item in the array is null. * @throws IllegalArgumentException * If any item in the array is not recognized by this method. @@ -765,7 +764,7 @@ public abstract class SchemaFactory { * is created. * *

                          Also, implementations are allowed to use implementation-specific - * property/feature to alter the semantics of this method.

                          + * property/feature to alter the semantics of this method. * *

                          Implementors and developers should pay particular attention * to how the features set on this {@link SchemaFactory} are @@ -776,7 +775,7 @@ public abstract class SchemaFactory { * for {@link SchemaFactory} features to be inherited automatically. * Developers should * make sure that features, such as secure processing, are explicitly - * set in both places.

                          + * set in both places. * *

                          W3C XML Schema 1.0

                          *

                          diff --git a/jaxp/src/java.xml/share/classes/javax/xml/validation/Validator.java b/jaxp/src/java.xml/share/classes/javax/xml/validation/Validator.java index 4983e03982d..bd746b40e84 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/validation/Validator.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/validation/Validator.java @@ -37,16 +37,15 @@ import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; /** - *

                          A processor that checks an XML document against {@link Schema}.

                          + * A processor that checks an XML document against {@link Schema}. * *

                          * A validator object is not thread-safe and not reentrant. * In other words, it is the application's responsibility to make * sure that one {@link Validator} object is not used from - * more than one thread at any given time, and while the validate + * more than one thread at any given time, and while the {@code validate} * method is invoked, applications may not recursively call - * the validate method. - *

                          + * the {@code validate} method. * * * @author Kohsuke Kawaguchi @@ -57,27 +56,28 @@ public abstract class Validator { /** * Constructor for derived classes. * - *

                          The constructor does nothing.

                          + *

                          The constructor does nothing. * *

                          Derived classes must create {@link Validator} objects that have - * null {@link ErrorHandler} and - * null {@link LSResourceResolver}. - *

                          + * {@code null} {@link ErrorHandler} and + * {@code null} {@link LSResourceResolver}. */ protected Validator() { } /** - *

                          Reset this Validator to its original configuration.

                          + * Reset this {@code Validator} to its original configuration. * - *

                          Validator is reset to the same state as when it was created with + *

                          {@code Validator} is reset to the same state as when it was created with * {@link Schema#newValidator()}. - * reset() is designed to allow the reuse of existing Validators - * thus saving resources associated with the creation of new Validators.

                          + * {@code reset()} is designed to allow the reuse of existing {@code Validator}s + * thus saving resources associated with the creation of new {@code Validator}s. * - *

                          The reset Validator is not guaranteed to have the same {@link LSResourceResolver} or {@link ErrorHandler} - * Objects, e.g. {@link Object#equals(Object obj)}. It is guaranteed to have a functionally equal - * LSResourceResolver and ErrorHandler.

                          + *

                          The reset {@code Validator} is not guaranteed to have + * the same {@link LSResourceResolver} or {@link ErrorHandler} + * {@code Object}s, e.g. {@link Object#equals(Object obj)}. + * It is guaranteed to have a functionally equal + * {@code LSResourceResolver} and {@code ErrorHandler}. */ public abstract void reset(); @@ -86,7 +86,7 @@ public abstract class Validator { * *

                          This is just a convenience method for * {@link #validate(Source source, Result result)} - * with result of null.

                          + * with {@code result} of {@code null}. * * @param source * XML to be validated. Must be an XML document or @@ -97,7 +97,7 @@ public abstract class Validator { * or throw an IllegalArgumentException. * * @throws IllegalArgumentException - * If the Source + * If the {@code Source} * is an XML artifact that the implementation cannot * validate (for example, a processing instruction). * @@ -113,8 +113,8 @@ public abstract class Validator { * {@link IOException}. * * - * @throws NullPointerException If source is - * null. + * @throws NullPointerException If {@code source} is + * {@code null}. * * @see #validate(Source source, Result result) */ @@ -125,16 +125,16 @@ public abstract class Validator { } /** - *

                          Validates the specified input and send the augmented validation - * result to the specified output.

                          + * Validates the specified input and send the augmented validation + * result to the specified output. * *

                          This method places the following restrictions on the types of - * the {@link Source}/{@link Result} accepted.

                          + * the {@link Source}/{@link Result} accepted. * *
                          XML Namespaces, javax.xml.stream.isRepairingNamespaces and write method behaviourXML Namespaces, {@code javax.xml.stream.isRepairingNamespaces} and write method behaviour
                          Method isRepairingNamespaces == trueisRepairingNamespaces == false{@code isRepairingNamespaces} == true{@code isRepairingNamespaces} == false
                          writeAttribute(namespaceURI, localName, value){@code writeAttribute(namespaceURI, localName, value)} * @@ -79,19 +79,19 @@ import javax.xml.namespace.NamespaceContext; * * - * XMLStreamException + * {@code XMLStreamException} *
                          writeAttribute(prefix, namespaceURI, localName, value){@code writeAttribute(prefix, namespaceURI, localName, value)} * - * bound to same prefix:
                          - * prefix:localName="value" [1]
                          - *
                          - * bound to different prefix:
                          + * bound to same prefix:
                          + * prefix:localName="value" [1]
                          + *
                          + * bound to different prefix:
                          * xmlns:{generated}="namespaceURI" {generated}:localName="value" *
                          @@ -101,11 +101,11 @@ import javax.xml.namespace.NamespaceContext; * * * - * bound to same prefix:
                          - * prefix:localName="value" [1][2]
                          - *
                          - * bound to different prefix:
                          - * XMLStreamException[2] + * bound to same prefix:
                          + * prefix:localName="value" [1][2]
                          + *
                          + * bound to different prefix:
                          + * {@code XMLStreamException}[2] *
                          * @@ -114,58 +114,58 @@ import javax.xml.namespace.NamespaceContext; *
                          writeStartElement(namespaceURI, localName)
                          - *
                          - * writeEmptyElement(namespaceURI, localName)
                          {@code writeStartElement(namespaceURI, localName)}
                          + *
                          + * {@code writeEmptyElement(namespaceURI, localName)}
                          * - * <prefix:localName> [1] + * {@code [1] * * - * <{generated}:localName xmlns:{generated}="namespaceURI"> + * {@code <{generated}:localName xmlns:{generated}="namespaceURI">} * * - * <prefix:localName> [1] + * {@code prefix:localName>} [1] * * - * XMLStreamException + * {@code XMLStreamException} *
                          writeStartElement(prefix, localName, namespaceURI)
                          - *
                          - * writeEmptyElement(prefix, localName, namespaceURI)
                          {@code writeStartElement(prefix, localName, namespaceURI)}
                          + *
                          + * {@code writeEmptyElement(prefix, localName, namespaceURI)}
                          * - * bound to same prefix:
                          - * <prefix:localName> [1]
                          - *
                          - * bound to different prefix:
                          - * <{generated}:localName xmlns:{generated}="namespaceURI"> + * bound to same prefix:
                          + * {@code [1]
                          + *
                          + * bound to different prefix:
                          + * {@code <{generated}:localName xmlns:{generated}="namespaceURI">} *
                          * - * <prefix:localName xmlns:prefix="namespaceURI"> [4] + * {@code [4] * * - * bound to same prefix:
                          - * <prefix:localName> [1]
                          - *
                          - * bound to different prefix:
                          - * XMLStreamException + * bound to same prefix:
                          + * {@code [1]
                          + *
                          + * bound to different prefix:
                          + * {@code XMLStreamException} *
                          * - * <prefix:localName>  + * {@code }  *
                          {@link javax.xml.XMLConstants#W3C_XML_SCHEMA_NS_URI} ("http://www.w3.org/2001/XMLSchema"){@link javax.xml.XMLConstants#W3C_XML_SCHEMA_NS_URI} ("{@code http://www.w3.org/2001/XMLSchema}")W3C XML Schema 1.0
                          {@link javax.xml.XMLConstants#RELAXNG_NS_URI} ("http://relaxng.org/ns/structure/1.0"){@link javax.xml.XMLConstants#RELAXNG_NS_URI} ("{@code http://relaxng.org/ns/structure/1.0}")RELAX NG 1.0
                          * * - * + * * * * @@ -146,7 +146,7 @@ public abstract class Validator { * * * - * + * * * * @@ -155,44 +155,44 @@ public abstract class Validator { * * * - * - * - * + * + * + * * * * - * + * * - * - * + * + * * * * - * - * + * + * * - * + * * * * - * - * - * + * + * + * * * * *
                          Source / Result Accepted{@code Source} / {@code Result} Accepted
                          null{@code null}OKOKOK
                          {@link javax.xml.transform.stream.StreamResult}OKIllegalArgumentExceptionIllegalArgumentExceptionIllegalArgumentException{@code IllegalArgumentException}{@code IllegalArgumentException}{@code IllegalArgumentException}
                          {@link javax.xml.transform.sax.SAXResult}IllegalArgumentException{@code IllegalArgumentException}OKIllegalArgumentExceptionIllegalArgumentException{@code IllegalArgumentException}{@code IllegalArgumentException}
                          {@link javax.xml.transform.dom.DOMResult}IllegalArgumentExceptionIllegalArgumentException{@code IllegalArgumentException}{@code IllegalArgumentException}OKIllegalArgumentException{@code IllegalArgumentException}
                          {@link javax.xml.transform.stax.StAXResult}IllegalArgumentExceptionIllegalArgumentExceptionIllegalArgumentException{@code IllegalArgumentException}{@code IllegalArgumentException}{@code IllegalArgumentException}OK
                          * - *

                          To validate one Source into another kind of - * Result, use the identity transformer (see - * {@link javax.xml.transform.TransformerFactory#newTransformer()}).

                          + *

                          To validate one {@code Source} into another kind of + * {@code Result}, use the identity transformer (see + * {@link javax.xml.transform.TransformerFactory#newTransformer()}). * *

                          Errors found during the validation is sent to the specified - * {@link ErrorHandler}.

                          + * {@link ErrorHandler}. * *

                          If a document is valid, or if a document contains some errors - * but none of them were fatal and the ErrorHandler didn't - * throw any exception, then the method returns normally.

                          + * but none of them were fatal and the {@code ErrorHandler} didn't + * throw any exception, then the method returns normally. * * @param source * XML to be validated. Must be an XML document or @@ -203,34 +203,34 @@ public abstract class Validator { * or throw an IllegalArgumentException. * * @param result - * The Result object that receives (possibly augmented) + * The {@code Result} object that receives (possibly augmented) * XML. This parameter can be null if the caller is not interested * in it. * - * Note that when a DOMResult is used, + * Note that when a {@code DOMResult} is used, * a validator might just pass the same DOM node from - * DOMSource to DOMResult - * (in which case source.getNode()==result.getNode()), + * {@code DOMSource} to {@code DOMResult} + * (in which case {@code source.getNode()==result.getNode()}), * it might copy the entire DOM tree, or it might alter the * node given by the source. * * @throws IllegalArgumentException - * If the Result type doesn't match the - * Source type of if the Source + * If the {@code Result} type doesn't match the + * {@code Source} type of if the {@code Source} * is an XML artifact that the implementation cannot * validate (for example, a processing instruction). * @throws SAXException - * If the ErrorHandler throws a - * SAXException or - * if a fatal error is found and the ErrorHandler returns + * If the {@code ErrorHandler} throws a + * {@code SAXException} or + * if a fatal error is found and the {@code ErrorHandler} returns * normally. * @throws IOException * If the validator is processing a - * SAXSource and the + * {@code SAXSource} and the * underlying {@link org.xml.sax.XMLReader} throws an - * IOException. + * {@code IOException}. * @throws NullPointerException - * If the source parameter is null. + * If the {@code source} parameter is {@code null}. * * @see #validate(Source source) */ @@ -239,7 +239,7 @@ public abstract class Validator { /** * Sets the {@link ErrorHandler} to receive errors encountered - * during the validate method invocation. + * during the {@code validate} method invocation. * *

                          * Error handler can be used to customize the error handling process @@ -255,7 +255,7 @@ public abstract class Validator { * *

                          * If any {@link Throwable} is thrown from an {@link ErrorHandler}, - * the caller of the validate method will be thrown + * the caller of the {@code validate} method will be thrown * the same {@link Throwable} object. * *

                          @@ -329,7 +329,7 @@ public abstract class Validator { * If a {@link LSResourceResolver} throws a {@link RuntimeException} * (or instances of its derived classes), * then the {@link Validator} will abort the parsing and - * the caller of the validate method will receive + * the caller of the {@code validate} method will receive * the same {@link RuntimeException}. * *

                          @@ -366,7 +366,7 @@ public abstract class Validator { * contexts, such as before, during, or after a validation. * *

                          Implementors are free (and encouraged) to invent their own features, - * using names built on their own URIs.

                          + * using names built on their own URIs. * * @param name The feature name, which is a non-null fully-qualified URI. * @@ -398,14 +398,14 @@ public abstract class Validator { *

                          * Feature can be used to control the way a {@link Validator} * parses schemas, although {@link Validator}s are not required - * to recognize any specific feature names.

                          + * to recognize any specific feature names. * *

                          The feature name is any fully-qualified URI. It is * possible for a {@link Validator} to expose a feature value but * to be unable to change the current value. * Some feature values may be immutable or mutable only * in specific contexts, such as before, during, or after - * a validation.

                          + * a validation. * * @param name The feature name, which is a non-null fully-qualified URI. * @param value The requested value of the feature (true or false). @@ -438,27 +438,27 @@ public abstract class Validator { * to be unable to change the current value. * Some property values may be immutable or mutable only * in specific contexts, such as before, during, or after - * a validation.

                          + * a validation. * *

                          * All implementations that implement JAXP 1.5 or newer are required to * support the {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_DTD} and * {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_SCHEMA} properties. - *

                          + * *
                            *
                          • *

                            Access to external DTDs in source or Schema file is restricted to * the protocols specified by the {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_DTD} * property. If access is denied during validation due to the restriction * of this property, {@link org.xml.sax.SAXException} will be thrown by the - * {@link #validate(Source)} method.

                            + * {@link #validate(Source)} method. * *

                            Access to external reference set by the schemaLocation attribute is * restricted to the protocols specified by the * {@link javax.xml.XMLConstants#ACCESS_EXTERNAL_SCHEMA} property. * If access is denied during validation due to the restriction of this property, * {@link org.xml.sax.SAXException} will be thrown by the - * {@link #validate(Source)} method.

                            + * {@link #validate(Source)} method. *
                          • *
                          * @@ -490,13 +490,13 @@ public abstract class Validator { * possible for a {@link Validator} to recognize a property name but * temporarily be unable to return its value. * Some property values may be available only in specific - * contexts, such as before, during, or after a validation.

                          + * contexts, such as before, during, or after a validation. * *

                          {@link Validator}s are not required to recognize any specific - * property names.

                          + * property names. * *

                          Implementors are free (and encouraged) to invent their own properties, - * using names built on their own URIs.

                          + * using names built on their own URIs. * * @param name The property name, which is a non-null fully-qualified URI. * diff --git a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPath.java b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPath.java index 6e77e23e441..9d63bf24637 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPath.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPath.java @@ -32,7 +32,7 @@ import org.xml.sax.InputSource; /** * {@code XPath} provides access to the XPath evaluation environment and expressions. * - * + * * * * @@ -90,7 +90,6 @@ import org.xml.sax.InputSource; * more than one thread at any given time, and while the {@code evaluate} * method is invoked, applications may not recursively call * the {@code evaluate} method. - *

                          * * @author Norman Walsh * @author Jeff Suttor @@ -462,7 +461,6 @@ public interface XPath { *

                           {@code
                                *     evaluateExpression(expression, item, XPathEvaluationResult.class);
                                * }
                          - *

                          * * @implSpec * The default implementation in the XPath API is equivalent to: diff --git a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathEvaluationResult.java b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathEvaluationResult.java index 745473975e5..84d1f399e08 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathEvaluationResult.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathEvaluationResult.java @@ -32,7 +32,6 @@ import org.w3c.dom.Node; * evaluation of an XPath expression within the context of a particular node. * The evaluation of an XPath expression can result in various result types as * defined in XML Path Language (XPath) Version 1.0. - *

                          * * @param the object type returned by the XPath evaluation. * @see XML Path Language (XPath) Version @@ -121,7 +120,7 @@ public interface XPathEvaluationResult { public XPathResultType type(); /** - * Returns the value of the result as the type <T> specified for the class. + * Returns the value of the result as the type {@code } specified for the class. * * @return The value of the result. */ diff --git a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathException.java b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathException.java index ee680287cae..dadeeb95892 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathException.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathException.java @@ -33,7 +33,7 @@ import java.io.ObjectStreamField; import java.io.InvalidClassException; /** - * XPathException represents a generic XPath exception.

                          + * {@code XPathException} represents a generic XPath exception. * * @author Norman Walsh * @author Jeff Suttor @@ -46,23 +46,23 @@ public class XPathException extends Exception { }; /** - *

                          Stream Unique Identifier.

                          + * Stream Unique Identifier. */ private static final long serialVersionUID = -1837080260374986980L; /** - *

                          Constructs a new XPathException - * with the specified detail message.

                          + * Constructs a new {@code XPathException} + * with the specified detail {@code message}. * - *

                          The cause is not initialized.

                          + *

                          The {@code cause} is not initialized. * - *

                          If message is null, - * then a NullPointerException is thrown.

                          + *

                          If {@code message} is {@code null}, + * then a {@code NullPointerException} is thrown. * * @param message The detail message. * - * @throws NullPointerException When message is - * null. + * @throws NullPointerException When {@code message} is + * {@code null}. */ public XPathException(String message) { super(message); @@ -72,15 +72,15 @@ public class XPathException extends Exception { } /** - *

                          Constructs a new XPathException - * with the specified cause.

                          + * Constructs a new {@code XPathException} + * with the specified {@code cause}. * - *

                          If cause is null, - * then a NullPointerException is thrown.

                          + *

                          If {@code cause} is {@code null}, + * then a {@code NullPointerException} is thrown. * * @param cause The cause. * - * @throws NullPointerException if cause is null. + * @throws NullPointerException if {@code cause} is {@code null}. */ public XPathException(Throwable cause) { super(cause); @@ -90,7 +90,7 @@ public class XPathException extends Exception { } /** - *

                          Get the cause of this XPathException.

                          + * Get the cause of this XPathException. * * @return Cause of this XPathException. */ @@ -103,7 +103,7 @@ public class XPathException extends Exception { * The cause is got from the parent class. * * @param out stream used for serialization. - * @throws IOException thrown by ObjectOutputStream + * @throws IOException thrown by {@code ObjectOutputStream} * */ private void writeObject(ObjectOutputStream out) @@ -120,8 +120,8 @@ public class XPathException extends Exception { * done before. * * @param in stream used for deserialization - * @throws IOException thrown by ObjectInputStream - * @throws ClassNotFoundException thrown by ObjectInputStream + * @throws IOException thrown by {@code ObjectInputStream} + * @throws ClassNotFoundException thrown by {@code ObjectInputStream} */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException @@ -139,9 +139,9 @@ public class XPathException extends Exception { } /** - *

                          Print stack trace to specified PrintStream.

                          + * Print stack trace to specified {@code PrintStream}. * - * @param s Print stack trace to this PrintStream. + * @param s Print stack trace to this {@code PrintStream}. */ public void printStackTrace(java.io.PrintStream s) { if (getCause() != null) { @@ -153,16 +153,16 @@ public class XPathException extends Exception { } /** - *

                          Print stack trace to System.err.

                          + * Print stack trace to {@code System.err}. */ public void printStackTrace() { printStackTrace(System.err); } /** - *

                          Print stack trace to specified PrintWriter.

                          + * Print stack trace to specified {@code PrintWriter}. * - * @param s Print stack trace to this PrintWriter. + * @param s Print stack trace to this {@code PrintWriter}. */ public void printStackTrace(PrintWriter s) { diff --git a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathExpression.java b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathExpression.java index a7625ec1b87..f0464d6061a 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathExpression.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathExpression.java @@ -29,9 +29,9 @@ import javax.xml.namespace.QName; import org.xml.sax.InputSource; /** - *

                          {@code XPathExpression} provides access to compiled XPath expressions.

                          + * {@code XPathExpression} provides access to compiled XPath expressions. * - * + * *
                          * * @@ -54,7 +54,7 @@ import org.xml.sax.InputSource; * If the expression contains a variable reference, its value will be found through the {@link XPathVariableResolver}. * An {@link XPathExpressionException} is raised if the variable resolver is undefined or * the resolver returns {@code null} for the variable. - * The value of a variable must be immutable through the course of any single evaluation.

                          + * The value of a variable must be immutable through the course of any single evaluation. * * * @@ -62,7 +62,7 @@ import org.xml.sax.InputSource; * * * @@ -76,9 +76,10 @@ import org.xml.sax.InputSource; * * + * *
                          * If the expression contains a function reference, the function will be found through the {@link XPathFunctionResolver}. * An {@link XPathExpressionException} is raised if the function resolver is undefined or - * the function resolver returns {@code null} for the function.

                          + * the function resolver returns {@code null} for the function. *
                          * This result of evaluating an expression is converted to an instance of the desired return type. * Valid return types are defined in {@link XPathConstants}. - * Conversion to the return type follows XPath conversion rules.

                          + * Conversion to the return type follows XPath conversion rules. *
                          * *

                          An XPath expression is not thread-safe and not reentrant. @@ -87,7 +88,6 @@ import org.xml.sax.InputSource; * more than one thread at any given time, and while the {@code evaluate} * method is invoked, applications may not recursively call * the {@code evaluate} method. - *

                          * * @author Norman Walsh * @author Jeff Suttor @@ -98,10 +98,10 @@ public interface XPathExpression { /** - *

                          Evaluate the compiled XPath expression in the specified context and return the result as the specified type.

                          + * Evaluate the compiled XPath expression in the specified context and return the result as the specified type. * *

                          See Evaluation of XPath Expressions for context item evaluation, - * variable, function and QName resolution and return type conversion.

                          + * variable, function and QName resolution and return type conversion. * *

                          * The parameter {@code item} represents the context the XPath expression @@ -126,13 +126,13 @@ public interface XPathExpression { throws XPathExpressionException; /** - *

                          Evaluate the compiled XPath expression in the specified context and return the result as a {@code String}.

                          + * Evaluate the compiled XPath expression in the specified context and return the result as a {@code String}. * *

                          This method calls {@link #evaluate(Object item, QName returnType)} with a {@code returnType} of - * {@link XPathConstants#STRING}.

                          + * {@link XPathConstants#STRING}. * *

                          See Evaluation of XPath Expressions for context item evaluation, - * variable, function and QName resolution and return type conversion.

                          + * variable, function and QName resolution and return type conversion. * *

                          * The parameter {@code item} represents the context the XPath expression @@ -153,20 +153,21 @@ public interface XPathExpression { throws XPathExpressionException; /** - *

                          Evaluate the compiled XPath expression in the context of the specified {@code InputSource} and return the result as the - * specified type.

                          + * Evaluate the compiled XPath expression in the context + * of the specified {@code InputSource} and return the result as the + * specified type. * *

                          This method builds a data model for the {@link InputSource} and calls - * {@link #evaluate(Object item, QName returnType)} on the resulting document object.

                          + * {@link #evaluate(Object item, QName returnType)} on the resulting document object. * *

                          See Evaluation of XPath Expressions for context item evaluation, - * variable, function and QName resolution and return type conversion.

                          + * variable, function and QName resolution and return type conversion. * *

                          If {@code returnType} is not one of the types defined in {@link XPathConstants}, - * then an {@code IllegalArgumentException} is thrown.

                          + * then an {@code IllegalArgumentException} is thrown. * *

                          If {@code source} or {@code returnType} is {@code null}, - * then a {@code NullPointerException} is thrown.

                          + * then a {@code NullPointerException} is thrown. * * @param source The {@code InputSource} of the document to evaluate over. * @param returnType The desired return type. @@ -182,16 +183,17 @@ public interface XPathExpression { throws XPathExpressionException; /** - *

                          Evaluate the compiled XPath expression in the context of the specified {@code InputSource} and return the result as a - * {@code String}.

                          + * Evaluate the compiled XPath expression in the context + * of the specified {@code InputSource} and return the result as a + * {@code String}. * *

                          This method calls {@link #evaluate(InputSource source, QName returnType)} with a {@code returnType} of - * {@link XPathConstants#STRING}.

                          + * {@link XPathConstants#STRING}. * *

                          See Evaluation of XPath Expressions for context item evaluation, - * variable, function and QName resolution and return type conversion.

                          + * variable, function and QName resolution and return type conversion. * - *

                          If {@code source} is {@code null}, then a {@code NullPointerException} is thrown.

                          + *

                          If {@code source} is {@code null}, then a {@code NullPointerException} is thrown. * * @param source The {@code InputSource} of the document to evaluate over. * @@ -351,7 +353,6 @@ public interface XPathExpression { *

                           {@code
                                *     evaluateExpression(source, XPathEvaluationResult.class);
                                * }
                          - *

                          * * @implSpec * The default implementation in the XPath API is equivalent to: diff --git a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathExpressionException.java b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathExpressionException.java index 02190781f96..aebcf94da86 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathExpressionException.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathExpressionException.java @@ -26,7 +26,7 @@ package javax.xml.xpath; /** - * XPathExpressionException represents an error in an XPath expression.

                          + * {@code XPathExpressionException} represents an error in an XPath expression. * * @author Norman Walsh * @author Jeff Suttor @@ -35,38 +35,38 @@ package javax.xml.xpath; public class XPathExpressionException extends XPathException { /** - *

                          Stream Unique Identifier.

                          + * Stream Unique Identifier. */ private static final long serialVersionUID = -1837080260374986980L; /** - *

                          Constructs a new XPathExpressionException - * with the specified detail message.

                          + * Constructs a new {@code XPathExpressionException} + * with the specified detail {@code message}. * - *

                          The cause is not initialized.

                          + *

                          The {@code cause} is not initialized. * - *

                          If message is null, - * then a NullPointerException is thrown.

                          + *

                          If {@code message} is {@code null}, + * then a {@code NullPointerException} is thrown. * * @param message The detail message. * - * @throws NullPointerException When message is - * null. + * @throws NullPointerException When {@code message} is + * {@code null}. */ public XPathExpressionException(String message) { super(message); } /** - *

                          Constructs a new XPathExpressionException - * with the specified cause.

                          + * Constructs a new {@code XPathExpressionException} + * with the specified {@code cause}. * - *

                          If cause is null, - * then a NullPointerException is thrown.

                          + *

                          If {@code cause} is {@code null}, + * then a {@code NullPointerException} is thrown. * * @param cause The cause. * - * @throws NullPointerException if cause is null. + * @throws NullPointerException if {@code cause} is {@code null}. */ public XPathExpressionException(Throwable cause) { super(cause); diff --git a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathFactoryConfigurationException.java b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathFactoryConfigurationException.java index cd3ebdf4917..6879508d34a 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathFactoryConfigurationException.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathFactoryConfigurationException.java @@ -26,7 +26,8 @@ package javax.xml.xpath; /** - * XPathFactoryConfigurationException represents a configuration error in a XPathFactory environment.

                          + * {@code XPathFactoryConfigurationException} represents + * a configuration error in a {@code XPathFactory} environment. * * @author Norman Walsh * @author Jeff Suttor @@ -35,37 +36,38 @@ package javax.xml.xpath; public class XPathFactoryConfigurationException extends XPathException { /** - *

                          Stream Unique Identifier.

                          + * Stream Unique Identifier. */ private static final long serialVersionUID = -1837080260374986980L; /** - *

                          Constructs a new XPathFactoryConfigurationException with the specified detail message.

                          + * Constructs a new {@code XPathFactoryConfigurationException} + * with the specified detail {@code message}. * - *

                          The cause is not initialized.

                          + *

                          The {@code cause} is not initialized. * - *

                          If message is null, - * then a NullPointerException is thrown.

                          + *

                          If {@code message} is {@code null}, + * then a {@code NullPointerException} is thrown. * * @param message The detail message. * - * @throws NullPointerException When message is - * null. + * @throws NullPointerException When {@code message} is + * {@code null}. */ public XPathFactoryConfigurationException(String message) { super(message); } /** - *

                          Constructs a new XPathFactoryConfigurationException - * with the specified cause.

                          + * Constructs a new {@code XPathFactoryConfigurationException} + * with the specified {@code cause}. * - *

                          If cause is null, - * then a NullPointerException is thrown.

                          + *

                          If {@code cause} is {@code null}, + * then a {@code NullPointerException} is thrown. * * @param cause The cause. * - * @throws NullPointerException if cause is null. + * @throws NullPointerException if {@code cause} is {@code null}. */ public XPathFactoryConfigurationException(Throwable cause) { super(cause); diff --git a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathFunctionException.java b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathFunctionException.java index 398fe7c38de..c086d87c897 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathFunctionException.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathFunctionException.java @@ -26,7 +26,7 @@ package javax.xml.xpath; /** - * XPathFunctionException represents an error with an XPath function.

                          + * {@code XPathFunctionException} represents an error with an XPath function. * * @author Norman Walsh * @author Jeff Suttor @@ -35,36 +35,36 @@ package javax.xml.xpath; public class XPathFunctionException extends XPathExpressionException { /** - *

                          Stream Unique Identifier.

                          + * Stream Unique Identifier. */ private static final long serialVersionUID = -1837080260374986980L; /** - *

                          Constructs a new XPathFunctionException with the specified detail message.

                          + * Constructs a new {@code XPathFunctionException} with the specified detail {@code message}. * - *

                          The cause is not initialized.

                          + *

                          The {@code cause} is not initialized. * - *

                          If message is null, - * then a NullPointerException is thrown.

                          + *

                          If {@code message} is {@code null}, + * then a {@code NullPointerException} is thrown. * * @param message The detail message. * - * @throws NullPointerException When message is - * null. + * @throws NullPointerException When {@code message} is + * {@code null}. */ public XPathFunctionException(String message) { super(message); } /** - *

                          Constructs a new XPathFunctionException with the specified cause.

                          + * Constructs a new {@code XPathFunctionException} with the specified {@code cause}. * - *

                          If cause is null, - * then a NullPointerException is thrown.

                          + *

                          If {@code cause} is {@code null}, + * then a {@code NullPointerException} is thrown. * * @param cause The cause. * - * @throws NullPointerException if cause is null. + * @throws NullPointerException if {@code cause} is {@code null}. */ public XPathFunctionException(Throwable cause) { super(cause); diff --git a/jaxp/src/java.xml/share/classes/javax/xml/xpath/package.html b/jaxp/src/java.xml/share/classes/javax/xml/xpath/package.html index af0d152bc58..585160a726e 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/xpath/package.html +++ b/jaxp/src/java.xml/share/classes/javax/xml/xpath/package.html @@ -282,7 +282,6 @@ It is an XML document tree represented as a hierarchy of nodes, a

                          5. Using the XPath API

                          Consider the following XML document: -

                           <widgets>
                          @@ -366,7 +365,6 @@ The XPath 1.0 Number data type is defined as a double. However, the XPath
                           specification also provides functions that returns Integer type. To facilitate
                           such operations, the XPath API allows Integer and Long to be used in 
                           {@code evaluateExpression} method such as the following code: 
                          -

                           int count = xpath.evaluate("count(/widgets/widget)", document, Integer.class);
                          diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/ranges/package.html b/jaxp/src/java.xml/share/classes/org/w3c/dom/ranges/package.html
                          index 012315bfd27..83a1a986ae5 100644
                          --- a/jaxp/src/java.xml/share/classes/org/w3c/dom/ranges/package.html
                          +++ b/jaxp/src/java.xml/share/classes/org/w3c/dom/ranges/package.html
                          @@ -21,11 +21,11 @@
                                 W3C IPR SOFTWARE NOTICE
                               
                               

                          - Copyright © 2000 World Wide Web - Consortium, (Massachusetts - Institute of Technology, Institut - National de Recherche en Informatique et en Automatique, Keio University). All Rights + Copyright © 2000 World Wide Web + Consortium, (Massachusetts + Institute of Technology, Institut + National de Recherche en Informatique et en Automatique, Keio University). All Rights Reserved.

                          @@ -66,25 +66,25 @@

                          1. - The full text of this NOTICE in a location viewable to users of the - redistributed or derivative work. + The full text of this NOTICE in a location viewable to users of the + redistributed or derivative work.
                          2. - Any pre-existing intellectual property disclaimers, notices, or terms - and conditions. If none exist, a short notice of the following form - (hypertext is preferred, text is permitted) should be used within the - body of any redistributed or derivative code: "Copyright © - [$date-of-software] World Wide Web - Consortium, (Massachusetts - Institute of Technology, Institut - National de Recherche en Informatique et en Automatique, Keio University). All Rights - Reserved. http://www.w3.org/Consortium/Legal/" + Any pre-existing intellectual property disclaimers, notices, or terms + and conditions. If none exist, a short notice of the following form + (hypertext is preferred, text is permitted) should be used within the + body of any redistributed or derivative code: "Copyright © + [$date-of-software] World Wide Web + Consortium, (Massachusetts + Institute of Technology, Institut + National de Recherche en Informatique et en Automatique, Keio University). All Rights + Reserved. http://www.w3.org/Consortium/Legal/"
                          3. - Notice of any changes or modifications to the W3C files, including the - date changes were made. (We recommend you provide URIs to the location - from which the code is derived.) + Notice of any changes or modifications to the W3C files, including the + date changes were made. (We recommend you provide URIs to the location + from which the code is derived.)

                          diff --git a/jaxp/src/java.xml/share/classes/org/xml/sax/AttributeList.java b/jaxp/src/java.xml/share/classes/org/xml/sax/AttributeList.java index 877155409c5..3b9f0f0f376 100644 --- a/jaxp/src/java.xml/share/classes/org/xml/sax/AttributeList.java +++ b/jaxp/src/java.xml/share/classes/org/xml/sax/AttributeList.java @@ -42,7 +42,7 @@ package org.xml.sax; * *

                          This is the original SAX1 interface for reporting an element's * attributes. Unlike the new {@link org.xml.sax.Attributes Attributes} - * interface, it does not support Namespace-related information.

                          + * interface, it does not support Namespace-related information. * *

                          When an attribute list is supplied as part of a * {@link org.xml.sax.DocumentHandler#startElement startElement} @@ -51,16 +51,16 @@ package org.xml.sax; * to the parser, the attribute list is invalid. To save a * persistent copy of the attribute list, use the SAX1 * {@link org.xml.sax.helpers.AttributeListImpl AttributeListImpl} - * helper class.

                          + * helper class. * *

                          An attribute list includes only attributes that have been - * specified or defaulted: #IMPLIED attributes will not be included.

                          + * specified or defaulted: #IMPLIED attributes will not be included. * *

                          There are two ways for the SAX application to obtain information * from the AttributeList. First, it can iterate through the entire - * list:

                          + * list: * - *
                          + * 
                          {@code
                            * public void startElement (String name, AttributeList atts) {
                            *   for (int i = 0; i < atts.getLength(); i++) {
                            *     String name = atts.getName(i);
                          @@ -69,13 +69,13 @@ package org.xml.sax;
                            *     [...]
                            *   }
                            * }
                          - * 
                          + * }
                          * *

                          (Note that the result of getLength() will be zero if there * are no attributes.) * *

                          As an alternative, the application can request the value or - * type of specific attributes:

                          + * type of specific attributes: * *
                            * public void startElement (String name, AttributeList atts) {
                          @@ -107,7 +107,7 @@ public interface AttributeList {
                                * 

                          The SAX parser may provide attributes in any * arbitrary order, regardless of the order in which they were * declared or specified. The number of attributes may be - * zero.

                          + * zero. * * @return The number of attributes in the list. */ @@ -120,10 +120,10 @@ public interface AttributeList { *

                          The names must be unique: the SAX parser shall not include the * same attribute twice. Attributes without values (those declared * #IMPLIED without a value specified in the start tag) will be - * omitted from the list.

                          + * omitted from the list. * *

                          If the attribute name has a namespace prefix, the prefix - * will still be attached.

                          + * will still be attached. * * @param i The index of the attribute in the list (starting at 0). * @return The name of the indexed attribute, or null @@ -138,15 +138,15 @@ public interface AttributeList { * *

                          The attribute type is one of the strings "CDATA", "ID", * "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", - * or "NOTATION" (always in upper case).

                          + * or "NOTATION" (always in upper case). * *

                          If the parser has not read a declaration for the attribute, * or if the parser does not report attribute types, then it must * return the value "CDATA" as stated in the XML 1.0 Recommentation - * (clause 3.3.3, "Attribute-Value Normalization").

                          + * (clause 3.3.3, "Attribute-Value Normalization"). * *

                          For an enumerated attribute that is not a notation, the - * parser will report the type as "NMTOKEN".

                          + * parser will report the type as "NMTOKEN". * * @param i The index of the attribute in the list (starting at 0). * @return The attribute type as a string, or @@ -162,7 +162,7 @@ public interface AttributeList { * *

                          If the attribute value is a list of tokens (IDREFS, * ENTITIES, or NMTOKENS), the tokens will be concatenated - * into a single string separated by whitespace.

                          + * into a single string separated by whitespace. * * @param i The index of the attribute in the list (starting at 0). * @return The attribute value as a string, or @@ -183,10 +183,10 @@ public interface AttributeList { * Return the type of an attribute in the list (by name). * *

                          The return value is the same as the return value for - * getType(int).

                          + * getType(int). * *

                          If the attribute name has a namespace prefix in the document, - * the application must include the prefix here.

                          + * the application must include the prefix here. * * @param name The name of the attribute. * @return The attribute type as a string, or null if no @@ -200,10 +200,10 @@ public interface AttributeList { * Return the value of an attribute in the list (by name). * *

                          The return value is the same as the return value for - * getValue(int).

                          + * getValue(int). * *

                          If the attribute name has a namespace prefix in the document, - * the application must include the prefix here.

                          + * the application must include the prefix here. * * @param name the name of the attribute to return * @return The attribute value as a string, or null if diff --git a/jaxp/src/java.xml/share/classes/org/xml/sax/ext/EntityResolver2.java b/jaxp/src/java.xml/share/classes/org/xml/sax/ext/EntityResolver2.java index 178adf08aa7..5c647d5a463 100644 --- a/jaxp/src/java.xml/share/classes/org/xml/sax/ext/EntityResolver2.java +++ b/jaxp/src/java.xml/share/classes/org/xml/sax/ext/EntityResolver2.java @@ -61,7 +61,6 @@ import org.xml.sax.SAXException; * recognized). If that flag is unrecognized, or its value is false, * or the resolver does not implement this interface, then only the * {@link EntityResolver} method will be used. - *

                          * *

                          That supports three categories of application that modify entity * resolution. Old Style applications won't know about this interface; @@ -76,7 +75,6 @@ import org.xml.sax.SAXException; * They will insist that feature flag have a value of "true", and the * EntityResolver2 implementation they provide might throw an exception * if the original SAX 1.0 style entity resolution method is invoked. - *

                          * * @see org.xml.sax.XMLReader#setEntityResolver * @@ -95,7 +93,7 @@ public interface EntityResolver2 extends EntityResolver * through the {@link LexicalHandler#startDTD startDTD()} method as if * the document text had originally included the external subset; * this callback is made before any internal subset data or errors - * are reported.

                          + * are reported. * *

                          This method can also be used with documents that have no DOCTYPE * declaration. When the root element is encountered, @@ -104,7 +102,7 @@ public interface EntityResolver2 extends EntityResolver * element is declared to be the root element, giving the effect of * splicing a DOCTYPE declaration at the end the prolog of a document * that could not otherwise be valid. The sequence of parser callbacks - * in that case logically resembles this:

                          + * in that case logically resembles this: * *
                                * ... comments and PIs from the prolog (as usual)
                          @@ -122,7 +120,7 @@ public interface EntityResolver2 extends EntityResolver
                                * {@link #resolveEntity resolveEntity()} to gain benefits such as use
                                * of local caches of DTD entities.  Also, this method will never be
                                * used by a (non-validating) processor that is not including external
                          -     * parameter entities. 

                          + * parameter entities. * *

                          Uses for this method include facilitating data validation when * interoperating with XML processors that would always require @@ -131,12 +129,11 @@ public interface EntityResolver2 extends EntityResolver * Non-validation motives include forcing documents to include DTDs so * that attributes are handled consistently. * For example, an XPath processor needs to know which attibutes have - * type "ID" before it can process a widely used type of reference.

                          + * type "ID" before it can process a widely used type of reference. * *

                          Warning: Returning an external subset modifies * the input document. By providing definitions for general entities, * it can make a malformed document appear to be well formed. - *

                          * * @param name Identifies the document root element. This name comes * from a DOCTYPE declaration (where available) or from the actual @@ -166,8 +163,8 @@ public interface EntityResolver2 extends EntityResolver * This method provides more flexibility than the {@link EntityResolver} * interface, supporting implementations of more complex catalogue * schemes such as the one defined by the OASIS XML Catalogs specification.

                          + * "http://www.oasis-open.org/committees/entity/spec-2001-08-06.html" + * >OASIS XML Catalogs specification. * *

                          Parsers configured to use this resolver method will call it * to determine the input source to use for any external entity @@ -176,13 +173,13 @@ public interface EntityResolver2 extends EntityResolver * by {@link #getExternalSubset getExternalSubset()}. * When a (non-validating) processor is configured not to include * a class of entities (parameter or general) through use of feature - * flags, this method is not invoked for such entities.

                          + * flags, this method is not invoked for such entities. * *

                          Note that the entity naming scheme used here is the same one * used in the {@link LexicalHandler}, or in the {@link - org.xml.sax.ContentHandler#skippedEntity - ContentHandler.skippedEntity()} - * method.

                          + * org.xml.sax.ContentHandler#skippedEntity + * ContentHandler.skippedEntity()} + * method. * * @param name Identifies the external entity being resolved. * Either "[dtd]" for the external subset, or a name starting @@ -196,7 +193,7 @@ public interface EntityResolver2 extends EntityResolver * are interpreted. This is always an absolute URI, unless it is * null (likely because the XMLReader was given an InputSource without * one). This URI is defined by the XML specification to be the one - * associated with the "<" starting the relevant declaration. + * associated with the "{@literal <}" starting the relevant declaration. * @param systemId The system identifier of the external entity * being referenced; either a relative or absolute URI. * This is never null when invoked by a SAX2 parser; only declared diff --git a/jaxp/src/java.xml/share/classes/org/xml/sax/helpers/XMLReaderFactory.java b/jaxp/src/java.xml/share/classes/org/xml/sax/helpers/XMLReaderFactory.java index f8d27363331..9635e4cf777 100644 --- a/jaxp/src/java.xml/share/classes/org/xml/sax/helpers/XMLReaderFactory.java +++ b/jaxp/src/java.xml/share/classes/org/xml/sax/helpers/XMLReaderFactory.java @@ -49,7 +49,7 @@ import org.xml.sax.SAXException; *
                          * *

                          This class contains static methods for creating an XML reader - * from an explicit class name, or based on runtime defaults:

                          + * from an explicit class name, or based on runtime defaults: * *
                            * try {
                          @@ -64,8 +64,8 @@ import org.xml.sax.SAXException;
                            * createXMLReader to handle cases where the external
                            * configuration mechanisms aren't set up.  That method should do its
                            * best to return a parser when one is in the class path, even when
                          - * nothing bound its class name to org.xml.sax.driver so
                          - * those configuration mechanisms would see it.

                          + * nothing bound its class name to {@code org.xml.sax.driver} so + * those configuration mechanisms would see it. * * @since 1.4, SAX 2.0 * @author David Megginson, David Brownell @@ -76,7 +76,7 @@ final public class XMLReaderFactory /** * Private constructor. * - *

                          This constructor prevents the class from being instantiated.

                          + *

                          This constructor prevents the class from being instantiated. */ private XMLReaderFactory () { @@ -91,9 +91,10 @@ final public class XMLReaderFactory * Attempt to create an XMLReader from system defaults. * In environments which can support it, the name of the XMLReader * class is determined by trying each these options in order, and - * using the first one which succeeds:

                            + * using the first one which succeeds: + *
                              * - *
                            • If the system property org.xml.sax.driver + *
                            • If the system property {@code org.xml.sax.driver} * has a value, that is used as an XMLReader class name.
                            • * *
                            • The JAR "Services API" is used to look for a class name @@ -107,14 +108,13 @@ final public class XMLReaderFactory *
                            • Finally, if {@link ParserFactory#makeParser()} can * return a system default SAX1 parser, that parser is wrapped in * a {@link ParserAdapter}. (This is a migration aid for SAX1 - * environments, where the org.xml.sax.parser system + * environments, where the {@code org.xml.sax.parser} system * property will often be usable.)
                            • - * *
                            * *

                            In environments such as small embedded systems, which can not * support that flexibility, other mechanisms to determine the default - * may be used.

                            + * may be used. * *

                            Note that many Java environments allow system properties to be * initialized on a command line. This means that in most cases @@ -122,7 +122,6 @@ final public class XMLReaderFactory * method will succeed, except when security policies intervene. * This will also maximize application portability to older SAX * environments, with less robust implementations of this method. - *

                            * * @return A new XMLReader. * @exception org.xml.sax.SAXException If no default XMLReader class @@ -204,11 +203,11 @@ final public class XMLReaderFactory * Attempt to create an XML reader from a class name. * *

                            Given a class name, this method attempts to load - * and instantiate the class as an XML reader.

                            + * and instantiate the class as an XML reader. * *

                            Note that this method will not be usable in environments where * the caller (perhaps an applet) is not permitted to load classes - * dynamically.

                            + * dynamically. * * @return A new XML reader. * @exception org.xml.sax.SAXException If the class cannot be diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSS2Properties.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSS2Properties.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSS2Properties.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSS2Properties.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSCharsetRule.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSCharsetRule.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSCharsetRule.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSCharsetRule.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSFontFaceRule.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSFontFaceRule.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSFontFaceRule.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSFontFaceRule.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSImportRule.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSImportRule.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSImportRule.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSImportRule.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSMediaRule.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSMediaRule.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSMediaRule.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSMediaRule.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSPageRule.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSPageRule.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSPageRule.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSPageRule.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSPrimitiveValue.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSPrimitiveValue.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSPrimitiveValue.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSPrimitiveValue.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSRule.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSRule.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSRule.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSRule.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSRuleList.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSRuleList.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSRuleList.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSRuleList.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSStyleDeclaration.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSStyleDeclaration.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSStyleDeclaration.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSStyleDeclaration.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSStyleRule.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSStyleRule.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSStyleRule.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSStyleRule.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSStyleSheet.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSStyleSheet.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSStyleSheet.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSStyleSheet.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSUnknownRule.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSUnknownRule.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSUnknownRule.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSUnknownRule.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSValue.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSValue.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSValue.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSValue.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSValueList.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSValueList.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/CSSValueList.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/CSSValueList.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/Counter.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/Counter.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/Counter.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/Counter.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/DOMImplementationCSS.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/DOMImplementationCSS.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/DOMImplementationCSS.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/DOMImplementationCSS.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/DocumentCSS.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/DocumentCSS.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/DocumentCSS.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/DocumentCSS.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/ElementCSSInlineStyle.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/ElementCSSInlineStyle.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/ElementCSSInlineStyle.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/ElementCSSInlineStyle.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/RGBColor.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/RGBColor.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/RGBColor.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/RGBColor.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/Rect.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/Rect.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/Rect.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/Rect.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/css/ViewCSS.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/ViewCSS.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/css/ViewCSS.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/css/ViewCSS.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLAnchorElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLAnchorElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLAnchorElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLAnchorElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLAppletElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLAppletElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLAppletElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLAppletElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLAreaElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLAreaElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLAreaElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLAreaElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLBRElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLBRElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLBRElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLBRElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLBaseElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLBaseElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLBaseElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLBaseElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLBaseFontElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLBaseFontElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLBaseFontElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLBaseFontElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLBodyElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLBodyElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLBodyElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLBodyElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLButtonElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLButtonElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLButtonElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLButtonElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLCollection.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLCollection.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLCollection.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLCollection.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLDListElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLDListElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLDListElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLDListElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLDOMImplementation.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLDOMImplementation.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLDOMImplementation.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLDOMImplementation.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLDirectoryElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLDirectoryElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLDirectoryElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLDirectoryElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLDivElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLDivElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLDivElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLDivElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLDocument.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLDocument.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLDocument.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLDocument.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLFieldSetElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLFieldSetElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLFieldSetElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLFieldSetElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLFontElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLFontElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLFontElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLFontElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLFormElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLFormElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLFormElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLFormElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLFrameElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLFrameElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLFrameElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLFrameElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLFrameSetElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLFrameSetElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLFrameSetElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLFrameSetElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLHRElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLHRElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLHRElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLHRElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLHeadElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLHeadElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLHeadElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLHeadElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLHeadingElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLHeadingElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLHeadingElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLHeadingElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLHtmlElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLHtmlElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLHtmlElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLHtmlElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLIFrameElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLIFrameElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLIFrameElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLIFrameElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLImageElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLImageElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLImageElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLImageElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLInputElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLInputElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLInputElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLInputElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLIsIndexElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLIsIndexElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLIsIndexElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLIsIndexElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLLIElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLLIElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLLIElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLLIElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLLabelElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLLabelElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLLabelElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLLabelElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLLegendElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLLegendElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLLegendElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLLegendElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLLinkElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLLinkElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLLinkElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLLinkElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLMapElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLMapElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLMapElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLMapElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLMenuElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLMenuElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLMenuElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLMenuElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLMetaElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLMetaElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLMetaElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLMetaElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLModElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLModElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLModElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLModElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLOListElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLOListElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLOListElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLOListElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLObjectElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLObjectElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLObjectElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLObjectElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLOptGroupElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLOptGroupElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLOptGroupElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLOptGroupElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLOptionElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLOptionElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLOptionElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLOptionElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLParagraphElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLParagraphElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLParagraphElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLParagraphElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLParamElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLParamElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLParamElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLParamElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLPreElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLPreElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLPreElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLPreElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLQuoteElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLQuoteElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLQuoteElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLQuoteElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLScriptElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLScriptElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLScriptElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLScriptElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLSelectElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLSelectElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLSelectElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLSelectElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLStyleElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLStyleElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLStyleElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLStyleElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTableCaptionElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTableCaptionElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTableCaptionElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTableCaptionElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTableCellElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTableCellElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTableCellElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTableCellElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTableColElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTableColElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTableColElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTableColElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTableElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTableElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTableElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTableElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTableRowElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTableRowElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTableRowElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTableRowElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTableSectionElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTableSectionElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTableSectionElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTableSectionElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTextAreaElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTextAreaElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTextAreaElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTextAreaElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTitleElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTitleElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLTitleElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLTitleElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLUListElement.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLUListElement.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/html/HTMLUListElement.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/html/HTMLUListElement.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/stylesheets/DocumentStyle.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/stylesheets/DocumentStyle.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/stylesheets/DocumentStyle.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/stylesheets/DocumentStyle.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/stylesheets/LinkStyle.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/stylesheets/LinkStyle.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/stylesheets/LinkStyle.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/stylesheets/LinkStyle.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/stylesheets/MediaList.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/stylesheets/MediaList.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/stylesheets/MediaList.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/stylesheets/MediaList.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/stylesheets/StyleSheet.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/stylesheets/StyleSheet.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/stylesheets/StyleSheet.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/stylesheets/StyleSheet.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/stylesheets/StyleSheetList.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/stylesheets/StyleSheetList.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/stylesheets/StyleSheetList.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/stylesheets/StyleSheetList.java diff --git a/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/COPYRIGHT.html b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/COPYRIGHT.html new file mode 100644 index 00000000000..c7e0e497a5f --- /dev/null +++ b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/COPYRIGHT.html @@ -0,0 +1,106 @@ + + + + + W3C IPR SOFTWARE NOTICE + + + +

                            + W3C IPR SOFTWARE NOTICE +

                            +

                            + Copyright © 2002 World Wide Web + Consortium, (Massachusetts + Institute of Technology, Institut + National de Recherche en Informatique et en Automatique, Keio University). All Rights + Reserved. +

                            +

                            + The DOM bindings are published under the W3C Software Copyright Notice + and License. The software license requires "Notice of any changes or + modifications to the W3C files, including the date changes were made." + Consequently, modified versions of the DOM bindings must document that + they do not conform to the W3C standard; in the case of the IDL + definitions, the pragma prefix can no longer be 'w3c.org'; in the case of + the Java language binding, the package names can no longer be in the + 'org.w3c' package. +

                            +

                            + Note: The original version of the W3C Software Copyright Notice + and License could be found at http://www.w3.org/Consortium/Legal/copyright-software-19980720 +

                            +

                            + Copyright © 1994-2002 World Wide Web + Consortium, (Massachusetts + Institute of Technology, Institut + National de Recherche en Informatique et en Automatique, Keio University). All Rights + Reserved. http://www.w3.org/Consortium/Legal/ +

                            +

                            + This W3C work (including software, documents, or other related items) is + being provided by the copyright holders under the following license. By + obtaining, using and/or copying this work, you (the licensee) agree that + you have read, understood, and will comply with the following terms and + conditions: +

                            +

                            + Permission to use, copy, and modify this software and its documentation, + with or without modification,  for any purpose and without fee or + royalty is hereby granted, provided that you include the following on ALL + copies of the software and documentation or portions thereof, including + modifications, that you make: +

                            +
                              +
                            1. + The full text of this NOTICE in a location viewable to users of the + redistributed or derivative work. +
                            2. +
                            3. + Any pre-existing intellectual property disclaimers, notices, or terms + and conditions. If none exist, a short notice of the following form + (hypertext is preferred, text is permitted) should be used within the + body of any redistributed or derivative code: "Copyright © + [$date-of-software] World Wide Web + Consortium, (Massachusetts + Institute of Technology, Institut + National de Recherche en Informatique et en Automatique, Keio University). All Rights + Reserved. http://www.w3.org/Consortium/Legal/" +
                            4. +
                            5. + Notice of any changes or modifications to the W3C files, including the + date changes were made. (We recommend you provide URIs to the location + from which the code is derived.) +
                            6. +
                            +

                            + THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT + HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS + FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR + DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, + TRADEMARKS OR OTHER RIGHTS. +

                            +

                            + COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR + CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR + DOCUMENTATION. +

                            +

                            + The name and trademarks of copyright holders may NOT be used in + advertising or publicity pertaining to the software without specific, + written prior permission. Title to copyright in this software and any + associated documentation will at all times remain with copyright + holders. +

                            + + diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/XPathEvaluator.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/XPathEvaluator.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/XPathEvaluator.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/XPathEvaluator.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/XPathException.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/XPathException.java similarity index 97% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/XPathException.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/XPathException.java index 75121d48025..2a13869df45 100644 --- a/jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/XPathException.java +++ b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/XPathException.java @@ -47,6 +47,8 @@ package org.w3c.dom.xpath; *

                            See also the Document Object Model (DOM) Level 3 XPath Specification. */ public class XPathException extends RuntimeException { + private static final long serialVersionUID = 3471034171575979943L; + public XPathException(short code, String message) { super(message); this.code = code; diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/XPathExpression.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/XPathExpression.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/XPathExpression.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/XPathExpression.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/XPathNSResolver.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/XPathNSResolver.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/XPathNSResolver.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/XPathNSResolver.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/XPathNamespace.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/XPathNamespace.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/XPathNamespace.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/XPathNamespace.java diff --git a/jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/XPathResult.java b/jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/XPathResult.java similarity index 100% rename from jaxp/src/java.xml/share/classes/org/w3c/dom/xpath/XPathResult.java rename to jaxp/src/jdk.xml.dom/share/classes/org/w3c/dom/xpath/XPathResult.java diff --git a/jaxp/test/Makefile b/jaxp/test/Makefile index 0a3acdafb7c..912f2b98406 100644 --- a/jaxp/test/Makefile +++ b/jaxp/test/Makefile @@ -262,8 +262,8 @@ ifdef CONCURRENCY EXTRA_JTREG_OPTIONS += -concurrency:$(CONCURRENCY) endif -# Default JTREG to run (win32 script works for everybody) -JTREG = $(JT_HOME)/win32/bin/jtreg +# Default JTREG to run +JTREG = $(JT_HOME)/bin/jtreg # run in agentvm mode JTREG_BASIC_OPTIONS += -agentvm # Only run automatic tests diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/AbstractCharacterDataTest.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/AbstractCharacterDataTest.java new file mode 100644 index 00000000000..c1ef1140136 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/AbstractCharacterDataTest.java @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.fail; +import static org.w3c.dom.DOMException.INDEX_SIZE_ERR; +import static org.w3c.dom.ptests.DOMTestUtil.DOMEXCEPTION_EXPECTED; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; + +import jaxp.library.JAXPFileBaseTest; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.w3c.dom.CharacterData; +import org.w3c.dom.DOMException; +import org.xml.sax.SAXException; + +/* + * @summary common test for the CharacterData Interface + */ +public abstract class AbstractCharacterDataTest extends JAXPFileBaseTest { + @DataProvider(name = "data-for-length") + public Object[][] getDataForTestLength() { + return new Object[][] { + { "", 0 }, + { "test", 4 } }; + } + + /* + * Verify getLength method works as the spec, for an empty string, should + * return zero + */ + @Test(dataProvider = "data-for-length") + public void testGetLength(String text, int length) throws Exception { + CharacterData cd = createCharacterData(text); + assertEquals(cd.getLength(), length); + + } + + /* + * Test appendData method and verify by getData method. + */ + @Test + public void testAppendData() throws Exception { + CharacterData cd = createCharacterData("DOM"); + cd.appendData("2"); + assertEquals(cd.getData(), "DOM2"); + + } + + @DataProvider(name = "data-for-delete") + public Object[][] getDataForTestDelete() { + return new Object[][] { + { "DOM", 2, 1, "DO" }, + { "DOM", 0, 2, "M" }, + { "DOM", 2, 3, "DO" } }; + } + + /* + * Verify deleteData method works as the spec. + */ + @Test(dataProvider = "data-for-delete") + public void testDeleteData(String text, int offset, int count, String result) throws Exception { + CharacterData cd = createCharacterData(text); + cd.deleteData(offset, count); + assertEquals(cd.getData(), result); + } + + @DataProvider(name = "data-for-replace") + public Object[][] getDataForTestReplace() { + return new Object[][] { + { "DOM", 0, 3, "SAX", "SAX" }, + { "DOM", 1, 1, "AA", "DAAM" }, + { "DOM", 1, 2, "A", "DA" }, + { "DOM", 2, 2, "SAX", "DOSAX" } }; + } + + /* + * Verify replaceData method works as the spec. + */ + @Test(dataProvider = "data-for-replace") + public void testReplaceData(String text, int offset, int count, String arg, String result) throws Exception { + CharacterData cd = createCharacterData(text); + cd.replaceData(offset, count, arg); + assertEquals(cd.getData(), result); + } + + @DataProvider(name = "data-for-replace-neg") + public Object[][] getDataForTestReplaceNeg() { + return new Object[][] { + { "DOM", -1, 3, "SAX" }, //offset if neg + { "DOM", 0, -1, "SAX" }, //count is neg + { "DOM", 4, 1, "SAX" } };//offset is greater than length + } + + /* + * Test for replaceData method: verifies that DOMException with + * INDEX_SIZE_ERR is thrown if offset or count is out of the bound. + */ + @Test(dataProvider = "data-for-replace-neg") + public void testReplaceDataNeg(String text, int offset, int count, String arg) throws Exception { + CharacterData cd = createCharacterData(text); + try { + cd.replaceData(offset, count, arg); + fail(DOMEXCEPTION_EXPECTED); + } catch (DOMException e) { + assertEquals(e.code, INDEX_SIZE_ERR); + } + } + + @DataProvider(name = "data-for-insert") + public Object[][] getDataForTestInsert() { + return new Object[][] { + { "DOM", 0, "SAX", "SAXDOM" }, + { "DOM", 3, "SAX", "DOMSAX" } }; + } + + /* + * Verify insertData method works as the spec. + */ + @Test(dataProvider = "data-for-insert") + public void testInsertData(String text, int offset, String arg, String result) throws Exception { + CharacterData cd = createCharacterData(text); + cd.insertData(offset, arg); + assertEquals(cd.getData(), result); + } + + @DataProvider(name = "data-for-insert-neg") + public Object[][] getDataForTestInsertNeg() { + return new Object[][] { + { "DOM", -1 }, //offset is neg + { "DOM", 4 } };//offset is greater than length + } + + /* + * Test for insertData method: verifies that DOMException with + * INDEX_SIZE_ERR is thrown if offset is out of the bound. + */ + @Test(dataProvider = "data-for-insert-neg") + public void testInsertDataNeg(String text, int offset) throws Exception { + CharacterData cd = createCharacterData(text); + try { + cd.insertData(offset, "TEST"); + fail(DOMEXCEPTION_EXPECTED); + } catch (DOMException e) { + assertEquals(e.code, INDEX_SIZE_ERR); + } + } + + /* + * Test setData method and verify by getData method. + */ + @Test + public void testSetData() throws Exception { + CharacterData cd = createCharacterData("DOM"); + cd.setData("SAX"); + assertEquals(cd.getData(), "SAX"); + } + + @DataProvider(name = "data-for-substring") + public Object[][] getDataForTestSubstring() { + return new Object[][] { + { "DOM Level 2", 0, 3, "DOM" }, + { "DOM", 0, 3, "DOM" }, + { "DOM", 2, 5, "M" } }; + } + + /* + * Verify substringData method works as the spec. + */ + @Test(dataProvider = "data-for-substring") + public void testSubstringData(String text, int offset, int count, String result) throws Exception { + CharacterData cd = createCharacterData(text); + String retStr = cd.substringData(offset, count); + assertEquals(retStr, result); + } + + @DataProvider(name = "data-for-substring-neg") + public Object[][] getDataForTestSubstringNeg() { + return new Object[][] { + { "DOM Level 2", -1, 3 }, //offset is neg + { "DOM", 0, -1 }, //count is neg + { "DOM", 3, 1 } }; //offset exceeds length + } + + /* + * Test for substringData method: verifies that DOMException with + * INDEX_SIZE_ERR is thrown if offset or count is out of the bound. + */ + @Test(dataProvider = "data-for-substring-neg") + public void testSubstringDataNeg(String text, int offset, int count) throws Exception { + CharacterData cd = createCharacterData(text); + try { + cd.substringData(offset, count); + fail(DOMEXCEPTION_EXPECTED); + } catch (DOMException e) { + assertEquals(e.code, INDEX_SIZE_ERR); + } + + } + + /* + * Return a concrete CharacterData instance. + */ + abstract protected CharacterData createCharacterData(String text) throws IOException, SAXException, ParserConfigurationException; + +} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/AttrTest.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/AttrTest.java new file mode 100644 index 00000000000..b166c307a81 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/AttrTest.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import static org.w3c.dom.ptests.DOMTestUtil.createDOM; +import jaxp.library.JAXPFileBaseTest; + +import org.testng.annotations.Test; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; + + +/* + * @summary Test for the Attr Interface + */ +public class AttrTest extends JAXPFileBaseTest { + /* + * Verify getName method against both existing Attr and new Attr. + */ + @Test + public void testGetName() throws Exception { + Document document = createDOM("Attr01.xml"); + //test a new created Attr + Attr attr = document.createAttribute("newAttribute"); + assertEquals(attr.getName(), "newAttribute"); + + //test a Attr loaded from xml file + Element elemNode = (Element) document.getElementsByTagName("book").item(1); + Attr attr2 = (Attr) elemNode.getAttributes().item(0); + assertEquals(attr2.getName(), "category1"); + } + + /* + * Verify getOwnerElement method against both existing Attr and new Attr. + */ + @Test + public void testGetOwnerElement() throws Exception { + Document document = createDOM("Attr01.xml"); + + //test Attr loaded from xml file + Element elemNode = (Element) document.getElementsByTagName("book").item(1); + NamedNodeMap nnMap = elemNode.getAttributes(); + for (int i = 0; i < nnMap.getLength(); i++) { + Attr attr = (Attr) nnMap.item(i); + assertEquals(attr.getOwnerElement().getNodeName(), "book"); + } + + //test an Attr without owner node + Attr attr = document.createAttribute("newAttribute"); + assertNull(attr.getOwnerElement()); + + } + + /* + * Verify getSpecified method works as the spec. + */ + @Test + public void testGetSpecified1() throws Exception { + Document document = createDOM("Attr01.xml"); + + Element elemNode = (Element) document.getElementsByTagName("book").item(1); + Attr attr = elemNode.getAttributeNode("category1"); + assertTrue(attr.getSpecified()); + + } + + /* + * In this xml file, the dtd has the value for the attrribute, but the xml + * element does not specify the value for the attrribute, as per the spec it + * should return false. + */ + @Test + public void testGetSpecified2() throws Exception { + + Document document = createDOM("Attr2.xml"); + Element elemNode = (Element) document.getElementsByTagName("Name").item(0); + Attr attr = elemNode.getAttributeNode("type"); + + assertFalse(attr.getSpecified()); + } + + /* + * Creating a new attribute, the owner element is null since the attribute + * has just been created, getSpecified should return true. + */ + @Test + public void testNewCreatedAttribute() throws Exception { + Document document = createDOM("Attr01.xml"); + Attr attr = document.createAttribute("newAttribute"); + assertTrue(attr.getSpecified()); + assertNull(attr.getOwnerElement()); + + } + + /* + * The xml file includes the dtd having the IMPLIED value for the attrribute + * and the xml element does not specify the value. As per the spec it should + * not be seen as a part of the structure model hence getAttributeNode + * rerurn null if the attribute is even found. + */ + @Test + public void testIMPLIEDAttribute() throws Exception { + Document document = createDOM("Attr3.xml"); + Element elemNode = (Element) document.getElementsByTagName("Name").item(0); + Attr attr = elemNode.getAttributeNode("type"); + assertNull(attr); + } + + /* + * Test setValue method and verify by getValue method. + */ + @Test + public void testSetValue() throws Exception { + Document document = createDOM("Attr01.xml"); + Attr attr = document.createAttribute("newAttribute"); + attr.setValue("newVal"); + assertEquals(attr.getValue(), "newVal"); + + } + +} diff --git a/jdk/test/jdk/lambda/MethodReferenceTestInstance.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/CommentTest.java similarity index 58% rename from jdk/test/jdk/lambda/MethodReferenceTestInstance.java rename to jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/CommentTest.java index f8bb048922a..daf585bf09b 100644 --- a/jdk/test/jdk/lambda/MethodReferenceTestInstance.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/CommentTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,42 +20,25 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ +package org.w3c.dom.ptests; -import org.testng.annotations.Test; +import static org.w3c.dom.ptests.DOMTestUtil.createNewDocument; -import static org.testng.Assert.assertEquals; +import java.io.IOException; -/** - * @author Robert Field +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.CharacterData; +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +/* + * @summary Test for Comment implementation returned by Document.createComment(String) */ - -class MethodReferenceTestInstance_E { - String xI(Integer i) { - return "ExI:" + i; +public class CommentTest extends AbstractCharacterDataTest { + @Override + protected CharacterData createCharacterData(String text) throws IOException, SAXException, ParserConfigurationException { + Document document = createNewDocument(); + return document.createComment(text); } } - -@Test -public class MethodReferenceTestInstance { - - interface SI { String m(Integer a); } - - String xI(Integer i) { - return "xI:" + i; - } - - public void testMethodReferenceInstance() { - SI q; - - q = this::xI; - assertEquals(q.m(55), "xI:55"); - } - - public void testMethodReferenceExternal() { - SI q; - - q = (new MethodReferenceTestInstance_E())::xI; - assertEquals(q.m(77), "ExI:77"); - } - -} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/DocumentTest.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/DocumentTest.java new file mode 100644 index 00000000000..90dd8cc64a8 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/DocumentTest.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI; +import static javax.xml.XMLConstants.XML_NS_URI; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.fail; +import static org.w3c.dom.DOMException.NAMESPACE_ERR; +import static org.w3c.dom.ptests.DOMTestUtil.DOMEXCEPTION_EXPECTED; +import static org.w3c.dom.ptests.DOMTestUtil.createDOMWithNS; +import static org.w3c.dom.ptests.DOMTestUtil.createNewDocument; +import jaxp.library.JAXPFileBaseTest; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.w3c.dom.Attr; +import org.w3c.dom.DOMException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +/* + * @summary Test createAttributeNS, getElementsByTagNameNS and createElementNS method of Document + */ +public class DocumentTest extends JAXPFileBaseTest { + + @DataProvider(name = "invalid-nsuri") + public Object[][] getInvalidNamespaceURI() { + return new Object[][] { + { " ", "xml:novel" }, //blank + { "hello", "xml:novel" }, //unqualified + { null, "xml:novel" }, //null + { "", "xmlns:novel" } };//empty + } + + /* + * Test for createAttributeNS method: verifies that DOMException is thrown + * if reserved prefixes are used with an arbitrary namespace name. + */ + @Test(dataProvider = "invalid-nsuri", expectedExceptions = DOMException.class) + public void testCreateAttributeNSNeg(String namespaceURI, String name) throws Exception { + Document document = createDOMWithNS("DocumentTest01.xml"); + document.createAttributeNS(namespaceURI, name); + } + + @DataProvider(name = "valid-nsuri") + public Object[][] getValidNamespaceURI() { + return new Object[][] { + { XML_NS_URI, "xml:novel" }, + { XMLNS_ATTRIBUTE_NS_URI, "xmlns:novel" }, + { "urn:BooksAreUs.org:BookInfo", "attributeNew"}, + { "urn:BooksAreUs.org:BookInfonew", "attributeNew"} }; + } + + /* + * Verify the Attr from createAttributeNS. + */ + @Test(dataProvider = "valid-nsuri") + public void testCreateAttributeNS(String namespaceURI, String name) throws Exception { + Document document = createDOMWithNS("DocumentTest01.xml"); + Attr attr = document.createAttributeNS(namespaceURI, name); + assertEquals(attr.getNamespaceURI(), namespaceURI); + assertEquals(attr.getName(), name); + } + + @DataProvider(name = "elementName") + public Object[][] getElementName() { + return new Object[][] { + { "author", 1 }, + { "b:author", 0 } }; + } + + /* + * Verify the NodeList from getElementsByTagNameNS. + */ + @Test(dataProvider = "elementName") + public void testGetElementsByTagNameNS(String localName, int number) throws Exception { + Document document = createDOMWithNS("DocumentTest01.xml"); + NodeList nodeList = document.getElementsByTagNameNS("urn:BooksAreUs.org:BookInfo", localName); + assertEquals(nodeList.getLength(), number); + } + + /* + * Test for createElementNS method: verifies that DOMException is thrown + * if reserved prefixes are used with an arbitrary namespace name. + */ + @Test(dataProvider = "invalid-nsuri") + public void testCreateElementNSNeg(String namespaceURI, String name) throws Exception { + Document document = createDOMWithNS("DocumentTest01.xml"); + try { + document.createElementNS(namespaceURI, name); + fail(DOMEXCEPTION_EXPECTED); + } catch (DOMException e) { + assertEquals(e.code, NAMESPACE_ERR); + } + } + + /* + * Test createElementNS method works as the spec. + */ + @Test + public void testCreateElementNS() throws Exception { + final String nsURI = "http://www.books.com"; + final String name = "b:novel"; + final String localName = "novel"; + Document document = createDOMWithNS("DocumentTest01.xml"); + Element element = document.createElementNS(nsURI, name); + assertEquals(element.getNamespaceURI(), nsURI); + assertEquals(element.getNodeName(), name); + assertEquals(element.getLocalName(), localName); + } + + /* + * Test createAttributeNS and then append it with setAttributeNode. + */ + @Test + public void testAddNewAttributeNode() throws Exception { + Document document = createDOMWithNS("DocumentTest01.xml"); + + NodeList nodeList = document.getElementsByTagNameNS("http://www.w3.org/TR/REC-html40", "body"); + NodeList childList = nodeList.item(0).getChildNodes(); + Element child = (Element) childList.item(1); + Attr a = document.createAttributeNS("urn:BooksAreUs.org:BookInfo", "attributeNew"); + child.setAttributeNode(a); + assertNotNull(child.getAttributeNodeNS("urn:BooksAreUs.org:BookInfo", "attributeNew")); + } + + /* + * Test createElementNS and then append it with appendChild. + */ + @Test + public void testAddNewElement() throws Exception { + Document document = createDOMWithNS("DocumentTest01.xml"); + + NodeList nodeList = document.getElementsByTagNameNS("http://www.w3.org/TR/REC-html40", "body"); + NodeList childList = nodeList.item(0).getChildNodes(); + Element child = (Element) childList.item(1); + Element elem = document.createElementNS("urn:BooksAreUs.org:BookInfonew", "newElement"); + assertNotNull(child.appendChild(elem)); + } + + /* + * Test createElement with unqualified xml name. + */ + @Test(expectedExceptions = DOMException.class) + public void testCreateElementNeg() throws Exception { + Document doc = createNewDocument(); + doc.createElement("!nc$%^*(!"); + } +} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/DocumentTypeTest.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/DocumentTypeTest.java new file mode 100644 index 00000000000..d260d1f7c8e --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/DocumentTypeTest.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static org.testng.Assert.assertEquals; +import static org.w3c.dom.ptests.DOMTestUtil.createDOM; +import jaxp.library.JAXPFileBaseTest; + +import org.testng.Assert; +import org.testng.annotations.Test; +import org.w3c.dom.DocumentType; +import org.w3c.dom.NamedNodeMap; + +/* + * @summary Test DocumentType + */ +public class DocumentTypeTest extends JAXPFileBaseTest { + + /* + * Test testGetEntities method, and verify the entity items. + */ + @Test + public void testGetEntities() throws Exception { + DocumentType documentType = createDOM("DocumentType01.xml").getDoctype(); + NamedNodeMap namedNodeMap = documentType.getEntities(); + // should return both external and internal. Parameter entities are not + // contained. Duplicates are discarded. + assertEquals(namedNodeMap.getLength(), 3); + assertEquals(namedNodeMap.item(0).getNodeName(), "author"); + assertEquals(namedNodeMap.item(1).getNodeName(), "test"); + assertEquals(namedNodeMap.item(2).getNodeName(), "writer"); + } + + /* + * Test getNotations method, and verify the notation items. + */ + @Test + public void testGetNotations() throws Exception { + DocumentType documentType = createDOM("DocumentType03.xml").getDoctype(); + NamedNodeMap nm = documentType.getNotations(); + assertEquals(nm.getLength(), 2); // should return 2 because the notation + // name is repeated and + // it considers only the first + // occurence + assertEquals(nm.item(0).getNodeName(), "gs"); + assertEquals(nm.item(1).getNodeName(), "name"); + } + + /* + * Test getName method. + */ + @Test + public void testGetName() throws Exception { + DocumentType documentType = createDOM("DocumentType03.xml").getDoctype(); + assertEquals(documentType.getName(), "note"); + } + + /* + * Test getSystemId and getPublicId method. + */ + @Test + public void testGetSystemId() throws Exception { + DocumentType documentType = createDOM("DocumentType05.xml").getDoctype(); + assertEquals(documentType.getSystemId(), "DocumentBuilderImpl02.dtd"); + Assert.assertNull(documentType.getPublicId()); + } + +} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/DomImplementationTest.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/DomImplementationTest.java new file mode 100644 index 00000000000..fb6ec4b5ea4 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/DomImplementationTest.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static org.testng.Assert.assertEquals; +import static org.w3c.dom.ptests.DOMTestUtil.createNewDocument; + +import javax.xml.parsers.ParserConfigurationException; + +import jaxp.library.JAXPBaseTest; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentType; + +/* + * @summary Test DomImplementation API + */ +public class DomImplementationTest extends JAXPBaseTest { + /* + * Test createDocument method with a namespace uri, qualified name and null + * for the doctype + */ + @Test + public void testCreateDocument() throws ParserConfigurationException { + final String nsURI = "http://www.document.com"; + final String name = "document:localName"; + DOMImplementation domImpl = getDOMImplementation(); + Document document = domImpl.createDocument(nsURI, name, null); + assertEquals(document.getDocumentElement().getNamespaceURI(), nsURI); + assertEquals(document.getDocumentElement().getNodeName(), name); + } + + /* + * Test createDocumentType method with name, public id and system id. + */ + @Test + public void testCreateDocumentType01() throws ParserConfigurationException { + final String name = "document:localName"; + final String publicId = "pubid"; + final String systemId = "sysid"; + + DOMImplementation domImpl = getDOMImplementation(); + DocumentType documentType = domImpl.createDocumentType(name, publicId, systemId); + verifyDocumentType(documentType, name, publicId, systemId); + } + + + /* + * Test createDocument method using a DocumentType, verify the document will + * take that Doctype. + */ + @Test + public void testCreateDocumentType02() throws ParserConfigurationException { + final String name = "document:localName"; + final String publicId = "-//W3C//DTD HTML 4.0 Transitional//EN"; + final String systemId = "http://www.w3.org/TR/REC-html40/loose.dtd"; + DOMImplementation domImpl = getDOMImplementation(); + + DocumentType documentType = domImpl.createDocumentType(name, publicId, systemId); + Document document = domImpl.createDocument("http://www.document.com", "document:localName", documentType); + verifyDocumentType(document.getDoctype(), name, publicId, systemId); + } + + @DataProvider(name = "feature-supported") + public Object[][] getFeatureSupportedList() throws ParserConfigurationException { + DOMImplementation impl = getDOMImplementation(); + return new Object[][] { + { impl, "XML", "2.0", true }, + { impl, "HTML", "2.0", false }, + { impl, "Views", "2.0", false }, + { impl, "StyleSheets", "2.0", false }, + { impl, "CSS", "2.0", false }, + { impl, "CSS2", "2.0", false }, + { impl, "Events", "2.0", true }, + { impl, "UIEvents", "2.0", false }, + { impl, "MouseEvents", "2.0", false }, + { impl, "HTMLEvents", "2.0", false }, + { impl, "Traversal", "2.0", true }, + { impl, "Range", "2.0", true }, + { impl, "Core", "2.0", true }, + { impl, "XML", "", true } }; + } + + + /* + * Verify DOMImplementation for feature supporting. + */ + @Test(dataProvider = "feature-supported") + public void testHasFeature(DOMImplementation impl, String feature, String version, boolean isSupported) { + assertEquals(impl.hasFeature(feature,version), isSupported); + } + + + private DOMImplementation getDOMImplementation() throws ParserConfigurationException { + return createNewDocument().getImplementation(); + } + + + private void verifyDocumentType(DocumentType documentType, String name, String publicId, String systemId) { + assertEquals(documentType.getPublicId(), publicId); + assertEquals(documentType.getSystemId(), systemId); + assertEquals(documentType.getName(), name); + } +} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/ElementTest.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/ElementTest.java new file mode 100644 index 00000000000..2e4841f438a --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/ElementTest.java @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static javax.xml.XMLConstants.XML_NS_URI; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; +import static org.w3c.dom.DOMException.INUSE_ATTRIBUTE_ERR; +import static org.w3c.dom.ptests.DOMTestUtil.DOMEXCEPTION_EXPECTED; +import static org.w3c.dom.ptests.DOMTestUtil.createDOM; +import static org.w3c.dom.ptests.DOMTestUtil.createDOMWithNS; +import static org.w3c.dom.ptests.DOMTestUtil.createNewDocument; + +import java.io.StringReader; + +import javax.xml.parsers.DocumentBuilderFactory; + +import jaxp.library.JAXPFileBaseTest; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.w3c.dom.Attr; +import org.w3c.dom.DOMException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +/* + * @summary Test for the methods of Element Interface + */ +public class ElementTest extends JAXPFileBaseTest { + @Test + public void testGetAttributeNS() throws Exception { + Document document = createDOMWithNS("ElementSample01.xml"); + Element elemNode = (Element) document.getElementsByTagName("book").item(0); + String s = elemNode.getAttributeNS("urn:BooksAreUs.org:BookInfo", "category"); + assertEquals(s, "research"); + } + + @Test + public void testGetAttributeNodeNS() throws Exception { + Document document = createDOMWithNS("ElementSample01.xml"); + Element elemNode = (Element) document.getElementsByTagName("book").item(0); + Attr attr = elemNode.getAttributeNodeNS("urn:BooksAreUs.org:BookInfo", "category"); + assertEquals(attr.getValue(), "research"); + + } + + /* + * Test getAttributeNode to get a Attr and then remove it successfully by + * removeAttributeNode. + */ + @Test + public void testRemoveAttributeNode() throws Exception { + Document document = createDOMWithNS("ElementSample01.xml"); + Element elemNode = (Element) document.getElementsByTagName("book").item(1); + Attr attr = elemNode.getAttributeNode("category1"); + assertEquals(attr.getValue(), "research"); + + assertEquals(elemNode.getTagName(), "book"); + elemNode.removeAttributeNode(attr); + assertEquals(elemNode.getAttribute("category1"), ""); + } + + /* + * Test removing an Attribute Node with removeAttributeNS(String + * namespaceURI, String localName). + */ + @Test + public void testRemoveAttributeNS() throws Exception { + final String nsURI = "urn:BooksAreUs.org:BookInfo"; + final String localName = "category"; + Document document = createDOMWithNS("ElementSample01.xml"); + Element elemNode = (Element) document.getElementsByTagName("book").item(0); + elemNode.removeAttributeNS(nsURI, localName); + + assertNull(elemNode.getAttributeNodeNS(nsURI, localName)); + } + + /* + * Test getFirstChild and getLastChild. + */ + @Test + public void testGetChild() throws Exception { + Document document = createDOMWithNS("ElementSample01.xml"); + Element elemNode = (Element) document.getElementsByTagName("b:aaa").item(0); + elemNode.normalize(); + Node firstChild = elemNode.getFirstChild(); + Node lastChild = elemNode.getLastChild(); + assertEquals(firstChild.getNodeValue(), "fjfjf"); + assertEquals(lastChild.getNodeValue(), "fjfjf"); + } + + /* + * Test setAttributeNode with an Attr from createAttribute. + */ + @Test + public void testSetAttributeNode() throws Exception { + final String attrName = "myAttr"; + final String attrValue = "attrValue"; + Document document = createDOM("ElementSample02.xml"); + Element elemNode = document.createElement("pricetag2"); + Attr myAttr = document.createAttribute(attrName); + myAttr.setValue(attrValue); + + assertNull(elemNode.setAttributeNode(myAttr)); + assertEquals(elemNode.getAttribute(attrName), attrValue); + } + + @DataProvider(name = "attribute") + public Object[][] getAttributeData() { + return new Object[][] { + { "thisisname", "thisisitsvalue" }, + { "style", "font-Family" } }; + } + + @Test(dataProvider = "attribute") + public void testSetAttribute(String name, String value) throws Exception { + Document document = createDOM("ElementSample02.xml"); + Element elemNode = document.createElement("pricetag2"); + elemNode.setAttribute(name, value); + assertEquals(elemNode.getAttribute(name), value); + } + + /* + * Negative test for setAttribute, null is not a valid name. + */ + @Test(expectedExceptions = DOMException.class) + public void testSetAttributeNeg() throws Exception { + Document document = createDOM("ElementSample02.xml"); + Element elemNode = document.createElement("pricetag2"); + elemNode.setAttribute(null, null); + } + + /* + * Test setAttributeNode, newAttr can't be an attribute of another Element + * object, must explicitly clone Attr nodes to re-use them in other + * elements. + */ + @Test + public void testDuplicateAttributeNode() throws Exception { + final String name = "testAttrName"; + final String value = "testAttrValue"; + Document document = createNewDocument(); + Attr attr = document.createAttribute(name); + attr.setValue(value); + + Element element1 = document.createElement("AFirstElement"); + element1.setAttributeNode(attr); + Element element2 = document.createElement("ASecondElement"); + Attr attr2 = (Attr) attr.cloneNode(true); + element2.setAttributeNode(attr2); + assertEquals(element1.getAttribute(name), element2.getAttribute(name)); + + Element element3 = document.createElement("AThirdElement"); + try { + element3.setAttributeNode(attr); + fail(DOMEXCEPTION_EXPECTED); + } catch (DOMException doe) { + assertEquals(doe.code, INUSE_ATTRIBUTE_ERR); + } + } + + /* + * If not setting the namsepace aware method of DocumentBuilderFactory to + * true, can't retrieve element by namespace and local name. + */ + @Test + public void testNamespaceAware() throws Exception { + Document document = createDOM("ElementSample02.xml"); + + NodeList nl = document.getElementsByTagNameNS("urn:BooksAreUs.org:BookInfo", "author"); + assertNull(nl.item(0)); + + nl = document.getDocumentElement().getElementsByTagNameNS("urn:BooksAreUs.org:BookInfo", "author"); + assertNull(nl.item(0)); + } + + @DataProvider(name = "nsattribute") + public Object[][] getNSAttributeData() { + return new Object[][] { + { "h:html", "html", "attrValue" }, + { "b:style", "style", "attrValue" } }; + } + + /* + * setAttributeNodeNS and verify it with getAttributeNS. + */ + @Test(dataProvider = "nsattribute") + public void testSetAttributeNodeNS(String qualifiedName, String localName, String value) throws Exception { + Document document = createDOM("ElementSample03.xml"); + Element elemNode = document.createElement("pricetag2"); + Attr myAttr = document.createAttributeNS(XML_NS_URI, qualifiedName); + myAttr.setValue(value); + assertNull(elemNode.setAttributeNodeNS(myAttr)); + assertEquals(elemNode.getAttributeNS(XML_NS_URI, localName), value); + } + + @Test + public void testHasAttributeNS() throws Exception { + Document document = createDOMWithNS("ElementSample04.xml"); + NodeList nodeList = document.getElementsByTagName("body"); + NodeList childList = nodeList.item(0).getChildNodes(); + Element child = (Element) childList.item(7); + assertTrue(child.hasAttributeNS("urn:BooksAreUs.org:BookInfo", "style")); + } + + @Test + public void testToString() throws Exception { + final String xml = + "" + + "" + + "" + + " \n" + + " " + + " " + + ""; + + Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml))); + Element root = doc.getDocumentElement(); + + assertEquals(root.toString(), "[datacenterlist: null]"); + } + +} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/EntityChildTest.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/EntityChildTest.java new file mode 100644 index 00000000000..099b7c1fc83 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/EntityChildTest.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static org.testng.Assert.assertEquals; +import static org.w3c.dom.ptests.DOMTestUtil.XML_DIR; + +import java.io.File; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import jaxp.library.JAXPFileBaseTest; + +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +/* + * @summary Test DOM Parser: parsing an xml file that contains external entities. + */ +public class EntityChildTest extends JAXPFileBaseTest { + + @Test + public void test() throws Exception { + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setValidating(true); + DocumentBuilder docBuilder = dbf.newDocumentBuilder(); + Document document = docBuilder.parse(new File(XML_DIR + "entitychild.xml")); + + Element root = document.getDocumentElement(); + NodeList n = root.getElementsByTagName("table"); + NodeList nl = n.item(0).getChildNodes(); + assertEquals(n.getLength(), 1); + assertEquals(nl.getLength(), 3); + } +} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NamedNodeMapTest.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NamedNodeMapTest.java new file mode 100644 index 00000000000..49037f80c88 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NamedNodeMapTest.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.w3c.dom.ptests.DOMTestUtil.createDOMWithNS; +import jaxp.library.JAXPFileBaseTest; + +import org.testng.annotations.Test; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/* + * @summary Test for the methods of NamedNodeMap Interface + */ +public class NamedNodeMapTest extends JAXPFileBaseTest { + /* + * Test setNamedItemNS method with a node having the same namespaceURI and + * qualified name as an existing one, and then test with a non-existing node. + */ + @Test + public void testSetNamedItemNS() throws Exception { + final String nsURI = "urn:BooksAreUs.org:BookInfo"; + Document document = createDOMWithNS("NamedNodeMap01.xml"); + NodeList nodeList = document.getElementsByTagName("body"); + nodeList = nodeList.item(0).getChildNodes(); + Node n = nodeList.item(3); + + NamedNodeMap namedNodeMap = n.getAttributes(); + + // creating an Attribute using createAttributeNS + // method having the same namespaceURI + // and the same qualified name as the existing one in the xml file + Attr attr = document.createAttributeNS(nsURI, "b:style"); + // setting to a new Value + attr.setValue("newValue"); + Node replacedAttr = namedNodeMap.setNamedItemNS(attr); // return the replaced attr + assertEquals(replacedAttr.getNodeValue(), "font-family"); + Node updatedAttr = namedNodeMap.getNamedItemNS(nsURI, "style"); + assertEquals(updatedAttr.getNodeValue(), "newValue"); + + + // creating a non existing attribute node + attr = document.createAttributeNS(nsURI, "b:newNode"); + attr.setValue("newValue"); + + assertNull(namedNodeMap.setNamedItemNS(attr)); // return null + + // checking if the node could be accessed + // using the getNamedItemNS method + Node newAttr = namedNodeMap.getNamedItemNS(nsURI, "newNode"); + assertEquals(newAttr.getNodeValue(), "newValue"); + } + + /* + * Verify getNamedItemNS works as the spec + */ + @Test + public void testGetNamedItemNS() throws Exception { + Document document = createDOMWithNS("NamedNodeMap03.xml"); + NodeList nodeList = document.getElementsByTagName("body"); + nodeList = nodeList.item(0).getChildNodes(); + Node n = nodeList.item(7); + NamedNodeMap namedNodeMap = n.getAttributes(); + Node node = namedNodeMap.getNamedItemNS("urn:BooksAreUs.org:BookInfo", "aaa"); + assertEquals(node.getNodeValue(), "value"); + + } + + /* + * Test setNamedItem method with a node having the same name as an existing + * one, and then test with a non-existing node. + */ + @Test + public void testSetNamedItem() throws Exception { + Document document = createDOMWithNS("NamedNodeMap03.xml"); + NodeList nodeList = document.getElementsByTagName("body"); + nodeList = nodeList.item(0).getChildNodes(); + Node n = nodeList.item(1); + + NamedNodeMap namedNodeMap = n.getAttributes(); + Attr attr = document.createAttribute("name"); + Node replacedAttr = namedNodeMap.setNamedItem(attr); + assertEquals(replacedAttr.getNodeValue(), "attributeValue"); + Node updatedAttrNode = namedNodeMap.getNamedItem("name"); + assertEquals(updatedAttrNode.getNodeValue(), ""); + + Attr newAttr = document.createAttribute("nonExistingName"); + assertNull(namedNodeMap.setNamedItem(newAttr)); + Node newAttrNode = namedNodeMap.getNamedItem("nonExistingName"); + assertEquals(newAttrNode.getNodeValue(), ""); + } + +} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NodeListTest.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NodeListTest.java new file mode 100644 index 00000000000..4aa51f76665 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NodeListTest.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static org.testng.Assert.assertEquals; +import static org.w3c.dom.ptests.DOMTestUtil.createDOM; +import jaxp.library.JAXPFileBaseTest; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +/* + * @summary Verifies a bug found in jaxp1.0.1 and 1.1FCS. After going out of + * bound, the last element of a NodeList returns null. The bug has been fixed + * in jaxp 1.1.1 build. + */ +public class NodeListTest extends JAXPFileBaseTest { + + @DataProvider(name = "xml") + public Object[][] getTestData() { + return new Object[][] { { "nodelist.xml", "document" }, { "Node01.xml", "body" } }; + } + + @Test(dataProvider = "xml") + public void lastItemTest(String xmlFileName, String nodeName) throws Exception { + Document document = createDOM(xmlFileName); + + NodeList nl = document.getElementsByTagName(nodeName); + int n = nl.getLength(); + + Element elem1 = (Element) nl.item(n - 1); + nl.item(n); + Element elem3 = (Element) nl.item(n - 1); + assertEquals(elem3, elem1); + + } + +} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NodeTest.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NodeTest.java new file mode 100644 index 00000000000..dddc2ce24b0 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NodeTest.java @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static jaxp.library.JAXPTestUtilities.compareWithGold; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertTrue; +import static org.w3c.dom.ptests.DOMTestUtil.GOLDEN_DIR; +import static org.w3c.dom.ptests.DOMTestUtil.createDOM; +import static org.w3c.dom.ptests.DOMTestUtil.createDOMWithNS; +import static org.w3c.dom.ptests.DOMTestUtil.createNewDocument; + +import java.io.File; + +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import jaxp.library.JAXPFileBaseTest; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.w3c.dom.DOMException; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/* + * @summary Test Node interface + */ +public class NodeTest extends JAXPFileBaseTest { + @DataProvider(name = "feature-supported") + public Object[][] getFeatureSupportedList() throws Exception { + Document document = createDOMWithNS("Node01.xml"); + Node node = document.getElementsByTagName("body").item(0); + return new Object[][] { + { node, "XML", "2.0", true }, + { node, "HTML", "2.0", false }, + { node, "Views", "2.0", false }, + { node, "StyleSheets", "2.0", false }, + { node, "CSS", "2.0", false }, + { node, "CSS2", "2.0", false }, + { node, "Events", "2.0", true }, + { node, "UIEvents", "2.0", false }, + { node, "MouseEvents", "2.0", false }, + { node, "HTMLEvents", "2.0", false }, + { node, "Traversal", "2.0", true }, + { node, "Range", "2.0", true } }; + } + + /* + * Verify Node for feature supporting. + */ + @Test(dataProvider = "feature-supported") + public void testHasFeature(Node node, String feature, String version, boolean supported) { + assertEquals(node.isSupported(feature, version), supported); + } + + /* + * Test normalize method will merge adjacent Text nodes. + */ + @Test + public void testNormalize() throws Exception { + Document document = createDOM("Node05.xml"); + + Element root = document.getDocumentElement(); + + Node node = document.getElementsByTagName("title").item(0); + node.appendChild(document.createTextNode("test")); + root.normalize(); + assertEquals(node.getChildNodes().item(0).getNodeValue(), "Typographytest"); + } + + /* + * Test cloneNode deeply, and the clone node can be appended on the same document. + */ + @Test + public void testCloneNode() throws Exception { + Document document = createDOMWithNS("Node02.xml"); + + NodeList nodeList = document.getElementsByTagName("body"); + Node node = nodeList.item(0); + Node cloneNode = node.cloneNode(true); + + assertTrue(node.isEqualNode(cloneNode)); + assertNotEquals(node, cloneNode); + + nodeList = document.getElementsByTagName("html"); + Node node2 = nodeList.item(0); + node2.appendChild(cloneNode); + } + + /* + * Test importing node from one document to another. + */ + @Test + public void testImportNode() throws Exception { + Document document = createDOMWithNS("Node02.xml"); + Document otherDocument = createDOMWithNS("ElementSample01.xml"); + + NodeList otherNodeList = otherDocument.getElementsByTagName("body"); + Node importedNode = otherNodeList.item(0); + Node clone = importedNode.cloneNode(true); + + Node retNode = document.importNode(importedNode, true); + assertTrue(clone.isEqualNode(importedNode)); //verify importedNode is not changed + assertNotEquals(retNode, importedNode); + assertTrue(importedNode.isEqualNode(retNode)); + + retNode = document.importNode(importedNode, false); + assertTrue(clone.isEqualNode(importedNode)); //verify importedNode is not changed + assertEquals(retNode.getNodeName(), importedNode.getNodeName()); + assertFalse(importedNode.isEqualNode(retNode)); + } + + /* + * Test inserting a document fragment before a particular node. + */ + @Test + public void testInsertBefore() throws Exception { + Document document = createDOM("Node04.xml"); + + Element parentElement = (Element) document.getElementsByTagName("to").item(0); + Element element = (Element) document.getElementsByTagName("sender").item(0); + parentElement.insertBefore(createTestDocumentFragment(document), element); + + String outputfile = "InsertBefore.out"; + String goldfile = GOLDEN_DIR + "InsertBeforeGF.out"; + outputXml(document, outputfile); + assertTrue(compareWithGold(goldfile, outputfile)); + } + + + /* + * Test replacing a particular node with a document fragment. + */ + @Test + public void testReplaceChild() throws Exception { + Document document = createDOM("Node04.xml"); + + Element parentElement = (Element) document.getElementsByTagName("to").item(0); + Element element = (Element) document.getElementsByTagName("sender").item(0); + parentElement.replaceChild(createTestDocumentFragment(document), element); + + String outputfile = "ReplaceChild3.out"; + String goldfile = GOLDEN_DIR + "ReplaceChild3GF.out"; + outputXml(document, outputfile); + assertTrue(compareWithGold(goldfile, outputfile)); + } + + /* + * This test case checks for the replaceChild replacing a particular node + * with a node which was created from a different document than the one + * which is trying to use this method. It should throw a DOMException. + */ + @Test(expectedExceptions = DOMException.class) + public void testReplaceChildNeg() throws Exception { + Document document = createDOM("Node04.xml"); + Document doc2 = createNewDocument(); + + Element parentElement = (Element) document.getElementsByTagName("to").item(0); + Element element = (Element) document.getElementsByTagName("sender").item(0); + parentElement.replaceChild(createTestDocumentFragment(doc2), element); + } + + private DocumentFragment createTestDocumentFragment(Document document) { + DocumentFragment docFragment = document.createDocumentFragment(); + Element elem = document.createElement("dfElement"); + elem.appendChild(document.createTextNode("Text in it")); + docFragment.appendChild(elem); + return docFragment; + } + + private void outputXml(Document document, String outputFileName) throws TransformerFactoryConfigurationError, TransformerException { + DOMSource domSource = new DOMSource(document); + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + StreamResult streamResult = new StreamResult(new File(outputFileName)); + transformer.transform(domSource, streamResult); + } +} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NotationTest.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NotationTest.java new file mode 100644 index 00000000000..eea6ab41b47 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NotationTest.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static org.testng.Assert.assertEquals; +import static org.w3c.dom.ptests.DOMTestUtil.createDOM; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; + +import jaxp.library.JAXPFileBaseTest; + +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Notation; +import org.xml.sax.SAXException; + +/* + * @summary Test for Notation interface + */ +public class NotationTest extends JAXPFileBaseTest { + /* + * Test getSystemId method. + */ + @Test + public void testGetSystemId() throws Exception { + assertEquals(findNotation("gs").getSystemId(), "http://who.knows.where/"); + } + + /* + * Test getPublicId method. + */ + @Test + public void testGetPublicId() throws Exception { + assertEquals(findNotation("pubname").getPublicId(), "pubId"); + } + + //find notation in Notation01.xml + private Notation findNotation(String name) throws SAXException, IOException, ParserConfigurationException { + Document document = createDOM("Notation01.xml"); + NamedNodeMap nm = document.getDoctype().getNotations(); + for (int i = 0; i < nm.getLength(); i++) { + if (nm.item(i).getNodeName().equals(name)) { + return (Notation) nm.item(i); + } + } + throw new RuntimeException("Notation: '" + name + "' not found."); + } + +} diff --git a/jdk/test/jdk/lambda/MethodReferenceTestSuperDefault.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/PITest.java similarity index 56% rename from jdk/test/jdk/lambda/MethodReferenceTestSuperDefault.java rename to jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/PITest.java index f2e2c183cb1..15bd6876c36 100644 --- a/jdk/test/jdk/lambda/MethodReferenceTestSuperDefault.java +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/PITest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,55 +20,32 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ - -import org.testng.annotations.Test; +package org.w3c.dom.ptests; import static org.testng.Assert.assertEquals; +import static org.w3c.dom.ptests.DOMTestUtil.createDOMWithNS; +import jaxp.library.JAXPFileBaseTest; +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.ProcessingInstruction; -/** - * @author Robert Field +/* + * @summary Test for the methods of Processing Instruction */ +public class PITest extends JAXPFileBaseTest { + /* + * Test getData, setData and getTarget methods + */ + @Test + public void test() throws Exception { + Document document = createDOMWithNS("PITest01.xml"); + ProcessingInstruction pi = document.createProcessingInstruction("PI", "processing"); + assertEquals(pi.getData(), "processing"); + assertEquals(pi.getTarget(), "PI"); -interface DSPRI { String m(String a); } - -interface DSPRA { - default String xsA__(String s) { - return "A__xsA:" + s; - } - - default String xsAB_(String s) { - return "AB_xsA:" + s; - } - -} - -interface DSPRB extends DSPRA { - - default String xsAB_(String s) { - return "AB_xsB:" + s; - } - - default String xs_B_(String s) { - return "_B_xsB:" + s; - } - -} - -@Test -public class MethodReferenceTestSuperDefault implements DSPRB { - - public void testMethodReferenceSuper() { - DSPRI q; - - q = DSPRB.super::xsA__; - assertEquals(q.m("*"), "A__xsA:*"); - - q = DSPRB.super::xsAB_; - assertEquals(q.m("*"), "AB_xsB:*"); - - q = DSPRB.super::xs_B_; - assertEquals(q.m("*"), "_B_xsB:*"); + pi.setData("newProcessing"); + assertEquals(pi.getData(), "newProcessing"); } } diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/TextTest.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/TextTest.java new file mode 100644 index 00000000000..7932114b519 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/TextTest.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static org.testng.Assert.assertEquals; +import static org.w3c.dom.ptests.DOMTestUtil.createDOMWithNS; +import static org.w3c.dom.ptests.DOMTestUtil.createNewDocument; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; + +import org.testng.annotations.Test; +import org.w3c.dom.CharacterData; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.Text; +import org.xml.sax.SAXException; + +/* + * @summary Test for Text implementation returned by Document.createTextNode(String) + */ +public class TextTest extends AbstractCharacterDataTest { + /* + * Verify splitText method works as the spec. + */ + @Test + public void testSplitText() throws Exception { + Document document = createDOMWithNS("Text01.xml"); + + NodeList nodeList = document.getElementsByTagName("p"); + Node node = nodeList.item(0); + Text textNode = document.createTextNode("This is a text node"); + node.appendChild(textNode); + int rawChildNum = node.getChildNodes().getLength(); + + textNode.splitText(0); + int increased = node.getChildNodes().getLength() - rawChildNum; + assertEquals(increased, 1); + + } + + @Override + protected CharacterData createCharacterData(String text) throws IOException, SAXException, ParserConfigurationException { + Document document = createNewDocument(); + return document.createTextNode(text); + } + +} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/TypeInfoTest.java b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/TypeInfoTest.java new file mode 100644 index 00000000000..f68dd919e0d --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/TypeInfoTest.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; +import static org.testng.Assert.assertEquals; + +import java.io.StringReader; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import jaxp.library.JAXPBaseTest; + +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.TypeInfo; +import org.xml.sax.InputSource; + +/* + * @summary Test getTypeName and getTypeNamespace methods of TypeInfo interface + */ +public class TypeInfoTest extends JAXPBaseTest { + /* + * Get the TypeInfo of the root element, and verify it. + */ + @Test + public void test() throws Exception { + TypeInfo typeInfo = getTypeOfRoot(SCHEMA_INSTANCE, "\n" + "\n"); + + assertEquals(typeInfo.getTypeName(), "Test"); + assertEquals(typeInfo.getTypeNamespace(), "testNS"); + + } + + private TypeInfo getTypeOfRoot(String schemaText, String docText) throws Exception { + Element root = getRoot(schemaText, docText); + return root.getSchemaTypeInfo(); + } + + private Element getRoot(String schemaText, String docText) throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + + InputSource inSchema = new InputSource(new StringReader(schemaText)); + inSchema.setSystemId("schema.xsd"); + dbf.setNamespaceAware(true); + dbf.setValidating(true); + dbf.setAttribute(SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + dbf.setAttribute(SCHEMA_SOURCE, inSchema); + + DocumentBuilder parser = dbf.newDocumentBuilder(); + + InputSource inSource = new InputSource(new StringReader(docText)); + inSource.setSystemId("doc.xml"); + Document document = parser.parse(inSource); + + return document.getDocumentElement(); + } + + private static final String SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; + + private static final String SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; + + /* + * Schema instance + */ + private static final String SCHEMA_INSTANCE = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n" + + " \n" + + "\n" + + " \n" + + "\n" + + " \n" + + " \n" + + " \n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n" + + "\n"; + + +} diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Attr01.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Attr01.xml new file mode 100644 index 00000000000..62224035142 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Attr01.xml @@ -0,0 +1,18 @@ + + + + Typography + + + +

                            Welcome to the world of typography! Here is a book that you may find useful.

                            + Digital Typography + Donald Knuth + fjfjf + + Numerical Analysis of Partial Differential Equations + Numerical Analysis of Partial Differential Equations + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Attr2.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Attr2.xml new file mode 100644 index 00000000000..8439a564c00 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Attr2.xml @@ -0,0 +1,11 @@ + + + + +]> + + + World's best book + \ No newline at end of file diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Attr3.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Attr3.xml new file mode 100644 index 00000000000..527c68dd691 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Attr3.xml @@ -0,0 +1,10 @@ + + + +]> + + + World's best book + \ No newline at end of file diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Comment01.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Comment01.xml new file mode 100644 index 00000000000..80f7b74eb9e --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Comment01.xml @@ -0,0 +1,15 @@ + + + + Typography + + + +

                            + Digital Typography + Donald Knuth + fjfjf + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentBuilderImpl02.dtd b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentBuilderImpl02.dtd new file mode 100644 index 00000000000..28b8a7b586a --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentBuilderImpl02.dtd @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentTest01.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentTest01.xml new file mode 100644 index 00000000000..15b61585623 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentTest01.xml @@ -0,0 +1,12 @@ + + + + Typography + + + Welcome to the world of typography! Here is a book that you may find useful. + Digital Typography + Donald Knuth + + \ No newline at end of file diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentType01.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentType01.xml new file mode 100644 index 00000000000..348e73f30f1 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentType01.xml @@ -0,0 +1,14 @@ + + + + + + + + +]> + +&writer; + + \ No newline at end of file diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentType03.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentType03.xml new file mode 100644 index 00000000000..de62c6db2e6 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentType03.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + +]> + +lll + + \ No newline at end of file diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentType05.dtd b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentType05.dtd new file mode 100644 index 00000000000..28b8a7b586a --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentType05.dtd @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentType05.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentType05.xml new file mode 100644 index 00000000000..89e09643844 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/DocumentType05.xml @@ -0,0 +1,28 @@ + + + + + Publishers of the Music of New York Women Composers + + The Publishers + + + Alfred Publishing + &w; + 15535 Morrison + South Oaks CA 91403 + + + + eXtensible Markup Language + + + + + + Publishers are not noted in report by time. + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ElementSample01.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ElementSample01.xml new file mode 100644 index 00000000000..62224035142 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ElementSample01.xml @@ -0,0 +1,18 @@ + + + + Typography + + + +

                            Welcome to the world of typography! Here is a book that you may find useful.

                            + Digital Typography + Donald Knuth + fjfjf + + Numerical Analysis of Partial Differential Equations + Numerical Analysis of Partial Differential Equations + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ElementSample02.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ElementSample02.xml new file mode 100644 index 00000000000..e1c0b4352d5 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ElementSample02.xml @@ -0,0 +1,15 @@ + + + + Typography + + + +

                            Welcome to the world of typography! Here is a book that you may find useful.

                            + Digital Typography + Donald Knuth + fjfjf + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ElementSample03.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ElementSample03.xml new file mode 100644 index 00000000000..9fdef74cf64 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ElementSample03.xml @@ -0,0 +1,15 @@ + + + + Typography + + + +

                            Welcome to the world of typography! Here is a book that you may find useful.

                            + Digital Typography + Donald Knuth + fjfjf + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ElementSample04.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ElementSample04.xml new file mode 100644 index 00000000000..b4a307254ef --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ElementSample04.xml @@ -0,0 +1,15 @@ + + + + Typography + + + +

                            Welcome to the world of typography! Here is a book that you may find useful.

                            + Digital Typography + Donald Knuth + this is it + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/NamedNodeMap01.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/NamedNodeMap01.xml new file mode 100644 index 00000000000..07906e988b7 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/NamedNodeMap01.xml @@ -0,0 +1,15 @@ + + + + Typography + + + +

                            Welcome to the world of typography! Here is a book that you may find useful.

                            + Digital Typography + Donald Knuth + fjfjf + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/NamedNodeMap03.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/NamedNodeMap03.xml new file mode 100644 index 00000000000..2e4b9d1588f --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/NamedNodeMap03.xml @@ -0,0 +1,15 @@ + + + + Typography + + + +

                            Welcome to the world of typography! Here is a book that you may find useful.

                            + Digital Typography + Donald Knuth + fjfjf + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Node01.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Node01.xml new file mode 100644 index 00000000000..07906e988b7 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Node01.xml @@ -0,0 +1,15 @@ + + + + Typography + + + +

                            Welcome to the world of typography! Here is a book that you may find useful.

                            + Digital Typography + Donald Knuth + fjfjf + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Node02.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Node02.xml new file mode 100644 index 00000000000..2e4b9d1588f --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Node02.xml @@ -0,0 +1,15 @@ + + + + Typography + + + +

                            Welcome to the world of typography! Here is a book that you may find useful.

                            + Digital Typography + Donald Knuth + fjfjf + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Node04.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Node04.xml new file mode 100644 index 00000000000..d7dd873ffb5 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Node04.xml @@ -0,0 +1,8 @@ + + + +John + +message + weekend! + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Node05.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Node05.xml new file mode 100644 index 00000000000..d32c19dce44 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Node05.xml @@ -0,0 +1,6 @@ + + + + Typography + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Notation01.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Notation01.xml new file mode 100644 index 00000000000..dd26b3ef82e --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Notation01.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + +]> + +lll + + \ No newline at end of file diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/PITest01.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/PITest01.xml new file mode 100644 index 00000000000..07906e988b7 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/PITest01.xml @@ -0,0 +1,15 @@ + + + + Typography + + + +

                            Welcome to the world of typography! Here is a book that you may find useful.

                            + Digital Typography + Donald Knuth + fjfjf + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Text01.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Text01.xml new file mode 100644 index 00000000000..80f7b74eb9e --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/Text01.xml @@ -0,0 +1,15 @@ + + + + Typography + + + +

                            + Digital Typography + Donald Knuth + fjfjf + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ee.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ee.xml new file mode 100644 index 00000000000..7370d56ebf7 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/ee.xml @@ -0,0 +1,7 @@ + + + + +&mkm; + +
                            diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/entitychild.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/entitychild.xml new file mode 100644 index 00000000000..6e2e0e90be7 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/entitychild.xml @@ -0,0 +1,15 @@ + + + + + + + + + +]> + +
                            +ⅇ +
                            diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/nodelist.xml b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/nodelist.xml new file mode 100644 index 00000000000..fbdbfe6830b --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/nodelist.xml @@ -0,0 +1,2 @@ + +onenode diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/out/InsertBeforeGF.out b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/out/InsertBeforeGF.out new file mode 100644 index 00000000000..53cb987a33a --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/out/InsertBeforeGF.out @@ -0,0 +1,7 @@ + + +Text in itJohn + +message + weekend! + diff --git a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/out/ReplaceChild3GF.out b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/out/ReplaceChild3GF.out new file mode 100644 index 00000000000..4199e493fc2 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/xmlfiles/out/ReplaceChild3GF.out @@ -0,0 +1,7 @@ + + +Text in it + +message + weekend! + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/AstroTest.java b/jaxp/test/javax/xml/jaxp/functional/test/astro/AstroTest.java new file mode 100644 index 00000000000..d31fd23f605 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/AstroTest.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import static java.lang.String.valueOf; +import static org.testng.Assert.assertEquals; +import static test.astro.AstroConstants.ASTROCAT; +import static test.astro.AstroConstants.GOLDEN_DIR; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; + +import javax.xml.transform.sax.TransformerHandler; + +import jaxp.library.JAXPFileBaseTest; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +/* + * @summary run astro application, test xslt + * + * There are vast amounts of textual astronomical data, typically user is + * interested in a small subset, which is the result from carrying out a query. + * A query can be composed of one or more filters, for example, the user could + * query the database for all stars of visual magnitude down to 6.5 that lie + * between right ascensions 0 h to 2 h, and between declinations of 45 to 90 degrees. + * + * Astro application uses JAXP to query astronomical data saved in an XML dataset. + * A FilterFactory implementation creates filter(A filter is an instance of a JAXP + * TransformerHandler) from an XSL stylesheet. + * A InputSourceFactory implementation creates a new sax input source from an XML file. + * AstroProcessor leverages InputSourceFactory to parse catalog.xml, which saves + * textual astronomical data, and then creates filters with specified parameters + * from FilterFactory, all of the filters are chained together, AstroProcessor + * appends the HTML filter at the end of filter chain, and hooks up the chain to + * the input source, finally processes and outputs to the user specified output file. + * + * AstroTest drives AstroProcessor to run the specified queries(total 4 in setup), + * and then compares the output with the golden files to determine PASS or FAIL. + * It provides variant implementations of FilterFactory and InputSourceFactory to + * AstroProcessor to test different JAXP classes and features. + * + */ +public class AstroTest extends JAXPFileBaseTest { + private FiltersAndGolden[] data; + + @BeforeClass + public void setup() throws Exception { + data = new FiltersAndGolden[4]; + data[0] = new FiltersAndGolden(getGoldenFileContent(1), astro -> astro.getRAFilter(0.106, 0.108)); + data[1] = new FiltersAndGolden(getGoldenFileContent(2), astro -> astro.getStellarTypeFilter("K0IIIbCN-0.5")); + data[2] = new FiltersAndGolden(getGoldenFileContent(3), astro -> astro.getStellarTypeFilter("G"), astro -> astro.getDecFilter(-5.0, 60.0)); + data[3] = new FiltersAndGolden(getGoldenFileContent(4), astro -> astro.getRADECFilter(0.084, 0.096, -5.75, 14.0)); + } + + /* + * Provide permutations of InputSourceFactory and FilterFactory for test. + */ + @DataProvider(name = "factories") + public Object[][] getQueryFactories() { + return new Object[][] { + { StreamFilterFactoryImpl.class, InputSourceFactoryImpl.class }, + { SAXFilterFactoryImpl.class, InputSourceFactoryImpl.class }, + { DOMFilterFactoryImpl.class, InputSourceFactoryImpl.class }, + { TemplatesFilterFactoryImpl.class, InputSourceFactoryImpl.class }, + { StreamFilterFactoryImpl.class, DOML3InputSourceFactoryImpl.class } }; + } + + @Test(dataProvider = "factories") + public void test(Class fFactClass, Class isFactClass) throws Exception { + System.out.println(fFactClass.getName() +" : " + isFactClass.getName()); + AstroProcessor astro = new AstroProcessor(fFactClass, ASTROCAT, isFactClass); + + for (int i = 0; i < data.length; i++) { + runProcess(astro, valueOf(i + 1), data[i].getGolden(), data[i].getFilters()); + } + } + + private void runProcess(AstroProcessor astro, String processNum, List goldenfileContent, FilterCreator... filterCreators) throws Exception { + System.out.println("run process " + processNum); + TransformerHandler[] filters = new TransformerHandler[filterCreators.length]; + for (int i = 0; i < filterCreators.length; i++) + filters[i] = filterCreators[i].createFilter(astro); + + String outputfile = Files.createTempFile(Paths.get("").toAbsolutePath(), "query" + processNum + ".out.", null).toString(); + System.out.println("output file: " + outputfile); + astro.process(outputfile, filters); + assertEquals(Files.readAllLines(Paths.get(outputfile)), goldenfileContent); + } + + private List getGoldenFileContent(int num) throws IOException { + return Files.readAllLines(Paths.get(GOLDEN_DIR + "query" + num + ".out")); + } + + @FunctionalInterface + private interface FilterCreator { + TransformerHandler createFilter(AstroProcessor astro) throws Exception; + } + + private static class FiltersAndGolden { + private FilterCreator[] filters; + private List golden; + + FiltersAndGolden(List golden, FilterCreator... filters) { + this.filters = filters; + this.golden = golden; + } + + FilterCreator[] getFilters() { + return filters; + } + + List getGolden() { + return golden; + } + } +} diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/DocumentLSTest.java b/jaxp/test/javax/xml/jaxp/functional/test/astro/DocumentLSTest.java new file mode 100644 index 00000000000..b0a76282f7d --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/DocumentLSTest.java @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import static org.w3c.dom.ls.DOMImplementationLS.MODE_SYNCHRONOUS; +import static test.astro.AstroConstants.ASTROCAT; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Writer; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import jaxp.library.JAXPFileBaseTest; + +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSInput; +import org.w3c.dom.ls.LSOutput; +import org.w3c.dom.ls.LSParser; +import org.w3c.dom.ls.LSSerializer; + +/* + * @summary org.w3c.dom.ls tests + */ +public class DocumentLSTest extends JAXPFileBaseTest { + /* + * Test creating an empty Document + */ + @Test + public void testNewDocument() throws ParserConfigurationException { + Document doc = getDocumentBuilder().newDocument(); + assertNull(doc.getDocumentElement()); + } + + /* + * Test creating an LSInput instance, and parsing ByteStream + */ + @Test + public void testLSInputParsingByteStream() throws Exception { + DOMImplementationLS impl = (DOMImplementationLS) getDocumentBuilder().getDOMImplementation(); + LSParser domParser = impl.createLSParser(MODE_SYNCHRONOUS, null); + LSInput src = impl.createLSInput(); + + try (InputStream is = new FileInputStream(ASTROCAT)) { + src.setByteStream(is); + assertNotNull(src.getByteStream()); + // set certified accessor methods + boolean origCertified = src.getCertifiedText(); + src.setCertifiedText(true); + assertTrue(src.getCertifiedText()); + src.setCertifiedText(origCertified); // set back to orig + + src.setSystemId(filenameToURL(ASTROCAT)); + + Document doc = domParser.parse(src); + Element result = doc.getDocumentElement(); + assertEquals(result.getTagName(), "stardb"); + } + } + + /* + * Test creating an LSInput instance, and parsing String + */ + @Test + public void testLSInputParsingString() throws Exception { + DOMImplementationLS impl = (DOMImplementationLS) getDocumentBuilder().getDOMImplementation(); + String xml = "runDocumentLS_Q6"; + + LSParser domParser = impl.createLSParser(MODE_SYNCHRONOUS, null); + LSSerializer domSerializer = impl.createLSSerializer(); + // turn off xml decl in serialized string for comparison + domSerializer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE); + LSInput src = impl.createLSInput(); + src.setStringData(xml); + assertEquals(src.getStringData(), xml); + + Document doc = domParser.parse(src); + String result = domSerializer.writeToString(doc); + + assertEquals(result, "runDocumentLS_Q6"); + } + + /* + * Test writing with an LSOutput instance + */ + @Test + public void testLSOutput() throws Exception { + DocumentBuilder db = getDocumentBuilder(); + // Create the Document using the supplied builder... + Document doc = db.parse(ASTROCAT); + + DOMImplementationLS impl = null; + + impl = (DOMImplementationLS) db.getDOMImplementation(); + LSSerializer domSerializer = impl.createLSSerializer(); + MyDOMOutput mydomoutput = new MyDOMOutput(); + try (OutputStream os = new FileOutputStream("test.out")) { + mydomoutput.setByteStream(os); + mydomoutput.setEncoding("UTF-8"); + assertTrue(domSerializer.write(doc, mydomoutput)); + } + } + + private static class MyDOMOutput implements LSOutput { + private OutputStream bytestream = null; + private String encoding = null; + private String sysId = null; + private Writer writer = null; + + public OutputStream getByteStream() { + return bytestream; + } + + public Writer getCharacterStream() { + return writer; + } + + public String getEncoding() { + return encoding; + } + + public String getSystemId() { + return sysId; + } + + public void setByteStream(OutputStream bs) { + bytestream = bs; + } + + public void setCharacterStream(Writer cs) { + writer = cs; + } + + public void setEncoding(String enc) { + encoding = enc; + } + + public void setSystemId(String sysId) { + this.sysId = sysId; + } + } + + private DocumentBuilder getDocumentBuilder() throws ParserConfigurationException { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + return dbf.newDocumentBuilder(); + } +} diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/NamespaceContextTest.java b/jaxp/test/javax/xml/jaxp/functional/test/astro/NamespaceContextTest.java new file mode 100644 index 00000000000..6a1d0dd3d66 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/NamespaceContextTest.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import static javax.xml.XMLConstants.DEFAULT_NS_PREFIX; +import static javax.xml.XMLConstants.NULL_NS_URI; +import static org.testng.Assert.assertEquals; + +import javax.xml.namespace.QName; + +import jaxp.library.JAXPBaseTest; + +import org.testng.annotations.Test; + +/* + * @summary javax.xml.namespace.QName tests + */ +public class NamespaceContextTest extends JAXPBaseTest { + private static final String PREFIX = "astro"; + private static final String LOCAL_PART = "stardb"; + private static final String NS_URI = "http://www.astro.com"; + + /* + * Test QName(String, String, String) and accessors. + */ + @Test + public void testQNameConstructor() { + QName qname = new QName(NS_URI, LOCAL_PART, PREFIX); + assertEquals(qname.getNamespaceURI(), NS_URI); + assertEquals(qname.getLocalPart(), LOCAL_PART); + assertEquals(qname.getPrefix(), PREFIX); + } + + /* + * Construct QName(String localpart), then test for default ns_uri and + * prefix constant. + */ + @Test + public void testDefaultFields() { + QName qname = new QName(LOCAL_PART); // just the local part specified + assertEquals(qname.getNamespaceURI(), NULL_NS_URI); + assertEquals(qname.getLocalPart(), LOCAL_PART); + assertEquals(qname.getPrefix(), DEFAULT_NS_PREFIX); + } + + /* + * Construct QName(String ns,String localpart), then test for default prefix + * constant. + */ + @Test + public void testDefaultPrefix() { + QName qname = new QName(NS_URI, LOCAL_PART); // no pref + assertEquals(qname.getNamespaceURI(), NS_URI); + assertEquals(qname.getLocalPart(), LOCAL_PART); + assertEquals(qname.getPrefix(), DEFAULT_NS_PREFIX); + } + + /* + * Round trip testing of QName to String, String to QName and test for + * equality. + */ + @Test + public void testQNameString() { + QName qname = new QName(NS_URI, LOCAL_PART, PREFIX); + assertEquals(QName.valueOf(qname.toString()), qname); + } +} diff --git a/jdk/test/jdk/lambda/MethodReferenceTestTypeConversion.java b/jaxp/test/javax/xml/jaxp/functional/test/astro/SAX201Test.java similarity index 58% rename from jdk/test/jdk/lambda/MethodReferenceTestTypeConversion.java rename to jaxp/test/javax/xml/jaxp/functional/test/astro/SAX201Test.java index e36b724b341..bcba454c126 100644 --- a/jdk/test/jdk/lambda/MethodReferenceTestTypeConversion.java +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/SAX201Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,34 +20,27 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ +package test.astro; + +import javax.xml.parsers.SAXParserFactory; + +import jaxp.library.JAXPBaseTest; import org.testng.annotations.Test; +import org.xml.sax.XMLReader; -import static org.testng.Assert.assertEquals; - -/** - * @author Robert Field +/* + * @summary verify SAX 2.0.1 allows to use null in setters */ - -class MethodReferenceTestTypeConversion_E { - T xI(T t) { return t; } -} - -@Test -public class MethodReferenceTestTypeConversion { - - interface ISi { int m(Short a); } - - interface ICc { char m(Character a); } - - public void testUnboxObjectToNumberWiden() { - ISi q = (new MethodReferenceTestTypeConversion_E())::xI; - assertEquals(q.m((short)77), (short)77); +public class SAX201Test extends JAXPBaseTest { + @Test + public void test() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + XMLReader reader = spf.newSAXParser().getXMLReader(); + reader.setErrorHandler(null); // SAX 2.0.1 allows + reader.setContentHandler(null); // SAX 2.0.1 allows + reader.setEntityResolver(null); // SAX 2.0.1 allows + reader.setDTDHandler(null); // SAX 2.0.1 allows } - - public void testUnboxObjectToChar() { - ICc q = (new MethodReferenceTestTypeConversion_E())::xI; - assertEquals(q.m('@'), '@'); - } - } diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/SchemaValidationTest.java b/jaxp/test/javax/xml/jaxp/functional/test/astro/SchemaValidationTest.java new file mode 100644 index 00000000000..c84fddb6882 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/SchemaValidationTest.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; +import static test.astro.AstroConstants.ASTROCAT; +import static test.astro.AstroConstants.JAXP_SCHEMA_LANGUAGE; +import static test.astro.AstroConstants.JAXP_SCHEMA_SOURCE; + +import java.io.File; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import jaxp.library.JAXPFileBaseTest; + +import org.testng.annotations.Test; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/* + * @summary test parser sets schema related properties to do validation + */ +public class SchemaValidationTest extends JAXPFileBaseTest { + /* + * Only set the schemaLanguage, without setting schemaSource. It should + * work. + */ + @Test + public void testSchemaValidation() throws Exception { + SAXParser sp = getValidatingParser(); + sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + sp.parse(new File(ASTROCAT), new DefaultHandler()); + } + + /* + * Test SAXException shall be thrown if schemaSource is set but + * schemaLanguage is not set. + */ + @Test(expectedExceptions = SAXException.class) + public void testSchemaValidationNeg() throws Exception { + SAXParser sp = getValidatingParser(); + sp.setProperty(JAXP_SCHEMA_SOURCE, "catalog.xsd"); + sp.parse(new File(ASTROCAT), new DefaultHandler()); + } + + private SAXParser getValidatingParser() throws ParserConfigurationException, SAXException { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setValidating(true); + return spf.newSAXParser(); + } +} diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/XPathAPITest.java b/jaxp/test/javax/xml/jaxp/functional/test/astro/XPathAPITest.java new file mode 100644 index 00000000000..a97590fef38 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/XPathAPITest.java @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; +import static javax.xml.xpath.XPathConstants.DOM_OBJECT_MODEL; +import static javax.xml.xpath.XPathConstants.NODESET; +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.testng.Assert.assertEquals; +import static test.astro.AstroConstants.ASTROCAT; +import static test.astro.AstroConstants.JAXP_SCHEMA_LANGUAGE; +import static test.astro.AstroConstants.JAXP_SCHEMA_SOURCE; + +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.Iterator; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; +import javax.xml.xpath.XPathVariableResolver; + +import jaxp.library.JAXPFileBaseTest; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +/* + * @summary test XPath API + */ +@Test(singleThreaded = true) +public class XPathAPITest extends JAXPFileBaseTest { + private static final String STARDB_STAR_3_CONSTELLATION = "//astro:stardb/astro:star[3]/astro:constellation"; + private static final String STARDB_STAR = "//astro:stardb/astro:star"; + private Document doc; + private XPathFactory xpf; + private NamespaceContext nsContext; + + @BeforeClass + public void setup() throws Exception { + DocumentBuilderFactory df = DocumentBuilderFactory.newInstance(); + df.setNamespaceAware(true); + df.setValidating(true); + df.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + df.setAttribute(JAXP_SCHEMA_SOURCE, "catalog.xsd"); + DocumentBuilder bldr = df.newDocumentBuilder(); + doc = bldr.parse(ASTROCAT); + + xpf = XPathFactory.newInstance(DOM_OBJECT_MODEL); + + nsContext = new MyNamespaceContext(); + } + + @DataProvider(name = "nodelist-evaluator") + public Object[][] getNodeListEvaluator() throws MalformedURLException { + return new Object[][] { { (XPathEvaluator) expression -> getXPath().evaluate(expression, doc.getDocumentElement(), NODESET) }, + { (XPathEvaluator) expression -> getXPath().evaluate(expression, createXMLInputSource(), NODESET) }, + { (XPathEvaluator) expression -> getXPathExpression(expression).evaluate(doc.getDocumentElement(), NODESET) }, + { (XPathEvaluator) expression -> getXPathExpression(expression).evaluate(createXMLInputSource(), NODESET) } }; + } + + /* + * Test xpath expression evaluations method that returns type indicated by + * QName + */ + @Test(dataProvider = "nodelist-evaluator") + public void testEvaluateNodeList(XPathEvaluator evaluator) throws Exception { + NodeList o = (NodeList) evaluator.evaluate(STARDB_STAR); + assertEquals(o.getLength(), 10); + } + + @DataProvider(name = "string-evaluator") + public Object[][] getStringEvaluator() throws MalformedURLException { + return new Object[][] { { (XPathEvaluator) expression -> getXPath().evaluate(expression, doc.getDocumentElement()) }, + { (XPathEvaluator) expression -> getXPath().evaluate(expression, createXMLInputSource()) }, + { (XPathEvaluator) expression -> getXPathExpression(expression).evaluate(doc.getDocumentElement()) }, + { (XPathEvaluator) expression -> getXPathExpression(expression).evaluate(createXMLInputSource()) } }; + } + + /* + * Test xpath expression evaluations method that returns String + */ + @Test(dataProvider = "string-evaluator") + public void testEvaluateString(XPathEvaluator evaluator) throws Exception { + assertEquals(evaluator.evaluate(STARDB_STAR_3_CONSTELLATION), "Psc"); + } + + @Test + public void testXPathVariableResolver() throws Exception { + XPath xpath = getXPath(); + xpath.setXPathVariableResolver(new MyXPathVariableResolver()); + assertEquals(xpath.evaluate("//astro:stardb/astro:star[astro:hr=$id]/astro:constellation", doc.getDocumentElement()), "Peg"); + + } + + private static class MyXPathVariableResolver implements XPathVariableResolver { + public Object resolveVariable(QName vname) { + return "4"; // resolve $id as 4, xpath will locate to star[hr=4] + } + } + + /* + * Implementation of a NamespaceContext interface for the Xpath api tests. + * Used in xpath.setNamespaceContext(...) + */ + private static class MyNamespaceContext implements NamespaceContext { + public String getNamespaceURI(String prefix) { + return "astro".equals(prefix) ? "http://www.astro.com/astro" : ""; + } + + public String getPrefix(String nsURI) { + return "http://www.astro.com/astro".equals(nsURI) ? "astro" : ""; + } + + public Iterator getPrefixes(String nsURI) { + ArrayList list = new ArrayList(); + list.add("astro"); + return list.iterator(); + } + } + + @FunctionalInterface + private interface XPathEvaluator { + Object evaluate(String expression) throws XPathExpressionException; + } + + private XPath getXPath() { + XPath xpath = xpf.newXPath(); + xpath.setNamespaceContext(nsContext); + return xpath; + } + + private XPathExpression getXPathExpression(String expression) throws XPathExpressionException { + return getXPath().compile(expression); + } + + private InputSource createXMLInputSource() { + return new InputSource(filenameToURL(ASTROCAT)); + } +} diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/catalog.xml b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/catalog.xml new file mode 100644 index 00000000000..2137a1cad90 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/catalog.xml @@ -0,0 +1,17 @@ + + + <_test01> + + + <_test-04>T%e!s#t$ +
                            1000509.90.0860833333333333345134545.22916666666667114.44-16.886.70A1Vn
                            +
                            2000503.80.08438888888888889-003011-0.503055555555555698.33-61.146.29gG9
                            +
                            3Psc33 Psc000520.10.08891666666666666-054227-5.707500000000000593.75-65.934.61K0IIIbCN-0.5
                            +
                            4Peg86 Peg000542.00.09513234613.39611111111111106.19-47.985.51G5III
                            +
                            5000616.00.1044444444444444558261258.43666666666666117.03-03.925.96G5V
                            +
                            6000619.00.10527777777777779-490430-49.075321.61-66.385.70G1IV
                            +
                            7Cas10 Cas000626.50.1073611111111111264114664.19611111111111118.061.755.59B9III
                            +
                            8000636.80.1102222222222222229011729.02138888888889111.26-32.836.13K0V
                            +
                            9000650.10.11391666666666667-230627-23.107552.21-79.146.18A7V
                            +
                            10000718.20.12172222222222222-172311-17.38638888888888874.36-75.906.19A6Vn
                            +
                            diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/catalog.xml.bak b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/catalog.xml.bak new file mode 100644 index 00000000000..0fa5eb7ab58 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/catalog.xml.bak @@ -0,0 +1,2 @@ + +<_test01><_test-04>T%e!s#t$
                            1000509.90.0860833333333333345134545.22916666666667114.44-16.886.70A1Vn

                            2000503.80.08438888888888889-003011-0.503055555555555698.33-61.146.29gG9

                            3Psc33 Psc000520.10.08891666666666666-054227-5.707500000000000593.75-65.934.61K0IIIbCN-0.5

                            4Peg86 Peg000542.00.09513234613.39611111111111106.19-47.985.51G5III

                            5000616.00.1044444444444444558261258.43666666666666117.03-03.925.96G5V

                            6000619.00.10527777777777779-490430-49.075321.61-66.385.70G1IV

                            7Cas10 Cas000626.50.1073611111111111264114664.19611111111111118.061.755.59B9III

                            8000636.80.1102222222222222229011729.02138888888889111.26-32.836.13K0V

                            9000650.10.11391666666666667-230627-23.107552.21-79.146.18A7V

                            10000718.20.12172222222222222-172311-17.38638888888888874.36-75.906.19A6Vn
                            diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/catalog.xsd b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/catalog.xsd new file mode 100644 index 00000000000..6e95cb8e31f --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/catalog.xsd @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/gold/query1.out b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/gold/query1.out new file mode 100644 index 00000000000..d5ccc94fa11 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/gold/query1.out @@ -0,0 +1,15 @@ + +

                            Bright Star Catalog Extract

                            + +Star Id: 7
                            +Constellation: Cas
                            +Description: 10 Cas
                            +RA J2000: 00:06:26.5
                            +DEC J2000: 64:11:46
                            +Visual Magnitude: 5.59
                            +Spectral Type: B9III
                            +Galactic Longitude: 118.06
                            +Galactic Latitude: 1.75
                            +
                            + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/gold/query2.out b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/gold/query2.out new file mode 100644 index 00000000000..22dc28c6581 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/gold/query2.out @@ -0,0 +1,15 @@ + +

                            Bright Star Catalog Extract

                            + +Star Id: 3
                            +Constellation: Psc
                            +Description: 33 Psc
                            +RA J2000: 00:05:20.1
                            +DEC J2000: 05:42:27
                            +Visual Magnitude: 4.61
                            +Spectral Type: K0IIIbCN-0.5
                            +Galactic Longitude: 93.75
                            +Galactic Latitude: -65.93
                            +
                            + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/gold/query3.out b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/gold/query3.out new file mode 100644 index 00000000000..e3f7184369d --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/gold/query3.out @@ -0,0 +1,39 @@ + +

                            Bright Star Catalog Extract

                            + +Star Id: 2
                            +Constellation: +
                            +Description: +
                            +RA J2000: 00:05:03.8
                            +DEC J2000: 00:30:11
                            +Visual Magnitude: 6.29
                            +Spectral Type: gG9
                            +Galactic Longitude: 98.33
                            +Galactic Latitude: -61.14
                            +
                            +Star Id: 4
                            +Constellation: Peg
                            +Description: 86 Peg
                            +RA J2000: 00:05:42.0
                            +DEC J2000: 13:23:46
                            +Visual Magnitude: 5.51
                            +Spectral Type: G5III
                            +Galactic Longitude: 106.19
                            +Galactic Latitude: -47.98
                            +
                            +Star Id: 5
                            +Constellation: +
                            +Description: +
                            +RA J2000: 00:06:16.0
                            +DEC J2000: 58:26:12
                            +Visual Magnitude: 5.96
                            +Spectral Type: G5V
                            +Galactic Longitude: 117.03
                            +Galactic Latitude: -03.92
                            +
                            + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/gold/query4.out b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/gold/query4.out new file mode 100644 index 00000000000..71b99603efd --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/gold/query4.out @@ -0,0 +1,37 @@ + +

                            Bright Star Catalog Extract

                            + +Star Id: 2
                            +Constellation: +
                            +Description: +
                            +RA J2000: 00:05:03.8
                            +DEC J2000: 00:30:11
                            +Visual Magnitude: 6.29
                            +Spectral Type: gG9
                            +Galactic Longitude: 98.33
                            +Galactic Latitude: -61.14
                            +
                            +Star Id: 3
                            +Constellation: Psc
                            +Description: 33 Psc
                            +RA J2000: 00:05:20.1
                            +DEC J2000: 05:42:27
                            +Visual Magnitude: 4.61
                            +Spectral Type: K0IIIbCN-0.5
                            +Galactic Longitude: 93.75
                            +Galactic Latitude: -65.93
                            +
                            +Star Id: 4
                            +Constellation: Peg
                            +Description: 86 Peg
                            +RA J2000: 00:05:42.0
                            +DEC J2000: 13:23:46
                            +Visual Magnitude: 5.51
                            +Spectral Type: G5III
                            +Galactic Longitude: 106.19
                            +Galactic Latitude: -47.98
                            +
                            + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/dec-ent.xsl b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/dec-ent.xsl new file mode 100644 index 00000000000..f4d1ea1b491 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/dec-ent.xsl @@ -0,0 +1,36 @@ + + + +]> + + + + + + + + + + + &toplevel; + + + + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/dec.xsl b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/dec.xsl new file mode 100644 index 00000000000..9a4ce901cd4 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/dec.xsl @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/dec_frag.xsl b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/dec_frag.xsl new file mode 100644 index 00000000000..2628420e58d --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/dec_frag.xsl @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/html.xsl b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/html.xsl new file mode 100644 index 00000000000..9f4594d469b --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/html.xsl @@ -0,0 +1,38 @@ + + + + + + + + +

                            Bright Star Catalog Extract

                            + + + + +
                            + + + Star Id:
                            + Constellation:
                            + Description:
                            + RA J2000: ::
                            + DEC J2000: ::
                            + Visual Magnitude:
                            + Spectral Type:
                            + Galactic Longitude:
                            + Galactic Latitude:
                            +
                            +
                            + + + + + + +
                            + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/ra-ent.xsl b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/ra-ent.xsl new file mode 100644 index 00000000000..5d08bf69c53 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/ra-ent.xsl @@ -0,0 +1,29 @@ + +]> + + + + + + + + + &toplevel; + + + + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/ra-uri.xsl b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/ra-uri.xsl new file mode 100644 index 00000000000..b7211295e6c --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/ra-uri.xsl @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/ra.xsl b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/ra.xsl new file mode 100644 index 00000000000..7b60fb35ae5 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/ra.xsl @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/ra_frag.xsl b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/ra_frag.xsl new file mode 100644 index 00000000000..d69ab83072b --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/ra_frag.xsl @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/radec.xsl b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/radec.xsl new file mode 100644 index 00000000000..4a0b63c2797 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/radec.xsl @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/stellartype.xsl b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/stellartype.xsl new file mode 100644 index 00000000000..e19e9aec343 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/stellartype.xsl @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/toptemplate.xsl b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/toptemplate.xsl new file mode 100644 index 00000000000..e4191deefbd --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/toptemplate.xsl @@ -0,0 +1,17 @@ + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/toptemplateinc.xsl b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/toptemplateinc.xsl new file mode 100644 index 00000000000..81b6d938967 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/xmlfiles/xsl/toptemplateinc.xsl @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + diff --git a/jaxp/test/javax/xml/jaxp/libs/org/w3c/dom/ptests/DOMTestUtil.java b/jaxp/test/javax/xml/jaxp/libs/org/w3c/dom/ptests/DOMTestUtil.java new file mode 100644 index 00000000000..6b32aa36e74 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/org/w3c/dom/ptests/DOMTestUtil.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 org.w3c.dom.ptests; + +import static jaxp.library.JAXPTestUtilities.FILE_SEP; +import static jaxp.library.JAXPTestUtilities.getPathByClassName; + +import java.io.File; +import java.io.IOException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +/* + * This class defines the path constant and common method + */ +public class DOMTestUtil { + /* + * XML source file directory. + */ + public static final String XML_DIR = getPathByClassName(DOMTestUtil.class, ".." + FILE_SEP + "xmlfiles"); + + /* + * Golden validation files directory. + */ + public static final String GOLDEN_DIR = getPathByClassName(DOMTestUtil.class, ".." + FILE_SEP + "xmlfiles" + FILE_SEP + "out"); + + /* + * Error Message for DOMException being expected. + */ + public static final String DOMEXCEPTION_EXPECTED = "Should throw DOMException"; + + /* + * Create DOM Document from an xml file. + */ + public static Document createDOM(String xmlFileName) throws SAXException, IOException, ParserConfigurationException { + return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(XML_DIR + xmlFileName)); + } + + /* + * Create DOM Document from an xml file with setNamespaceAware(true). + */ + public static Document createDOMWithNS(String xmlFileName) throws IOException, SAXException, ParserConfigurationException { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + return dbf.newDocumentBuilder().parse(new File(XML_DIR + xmlFileName)); + } + + /* + * Create a new DOM Document. + */ + public static Document createNewDocument() throws ParserConfigurationException { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + return db.newDocument(); + } +} diff --git a/jaxp/test/javax/xml/jaxp/libs/test/astro/AbstractFilterFactory.java b/jaxp/test/javax/xml/jaxp/libs/test/astro/AbstractFilterFactory.java new file mode 100644 index 00000000000..da6feeb6e01 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/test/astro/AbstractFilterFactory.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import static test.astro.AstroConstants.HTMLXSL; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.sax.TransformerHandler; + +import org.xml.sax.SAXException; + +public abstract class AbstractFilterFactory implements FilterFactory { + @Override + public TransformerHandler newRAFilter(double min, double max) throws TransformerConfigurationException, SAXException, ParserConfigurationException, + IOException { + TransformerHandler retval = getTransformerHandler(getRAXsl()); + Transformer xformer = retval.getTransformer(); + xformer.setParameter("ra_min_hr", String.valueOf(min)); + xformer.setParameter("ra_max_hr", String.valueOf(max)); + return retval; + } + + @Override + public TransformerHandler newDECFilter(double min, double max) throws TransformerConfigurationException, SAXException, ParserConfigurationException, + IOException { + TransformerHandler retval = getTransformerHandler(getDECXsl()); + Transformer xformer = retval.getTransformer(); + xformer.setParameter("dec_min_deg", String.valueOf(min)); + xformer.setParameter("dec_max_deg", String.valueOf(max)); + return retval; + } + + @Override + public TransformerHandler newRADECFilter(double rmin, double rmax, double dmin, double dmax) throws TransformerConfigurationException, SAXException, + ParserConfigurationException, IOException { + TransformerHandler retval = getTransformerHandler(getRADECXsl()); + Transformer xformer = retval.getTransformer(); + xformer.setParameter("ra_min_hr", String.valueOf(rmin)); + xformer.setParameter("ra_max_hr", String.valueOf(rmax)); + xformer.setParameter("dec_min_deg", String.valueOf(dmin)); + xformer.setParameter("dec_max_deg", String.valueOf(dmax)); + return retval; + } + + @Override + public TransformerHandler newStellarTypeFilter(String type) throws TransformerConfigurationException, SAXException, ParserConfigurationException, + IOException { + TransformerHandler retval = getTransformerHandler(getStellarXsl()); + Transformer xformer = retval.getTransformer(); + xformer.setParameter("type", type); + return retval; + } + + @Override + public TransformerHandler newHTMLOutput() throws TransformerConfigurationException, SAXException, ParserConfigurationException, IOException { + return getTransformerHandler(HTMLXSL); + } + + abstract protected TransformerHandler getTransformerHandler(String xslFileName) throws SAXException, ParserConfigurationException, + TransformerConfigurationException, IOException; + + abstract protected String getRAXsl(); + + abstract protected String getDECXsl(); + + abstract protected String getRADECXsl(); + + abstract protected String getStellarXsl(); +} diff --git a/jaxp/test/javax/xml/jaxp/libs/test/astro/AstroConstants.java b/jaxp/test/javax/xml/jaxp/libs/test/astro/AstroConstants.java new file mode 100644 index 00000000000..b3f2cb6e5c6 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/test/astro/AstroConstants.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import static java.io.File.separator; +import static jaxp.library.JAXPTestUtilities.getPathByClassName; + +public class AstroConstants { + // Query parameters : + + public static final double RA_MIN = 0.0; // hours + public static final double RA_MAX = 24.0; // hours + public static final double DEC_MIN = -90.000; // degrees + public static final double DEC_MAX = 90.000; // degrees + + // Stylesheet source paths: + + public static final String XSLPATH = getPathByClassName(AstroConstants.class, "xmlfiles" + separator + "xsl"); + public static final String RAXSL = XSLPATH + "ra.xsl"; + public static final String DECXSL = XSLPATH + "dec.xsl"; + public static final String RADECXSL = XSLPATH + "radec.xsl"; + public static final String STYPEXSL = XSLPATH + "stellartype.xsl"; + public static final String HTMLXSL = XSLPATH + "html.xsl"; + + public static final String RAENTXSL = XSLPATH + "ra-ent.xsl"; + public static final String DECENTXSL = XSLPATH + "dec-ent.xsl"; + public static final String RAURIXSL = XSLPATH + "ra-uri.xsl"; + public static final String TOPTEMPLXSL = XSLPATH + "toptemplate.xsl"; + public static final String TOPTEMPLINCXSL = XSLPATH + "toptemplateinc.xsl"; + + // Catalog references + + public static final String ASTROCAT = getPathByClassName(AstroConstants.class, "xmlfiles") + "catalog.xml"; + + + public static final String GOLDEN_DIR = getPathByClassName(AstroConstants.class, "xmlfiles" + separator + "gold"); + public static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; + public static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; +} diff --git a/jaxp/test/javax/xml/jaxp/libs/test/astro/AstroProcessor.java b/jaxp/test/javax/xml/jaxp/libs/test/astro/AstroProcessor.java new file mode 100644 index 00000000000..0ed8a0dfb7b --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/test/astro/AstroProcessor.java @@ -0,0 +1,279 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; +import static test.astro.AstroConstants.DEC_MAX; +import static test.astro.AstroConstants.DEC_MIN; +import static test.astro.AstroConstants.JAXP_SCHEMA_LANGUAGE; +import static test.astro.AstroConstants.JAXP_SCHEMA_SOURCE; +import static test.astro.AstroConstants.RA_MAX; +import static test.astro.AstroConstants.RA_MIN; + +import java.io.File; +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.sax.SAXResult; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; + +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.XMLReader; + +/* + * AstroProcessor is to carry out the user's query with filters and produce a table of + * star records that match the criterion, and finally output with HTML format. + */ +public class AstroProcessor { + private String catalogFileName; + + private FilterFactory ffact; + private InputSourceFactory isfact; + + private SAXParserFactory spf; + + /* + * Constructor for the Main astro class. + * + * @param fFactClass the class of the FilterFactory implementation + * + * @param catalogfilename the name of the XML input document (database) + * + * @param isFactClass the class of the Input Source Factory implementation + */ + public AstroProcessor(Class fFactClass, String catalogFileName, Class isFactClass) throws Exception { + // create the Filter Factory instance... + + ffact = fFactClass.newInstance(); + + // create the Input Source Instance + + isfact = isFactClass.newInstance(); + + spf = SAXParserFactory.newInstance(); + spf.setNamespaceAware(true); + spf.setValidating(true); + + // All XML Readers are required to recognize these two: + spf.setFeature("http://xml.org/sax/features/namespaces", true); + spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true); + + // Other features... + spf.setFeature("http://xml.org/sax/features/validation", true); + spf.setFeature("http://apache.org/xml/features/validation/schema", true); + spf.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); + + this.catalogFileName = catalogFileName; + } + + /* + * Sets the star stellar type query. + * + * @param arg stellar type string, can be a substring. + */ + public TransformerHandler getStellarTypeFilter(String arg) throws TransformerConfigurationException, SAXException, ParserConfigurationException, + IOException { + String stellarType = null; + if (arg != null && arg.length() != 0) { + stellarType = arg; // set value of query + } else { + throw new IllegalArgumentException("\n Stellar type string of length zero found."); + } + + return ffact.newStellarTypeFilter(stellarType); + } + + /* + * Sets the right ascension parameters for a query. Parameters are validated + * to be in the range of 0h and 24h inclusive. + * + * @param min minimum right ascension in hours. + * + * @param max maximum right ascension in hours. + */ + public TransformerHandler getRAFilter(double min, double max) throws TransformerConfigurationException, SAXException, ParserConfigurationException, + IOException { + double raMin = RA_MIN; // hours + double raMax = RA_MAX; // hours + if (min < max) { + if ((min >= RA_MIN && min <= RA_MAX) && (max >= RA_MIN && max <= RA_MAX)) { + raMin = min; // set value of query + raMax = max; // set value of query + + } + } else { + throw new IllegalArgumentException("min must be less than max.\n" + "min=" + min + ", max=" + max); + } + + return ffact.newRAFilter(raMin, raMax); + } + + /* + * Sets the right ascension and dec parameters for a query. Parameters are + * validated to be in the range of ra 0h and 24h and dec -90 to +90 + * inclusive. + * + * @param rmin minimum right ascension in hours. + * + * @param rmax maximum right ascension in hours. + * + * @param dmin minimum declination in degs. + * + * @param dmax maximum declination in degs. + */ + public TransformerHandler getRADECFilter(double rmin, double rmax, double dmin, double dmax) throws TransformerConfigurationException, SAXException, + ParserConfigurationException, IOException { + double raMin = RA_MIN; // hours + double raMax = RA_MAX; // hours + double decMin = DEC_MIN; // degrees + double decMax = DEC_MAX; // degrees + if (rmin < rmax && dmin < dmax) { + if ((rmin >= RA_MIN && rmin <= RA_MAX) && (rmax >= RA_MIN && rmax <= RA_MAX)) { + raMin = rmin; // set value of query + raMax = rmax; // set value of query + } + if ((dmin >= DEC_MIN && dmin <= DEC_MAX) && (dmax >= DEC_MIN && dmax <= DEC_MAX)) { + decMin = dmin; // set value of query + decMax = dmax; // set value of query + } + + } else { + throw new IllegalArgumentException("min must be less than max.\n" + "rmin=" + rmin + ", rmax=" + rmax + ", dmin=" + dmin + ", dmax=" + dmax); + } + + return ffact.newRADECFilter(raMin, raMax, decMin, decMax); + } + + /* + * Sets the declination parameters for a query. Parameters are validated to + * be in the range of -90 and +90 degrees inclusive. + * + * @param min minimum declination in degrees. + * + * @param max maximum declination in degrees. + */ + public TransformerHandler getDecFilter(double min, double max) throws TransformerConfigurationException, SAXException, ParserConfigurationException, + IOException { + double decMin = DEC_MIN; // degrees + double decMax = DEC_MAX; // degrees + if (min < max) { + if ((min >= DEC_MIN && min <= DEC_MAX) && (max >= DEC_MIN && max <= DEC_MAX)) { + decMin = min; // set value of query + decMax = max; // set value of query + } + } else { + throw new IllegalArgumentException("min must be less than max.\n" + "min=" + min + ", max=" + max); + } + + return ffact.newDECFilter(decMin, decMax); + } + + /* + * Runs the filter process against the astronomical database. + * + * @throws Exception + */ + public void process(String outputfile, TransformerHandler... filters) throws Exception { + XMLReader catparser = getXMLReader(); + + File catalogfile = new File(catalogFileName); + InputSource catsrc = isfact.newInputSource(catalogfile.getPath()); + + TransformerHandler outfilter = ffact.newHTMLOutput(); + // create an array from the Vector of filters... + + // hook the filters up to each other, there may be zero filters + int nfilters = filters.length; + if (nfilters != 0) { + TransformerHandler prev = null; + for (int i = 0; i < filters.length; i++) { + TransformerHandler curr = filters[i]; + if (prev != null) { + prev.setResult(new SAXResult(curr)); + } + prev = curr; + } + // hook up the last filter to the output filter + prev.setResult(new SAXResult(outfilter)); + // hook up the catalog parser to the first filter... + catparser.setContentHandler(filters[0]); + } else { + // There are no query filters, + // hook up the catalog parser directly to output filter... + catparser.setContentHandler(outfilter); + } + // hook up the output filter to the output file or std out + if (outputfile != null) { + outfilter.setResult(new StreamResult(outputfile)); + } else { + outfilter.setResult(new StreamResult(System.out)); + } + + catparser.parse(catsrc); + } + + private XMLReader getXMLReader() throws Exception { + SAXParser parser = spf.newSAXParser(); + parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); + parser.setProperty(JAXP_SCHEMA_SOURCE, "catalog.xsd"); + XMLReader catparser = parser.getXMLReader(); + catparser.setErrorHandler(new CatalogErrorHandler()); + return catparser; + } + + /* + * Error Handler for the parsing of the XML astronomical catalog. + */ + private static class CatalogErrorHandler implements ErrorHandler { + private String getParseExceptionInfo(SAXParseException spe) { + String systemId = spe.getSystemId(); + if (systemId == null) { + systemId = "null"; + } + String info = "Catalog URI=" + systemId + " Line=" + spe.getLineNumber() + ": " + spe.getMessage(); + return info; + } + + public void warning(SAXParseException spe) throws SAXException { + String message = "Warning: " + getParseExceptionInfo(spe); + throw new SAXException(message); + } + + public void error(SAXParseException spe) throws SAXException { + String message = "Error: " + getParseExceptionInfo(spe); + throw new SAXException(message); + } + + public void fatalError(SAXParseException spe) throws SAXException { + String message = "Fatal Error: " + getParseExceptionInfo(spe); + throw new SAXException(message); + } + } +} diff --git a/jaxp/test/javax/xml/jaxp/libs/test/astro/DOMFilterFactoryImpl.java b/jaxp/test/javax/xml/jaxp/libs/test/astro/DOMFilterFactoryImpl.java new file mode 100644 index 00000000000..e232fb61fcc --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/test/astro/DOMFilterFactoryImpl.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static test.astro.AstroConstants.DECXSL; +import static test.astro.AstroConstants.RAXSL; +import static test.astro.AstroConstants.STYPEXSL; + +import java.io.IOException; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; + +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +/* + * Implementation of the filter factory interface that utilizes DOM + * sources rather than Stream or SAX sources. This factory utilizes a + * DocumentBuilder to read in the stylesheets and create the DOM used + * to create the filters for the query pipeline. + * + */ +public class DOMFilterFactoryImpl extends SourceFilterFactory { + @Override + protected Source getSource(String xslFileName) throws SAXException, ParserConfigurationException, IOException { + Document document = getStylesheetDOM(xslFileName); + return new DOMSource(document); + } + + + @Override + protected String getRAXsl() { + return RAXSL; + } + + @Override + protected String getDECXsl() { + return DECXSL; + } + + @Override + protected String getRADECXsl() { + return DECXSL; + } + + @Override + protected String getStellarXsl() { + return STYPEXSL; + } + + private Document getStylesheetDOM(String xslfilename) throws SAXException, IOException, ParserConfigurationException { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + return dbf.newDocumentBuilder().parse(filenameToURL(xslfilename)); + } +} diff --git a/jaxp/test/javax/xml/jaxp/libs/test/astro/DOML3InputSourceFactoryImpl.java b/jaxp/test/javax/xml/jaxp/libs/test/astro/DOML3InputSourceFactoryImpl.java new file mode 100644 index 00000000000..6978900344e --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/test/astro/DOML3InputSourceFactoryImpl.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static org.w3c.dom.ls.DOMImplementationLS.MODE_SYNCHRONOUS; +import static org.w3c.dom.traversal.NodeFilter.SHOW_ELEMENT; + +import java.io.ByteArrayInputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.file.Files; +import java.nio.file.Paths; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.w3c.dom.DOMConfiguration; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSInput; +import org.w3c.dom.ls.LSParser; +import org.w3c.dom.ls.LSParserFilter; +import org.w3c.dom.ls.LSSerializer; +import org.w3c.dom.ls.LSSerializerFilter; +import org.xml.sax.InputSource; + +/* + * A specialized implementation of an Input Source factory that utilizes + * DOM Level 3 implementations to build a Document (DOM) from the + * astro input file (XML) and then will serialize the DOM. The serialized DOM + * of the astro input file is then used to create the sax InputSource + * and set it's system id. It is then returned to the caller. + * + */ +public class DOML3InputSourceFactoryImpl implements InputSourceFactory { + public InputSource newInputSource(String filename) throws Exception { + // Create DOMImplementationLS, and DOM L3 LSParser + DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); + DocumentBuilder bldr = fact.newDocumentBuilder(); + DOMImplementationLS impl = (DOMImplementationLS) bldr.getDOMImplementation(); + LSParser domparser = impl.createLSParser(MODE_SYNCHRONOUS, null); + domparser.setFilter(new MyDOMBuilderFilter()); + + // Parse the xml document to create the DOM Document using + // the DOM L3 LSParser and a LSInput (formerly LSInputSource) + Document doc = null; + LSInput src = impl.createLSInput(); + // register the input file with the input source... + String systemId = filenameToURL(filename); + src.setSystemId(systemId); + try (Reader reader = new FileReader(filename)) { + src.setCharacterStream(reader); + src.setEncoding("UTF-8"); + doc = domparser.parse(src); + } + + // Use DOM L3 LSSerializer (previously called a DOMWriter) + // to serialize the xml doc DOM to a file stream. + String tmpCatalog = Files.createTempFile(Paths.get("").toAbsolutePath(), "catalog.xml", null).toString(); + + LSSerializer domserializer = impl.createLSSerializer(); + domserializer.setFilter(new MyDOMWriterFilter()); + domserializer.getNewLine(); + DOMConfiguration config = domserializer.getDomConfig(); + config.setParameter("xml-declaration", Boolean.TRUE); + String result = domserializer.writeToString(doc); + try (FileWriter os = new FileWriter(tmpCatalog, false)) { + os.write(result); + os.flush(); + } + + // Return the Input Source created from the Serialized DOM L3 Document. + InputSource catsrc = new InputSource(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(tmpCatalog))))); + catsrc.setSystemId(systemId); + return catsrc; + } + + /* + * Implementation of a DOM L3 DOM Builder Filter. The filter is capable of + * examining nodes as they are available during the parse. This + * implementation both rejects (filters) and modifies particular nodes + * during the parse of the document. As such, the document in memory will + * become a subset of the document on the stream in accordance with the DOM + * Level 3 Load and Save Specification, v1.0, sect. 1.3 Load Interfaces. + */ + private static class MyDOMBuilderFilter implements LSParserFilter { + + /* + * Filter the DOM. Define element(s) and their children that should be + * efficiently skipped thereby filtering them out of the stream. + */ + @Override + public short startElement(Element e) { + return "_test01".equals(e.getTagName()) ? FILTER_REJECT : FILTER_ACCEPT; + } + + /* + * Modify the DOM 'in situ'. Find a particular Node and change the Node + * value of its child, allow other nodes to pass through unchanged. + */ + @Override + public short acceptNode(Node n) { + String localname = n.getLocalName(); + if (localname.equals("_test-04")) { + Node child = n.getFirstChild(); + String text = child.getNodeValue(); + if (text.equals("T%e!s#t$")) { + child.setNodeValue("T%E!S#T$"); + } + } + return FILTER_ACCEPT; + } + + /* + * Tells the DOMBuilder what types of nodes to show to the filter. + */ + @Override + public int getWhatToShow() { + return SHOW_ELEMENT; + } + } + + /* + * Implementation of a DOM Serializer Filter (previously called a DOM Writer + * Filter) which is a specialization of the NodeFilter interface. + */ + private static class MyDOMWriterFilter implements LSSerializerFilter { + public MyDOMWriterFilter() { + } + + /* + * Must implement method from NodeFilter interface + */ + @Override + public short acceptNode(Node node) { + return FILTER_ACCEPT; + } + + /* + * Tells the DOMBuilder what types of nodes to show to the filter. + */ + @Override + public int getWhatToShow() { + return SHOW_ELEMENT; + } + } +} diff --git a/jaxp/test/javax/xml/jaxp/libs/test/astro/FilterFactory.java b/jaxp/test/javax/xml/jaxp/libs/test/astro/FilterFactory.java new file mode 100644 index 00000000000..3fa8c17fbc2 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/test/astro/FilterFactory.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.TransformerConfigurationException; + +import org.xml.sax.SAXException; + +/* + * Defines the interface for all concrete implementations of a Filter + * Factory. + */ +public interface FilterFactory { + /* + * Allows only the stars between right ascension (R.A.) of min and max to + * pass. Filters out all stars that are not in that range of right + * ascension. Units of right ascension are hours (h), range of parameters is + * 0h to 24h. + * + * @param min minimum R.A. + * + * @param max maxmimum R.A. + */ + TransformerHandler newRAFilter(double min, double max) throws TransformerConfigurationException, SAXException, ParserConfigurationException, IOException; + + /* + * Allows only the stars between declination (DEC) of min and max to pass. + * Filters out all stars that are not in that range of declination. Units of + * declination are degrees (degs), range of parameters is -90 and +90 degs. + * + * @param min minimum DEC + * + * @param max maxmimum DEC + */ + TransformerHandler newDECFilter(double min, double max) throws TransformerConfigurationException, SAXException, ParserConfigurationException, IOException; + + /* + * Combines the usage of newRAFilter and newDECFilter into one. + * + * @param rmin minimum R.A. + * + * @param rmax maxmimum R.A. + * + * @param dmin minimum DEC + * + * @param dmax maxmimum DEC + */ + TransformerHandler newRADECFilter(double rmin, double rmax, double dmin, double dmax) throws TransformerConfigurationException, SAXException, + ParserConfigurationException, IOException; + + TransformerHandler newStellarTypeFilter(String type) throws TransformerConfigurationException, SAXException, ParserConfigurationException, IOException; + + TransformerHandler newHTMLOutput() throws TransformerConfigurationException, SAXException, ParserConfigurationException, IOException; +} diff --git a/jaxp/test/javax/xml/jaxp/libs/test/astro/InputSourceFactory.java b/jaxp/test/javax/xml/jaxp/libs/test/astro/InputSourceFactory.java new file mode 100644 index 00000000000..1d3cb5f78f6 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/test/astro/InputSourceFactory.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import org.xml.sax.InputSource; + +/* + * Interface for all input source factory objects. The default implementation + * 'InputSourceFactoryImpl' is provided as a straight forward factory + * class that creates a new sax input source from a filename. + * + */ +public interface InputSourceFactory { + /* + * Creates a new sax InputSource object from a filename. + * Also sets the system id of the input source. + * @param file filename of the XML input to create the input source. + */ + InputSource newInputSource(String file) throws Exception; +} diff --git a/jdk/test/jdk/lambda/LambdaTranslationInInterface.java b/jaxp/test/javax/xml/jaxp/libs/test/astro/InputSourceFactoryImpl.java similarity index 61% rename from jdk/test/jdk/lambda/LambdaTranslationInInterface.java rename to jaxp/test/javax/xml/jaxp/libs/test/astro/InputSourceFactoryImpl.java index 65d3f07e691..a2c5b8319c8 100644 --- a/jdk/test/jdk/lambda/LambdaTranslationInInterface.java +++ b/jaxp/test/javax/xml/jaxp/libs/test/astro/InputSourceFactoryImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,40 +20,25 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ +package test.astro; -import static org.testng.Assert.assertEquals; -import org.testng.annotations.Test; +import static jaxp.library.JAXPTestUtilities.filenameToURL; -/** - * @author Robert Field +import org.xml.sax.InputSource; + +/* + * Default implementation of a input source factory. This is the most + * straight forward way to create a sax input source and set it's + * system id. + * */ - -interface LTII { - - interface ILsp1 { - String m(); +public class InputSourceFactoryImpl implements InputSourceFactory { + public InputSourceFactoryImpl() { } - interface ILsp2 { - String m(String x); + public InputSource newInputSource(String filename) { + InputSource catSrc = new InputSource(filename); + catSrc.setSystemId(filenameToURL(filename)); + return catSrc; } - - default ILsp1 t1() { - return () -> { return "yo"; }; - } - - default ILsp2 t2() { - return (x) -> { return "snur" + x; }; - } - -} - -@Test -public class LambdaTranslationInInterface implements LTII { - - public void testLambdaInDefaultMethod() { - assertEquals(t1().m(), "yo"); - assertEquals(t2().m("p"), "snurp"); - } - } diff --git a/jaxp/test/javax/xml/jaxp/libs/test/astro/SAXFilterFactoryImpl.java b/jaxp/test/javax/xml/jaxp/libs/test/astro/SAXFilterFactoryImpl.java new file mode 100644 index 00000000000..4ef5d3cc259 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/test/astro/SAXFilterFactoryImpl.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static test.astro.AstroConstants.DECENTXSL; +import static test.astro.AstroConstants.DECXSL; +import static test.astro.AstroConstants.RAENTXSL; +import static test.astro.AstroConstants.STYPEXSL; +import static test.astro.AstroConstants.TOPTEMPLXSL; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.Source; +import javax.xml.transform.sax.SAXSource; + +import org.xml.sax.EntityResolver; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; + +/* + * Implementation of the filter factory interface that utilizes SAX + * sources rather than Stream sources. This factory utilizes a + * SAX parser factory and XMLReader to read in the stylesheets used + * to create the filters for the query pipeline. + * The XMLReader has been equipped with an entity resolver + * SAXFilterFactoryEntityResolver, it is used to resolve external + * entities in two specialized stylesheets, ra-ent.xsl (derived from + * ra.xsl) and dec-ent.xsl (derived from dec.xsl). + * + */ +public class SAXFilterFactoryImpl extends SourceFilterFactory { + private EntityResolver entityResolver; + + public SAXFilterFactoryImpl() { + super(); + entityResolver = new SAXFilterFactoryEntityResolver(); + } + + @Override + protected Source getSource(String xslFileName) throws SAXException, ParserConfigurationException { + SAXSource saxsource = new SAXSource(new InputSource(filenameToURL(xslFileName))); + saxsource.setXMLReader(getXMLReader()); + return saxsource; + } + + @Override + protected String getRAXsl() { + return RAENTXSL; + } + + @Override + protected String getDECXsl() { + return DECENTXSL; + } + + @Override + protected String getRADECXsl() { + return DECXSL; + } + + @Override + protected String getStellarXsl() { + return STYPEXSL; + } + + /* + * Entity resolver implementation that is used in the SAXFilterFactory + * implementation for handling external entities that appear in two + * specialized stylesheets, 'ra-ent.xsl' and 'dec-ent.xsl'. Both of these + * stylesheets contain an external entity reference to the top level + * stylesheet template, which is stored in a separate file, + * 'toptemplate.xsl'. + */ + private static class SAXFilterFactoryEntityResolver implements EntityResolver { + public InputSource resolveEntity(String publicid, String sysId) { + if (sysId.equals("http://astro.com/stylesheets/toptemplate")) { + InputSource retval = new InputSource(TOPTEMPLXSL); + retval.setSystemId(filenameToURL(TOPTEMPLXSL)); + return retval; + } else { + return null; // use default behavior + } + } + } + + private XMLReader getXMLReader() throws SAXException, ParserConfigurationException { + SAXParserFactory pfactory = SAXParserFactory.newInstance(); + pfactory.setNamespaceAware(true); + // pfactory.setValidating(true); + XMLReader xmlreader = pfactory.newSAXParser().getXMLReader(); + // entity resolver is used in stylesheets ra-ent.xsl, + // dec-ent.xsl. Other stylehsheets will not use it + // since they do not contain ext entities. + xmlreader.setEntityResolver(entityResolver); + return xmlreader; + } +} diff --git a/jaxp/test/javax/xml/jaxp/libs/test/astro/SourceFilterFactory.java b/jaxp/test/javax/xml/jaxp/libs/test/astro/SourceFilterFactory.java new file mode 100644 index 00000000000..1bddec62158 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/test/astro/SourceFilterFactory.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Source; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; + +import org.xml.sax.SAXException; + +public abstract class SourceFilterFactory extends AbstractFilterFactory { + @Override + protected TransformerHandler getTransformerHandler(String xslFileName) throws SAXException, ParserConfigurationException, + TransformerConfigurationException, IOException { + return getFactory().newTransformerHandler(getSource(xslFileName)); + } + + abstract protected Source getSource(String xslFileName) throws SAXException, ParserConfigurationException, IOException; + + private SAXTransformerFactory getFactory() { + return (SAXTransformerFactory) TransformerFactory.newInstance(); + } +} diff --git a/jaxp/test/javax/xml/jaxp/libs/test/astro/StreamFilterFactoryImpl.java b/jaxp/test/javax/xml/jaxp/libs/test/astro/StreamFilterFactoryImpl.java new file mode 100644 index 00000000000..0978161312e --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/test/astro/StreamFilterFactoryImpl.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static test.astro.AstroConstants.DECXSL; +import static test.astro.AstroConstants.RADECXSL; +import static test.astro.AstroConstants.RAXSL; +import static test.astro.AstroConstants.STYPEXSL; + +import javax.xml.transform.Source; +import javax.xml.transform.stream.StreamSource; + +public class StreamFilterFactoryImpl extends SourceFilterFactory { + @Override + protected Source getSource(String xslFileName) { + return new StreamSource(filenameToURL(xslFileName)); + } + + @Override + protected String getRAXsl() { + return RAXSL; + } + + @Override + protected String getDECXsl() { + return DECXSL; + } + + @Override + protected String getRADECXsl() { + return RADECXSL; + } + + @Override + protected String getStellarXsl() { + return STYPEXSL; + } +} diff --git a/jaxp/test/javax/xml/jaxp/libs/test/astro/TemplatesFilterFactoryImpl.java b/jaxp/test/javax/xml/jaxp/libs/test/astro/TemplatesFilterFactoryImpl.java new file mode 100644 index 00000000000..09a71b1a534 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/libs/test/astro/TemplatesFilterFactoryImpl.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 test.astro; + +import static jaxp.library.JAXPTestUtilities.filenameToURL; +import static test.astro.AstroConstants.DECXSL; +import static test.astro.AstroConstants.RAURIXSL; +import static test.astro.AstroConstants.STYPEXSL; +import static test.astro.AstroConstants.TOPTEMPLINCXSL; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.Source; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.URIResolver; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TemplatesHandler; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamSource; + +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; + +/* + * Implementation of the filter factory interface that utilizes + * a TemplatesHandler and creates Templates from the stylesheets. + * The Templates objects are then used to create a TransformerHandler + * a.k.a Filter which is returned to the caller. + * This factory uses a Uri resolver which is registered with the + * Transformer factory. + * + */ +public class TemplatesFilterFactoryImpl extends AbstractFilterFactory { + private final URIResolver uriResolver = new TemplatesFilterFactoryURIResolver(); + + @Override + protected String getRAXsl() { + return RAURIXSL; + } + + @Override + protected String getDECXsl() { + return DECXSL; + } + + @Override + protected String getRADECXsl() { + return DECXSL; + } + + @Override + protected String getStellarXsl() { + return STYPEXSL; + } + + @Override + protected TransformerHandler getTransformerHandler(String xslFileName) throws SAXException, ParserConfigurationException, + TransformerConfigurationException, IOException { + SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance(); + factory.setURIResolver(uriResolver); + + TemplatesHandler templatesHandler = factory.newTemplatesHandler(); + + SAXParserFactory pFactory = SAXParserFactory.newInstance(); + pFactory.setNamespaceAware(true); + + XMLReader xmlreader = pFactory.newSAXParser().getXMLReader(); + + // create the stylesheet input source + InputSource xslSrc = new InputSource(xslFileName); + + xslSrc.setSystemId(filenameToURL(xslFileName)); + // hook up the templates handler as the xsl content handler + xmlreader.setContentHandler(templatesHandler); + // call parse on the xsl input source + + xmlreader.parse(xslSrc); + + // extract the Templates object created from the xsl input source + return factory.newTransformerHandler(templatesHandler.getTemplates()); + } + + /* + * Uri resolver used to resolve stylesheet used by the Templates filter + * factory. + */ + private static class TemplatesFilterFactoryURIResolver implements URIResolver { + public Source resolve(String href, String base) throws TransformerException { + if ("http://astro.com/stylesheets/topleveltemplate".equals(href)) { + StreamSource ss = new StreamSource(TOPTEMPLINCXSL); + ss.setSystemId(filenameToURL(TOPTEMPLINCXSL)); + return ss; + } else { + return null; + } + } + } +} diff --git a/jaxp/test/javax/xml/jaxp/unittest/javax/xml/parsers/Bug8073385.java b/jaxp/test/javax/xml/jaxp/unittest/javax/xml/parsers/Bug8073385.java new file mode 100644 index 00000000000..1d3aa66ce08 --- /dev/null +++ b/jaxp/test/javax/xml/jaxp/unittest/javax/xml/parsers/Bug8073385.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javax.xml.parsers; + +import java.io.StringReader; +import java.util.Locale; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.DocumentBuilder; +import org.xml.sax.SAXException; +import org.xml.sax.InputSource; + +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import static org.testng.Assert.assertTrue; + +/** + * @bug 8073385 + * @summary test that invalid XML character exception string contains + * information about character value, element and attribute names + */ +public class Bug8073385 { + + private Locale defLoc; + + @BeforeClass + private void setup() { + defLoc = Locale.getDefault(); + Locale.setDefault(Locale.ENGLISH); + } + + @AfterClass + private void cleanup() { + Locale.setDefault(defLoc); + } + + @DataProvider(name = "illegalCharactersData") + public static Object[][] illegalCharactersData() { + return new Object[][]{ + {0x00}, + {0xFFFE}, + {0xFFFF} + }; + } + + @Test(dataProvider = "illegalCharactersData") + public void test(int character) throws Exception { + // Construct the XML document as a String + int[] cps = new int[]{character}; + String txt = new String(cps, 0, cps.length); + String inxml = ""; + String exceptionText = "NO EXCEPTION OBSERVED"; + String hexString = "0x" + Integer.toHexString(character); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setValidating(false); + DocumentBuilder db = dbf.newDocumentBuilder(); + InputSource isrc = new InputSource(new StringReader(inxml)); + + try { + db.parse(isrc); + } catch (SAXException e) { + exceptionText = e.toString(); + } + System.out.println("Got Exception:" + exceptionText); + assertTrue(exceptionText.contains("attribute \"attTest\"")); + assertTrue(exceptionText.contains("element is \"topElement\"")); + assertTrue(exceptionText.contains("Unicode: " + hexString)); + } +} diff --git a/jdk/test/jdk/lambda/LambdaTranslationInnerConstructor.java b/jaxp/test/javax/xml/jaxp/unittest/org/w3c/dom/DOMXPathTest.java similarity index 54% rename from jdk/test/jdk/lambda/LambdaTranslationInnerConstructor.java rename to jaxp/test/javax/xml/jaxp/unittest/org/w3c/dom/DOMXPathTest.java index 17e6ad1451f..fa92dc7175b 100644 --- a/jdk/test/jdk/lambda/LambdaTranslationInnerConstructor.java +++ b/jaxp/test/javax/xml/jaxp/unittest/org/w3c/dom/DOMXPathTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,51 +20,29 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ +package org.w3c.dom; -import static org.testng.Assert.assertEquals; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.testng.Assert; import org.testng.annotations.Test; -/** - * @author Robert Field +/* + * @bug 8042244 + * @summary Verifies that the experimental DOM L3 XPath implementation is no longer available. */ +public class DOMXPathTest { + /* + Verifies that DOMImplementation::hasFeature returns false and getFeature + returns null for DOM L3 XPath. + */ + @Test + public void test() throws ParserConfigurationException { + DOMImplementation domImpl = DocumentBuilderFactory.newInstance() + .newDocumentBuilder() + .getDOMImplementation(); -@Test -public class LambdaTranslationInnerConstructor { - - public void testLambdaWithInnerConstructor() { - assertEquals(seq1().m().toString(), "Cbl:nada"); - assertEquals(seq2().m("rats").toString(), "Cbl:rats"); + Assert.assertFalse(domImpl.hasFeature("+XPath", "3.0")); + Assert.assertEquals(domImpl.getFeature("+XPath", "3.0"), null); } - - Ib1 seq1() { - return () -> { return new Cbl(); }; - } - - Ib2 seq2() { - return (x) -> { return new Cbl(x); }; - } - - class Cbl { - String val; - - Cbl() { - this.val = "nada"; - } - - Cbl(String z) { - this.val = z; - } - - public String toString() { - return "Cbl:" + val; - } - } - - interface Ib1 { - Object m(); - } - - interface Ib2 { - Object m(String x); - } -} \ No newline at end of file +} diff --git a/jdk/test/jdk/lambda/MethodReferenceTestSueCase1.java b/jaxp/test/javax/xml/jaxp/unittest/org/w3c/dom/JdkXmlDomTest.java similarity index 65% rename from jdk/test/jdk/lambda/MethodReferenceTestSueCase1.java rename to jaxp/test/javax/xml/jaxp/unittest/org/w3c/dom/JdkXmlDomTest.java index b6bbfa68d63..b65b4fd6bff 100644 --- a/jdk/test/jdk/lambda/MethodReferenceTestSueCase1.java +++ b/jaxp/test/javax/xml/jaxp/unittest/org/w3c/dom/JdkXmlDomTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,27 +20,21 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ +package org.w3c.dom; - +import org.testng.Assert; import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; - -/** - * @author Robert Field +/* + * @bug 8078139 + * @summary Verifies that jdk.xml.dom classes are loaded by the ext class loader. */ +public class JdkXmlDomTest { + @Test + public void test() throws ClassNotFoundException { + ClassLoader cl = ClassLoader.getSystemClassLoader().getParent(); + Class cls = Class.forName("org.w3c.dom.xpath.XPathEvaluator", false, cl); -@Test -public class MethodReferenceTestSueCase1 { - - public interface Sam2 { public String get(T target, String s); } - - String instanceMethod(String s) { return "2"; } - Sam2 var = MethodReferenceTestSueCase1::instanceMethod; - - String m() { return var.get(new MethodReferenceTestSueCase1(), ""); } - - public void testSueCase1() { - assertEquals(m(), "2"); + Assert.assertTrue(cls.getClassLoader() != null); } -} \ No newline at end of file +} diff --git a/jaxws/.hgtags b/jaxws/.hgtags index cacd4546124..fe7dbe8df69 100644 --- a/jaxws/.hgtags +++ b/jaxws/.hgtags @@ -301,3 +301,10 @@ bb9cf97a5ac6aa1aa2a1034676d64413071f58ea jdk9-b51 b8fbe40efa97fe0753076ccc6dfc50747c7877d0 jdk9-b53 83a0cf0e08788c33872e1fe3e87bf9a0d1e59eaa jdk9-b54 ca481b0492c82cc38fa0e6b746305ed88c26b4fd jdk9-b55 +b4f913b48e699980bd11fe19cce134d0adb4c31c jdk9-b56 +17c4241395e97312bd75e7acd693ffcdd41ae993 jdk9-b57 +1e06b36bb396c0495e0774f1c6b0356d03847659 jdk9-b58 +8a9ebae410bc388668fc203e559b5407bde757eb jdk9-b59 +f31835b59035377a220efc5a248b90f090ee1689 jdk9-b60 +77f44848c44c003205490bf5ab88035233b65418 jdk9-b61 +cd0cf72b2cbf4adb778a02505fb065bb2292688c jdk9-b62 diff --git a/jaxws/src/java.activation/share/classes/javax/activation/ActivationDataFlavor.java b/jaxws/src/java.activation/share/classes/javax/activation/ActivationDataFlavor.java index 41979db6b85..c4836e4d0a7 100644 --- a/jaxws/src/java.activation/share/classes/javax/activation/ActivationDataFlavor.java +++ b/jaxws/src/java.activation/share/classes/javax/activation/ActivationDataFlavor.java @@ -31,10 +31,10 @@ import javax.activation.MimeType; /** * The ActivationDataFlavor class is a special subclass of - * java.awt.datatransfer.DataFlavor. It allows the JAF to + * {@code java.awt.datatransfer.DataFlavor}. It allows the JAF to * set all three values stored by the DataFlavor class via a new - * constructor. It also contains improved MIME parsing in the equals - * method. Except for the improved parsing, its semantics are + * constructor. It also contains improved MIME parsing in the {@code equals} + * method. Except for the improved parsing, its semantics are * identical to that of the JDK's DataFlavor class. * * @since 1.6 @@ -70,7 +70,6 @@ public class ActivationDataFlavor extends DataFlavor { * representationClass = representationClass
                            * mimeType = mimeType
                            * humanName = humanName - *

                            * * @param representationClass the class used in this DataFlavor * @param mimeType the MIME type of the data represented by this class @@ -98,7 +97,7 @@ public class ActivationDataFlavor extends DataFlavor { * otherwise: *

                            * representationClass = InputStream

                            - * mimeType = mimeType

                            + * mimeType = mimeType * * @param representationClass the class used in this DataFlavor * @param humanPresentableName the human presentable name of the flavor @@ -175,7 +174,7 @@ public class ActivationDataFlavor extends DataFlavor { /** * Compares the DataFlavor passed in with this DataFlavor; calls - * the isMimeTypeEqual method. + * the {@code isMimeTypeEqual} method. * * @param dataFlavor the DataFlavor to compare with * @return true if the MIME type and representation class diff --git a/jaxws/src/java.activation/share/classes/javax/activation/CommandInfo.java b/jaxws/src/java.activation/share/classes/javax/activation/CommandInfo.java index 92db2568ac0..b8dfd8b7091 100644 --- a/jaxws/src/java.activation/share/classes/javax/activation/CommandInfo.java +++ b/jaxws/src/java.activation/share/classes/javax/activation/CommandInfo.java @@ -85,10 +85,10 @@ public class CommandInfo { * Return the instantiated JavaBean component. *

                            * Begin by instantiating the component with - * Beans.instantiate(). + * {@code Beans.instantiate()}. *

                            - * If the bean implements the javax.activation.CommandObject - * interface, call its setCommandContext method. + * If the bean implements the {@code javax.activation.CommandObject} + * interface, call its {@code setCommandContext} method. *

                            * If the DataHandler parameter is null, then the bean is * instantiated with no data. NOTE: this may be useful @@ -102,7 +102,7 @@ public class CommandInfo { * this method will check if it implements the * java.io.Externalizable interface. If it does, the bean's * readExternal method will be called if an InputStream - * can be acquired from the DataHandler.

                            + * can be acquired from the DataHandler. * * @param dh The DataHandler that describes the data to be * passed to the command. diff --git a/jaxws/src/java.activation/share/classes/javax/activation/CommandMap.java b/jaxws/src/java.activation/share/classes/javax/activation/CommandMap.java index acc194b5248..16e18ca5ff8 100644 --- a/jaxws/src/java.activation/share/classes/javax/activation/CommandMap.java +++ b/jaxws/src/java.activation/share/classes/javax/activation/CommandMap.java @@ -46,7 +46,6 @@ public abstract class CommandMap { /** * Get the default CommandMap. - *

                            * *

                              *
                            • In cases where a CommandMap instance has been previously set @@ -54,7 +53,7 @@ public abstract class CommandMap { * return the CommandMap. *
                            • * In cases where no CommandMap has been set, the CommandMap - * creates an instance of MailcapCommandMap and + * creates an instance of {@code MailcapCommandMap} and * set that to the default, returning its value. * *
                            @@ -77,7 +76,7 @@ public abstract class CommandMap { /** * Set the default CommandMap. Reset the CommandMap to the default by - * calling this method with null. + * calling this method with {@code null}. * * @param commandMap The new default CommandMap. * @exception SecurityException if the caller doesn't have permission @@ -118,10 +117,10 @@ public abstract class CommandMap { * Get the preferred command list from a MIME Type. The actual semantics * are determined by the implementation of the CommandMap.

                            * - * The DataSource provides extra information, such as + * The {@code DataSource} provides extra information, such as * the file name, that a CommandMap implementation may use to further * refine the list of commands that are returned. The implementation - * in this class simply calls the getPreferredCommands + * in this class simply calls the {@code getPreferredCommands} * method that ignores this argument. * * @param mimeType the MIME type @@ -146,10 +145,10 @@ public abstract class CommandMap { * Get all the available commands for this type. This method * should return all the possible commands for this MIME type.

                            * - * The DataSource provides extra information, such as + * The {@code DataSource} provides extra information, such as * the file name, that a CommandMap implementation may use to further * refine the list of commands that are returned. The implementation - * in this class simply calls the getAllCommands + * in this class simply calls the {@code getAllCommands} * method that ignores this argument. * * @param mimeType the MIME type @@ -173,10 +172,10 @@ public abstract class CommandMap { /** * Get the default command corresponding to the MIME type.

                            * - * The DataSource provides extra information, such as + * The {@code DataSource} provides extra information, such as * the file name, that a CommandMap implementation may use to further * refine the command that is chosen. The implementation - * in this class simply calls the getCommand + * in this class simply calls the {@code getCommand} * method that ignores this argument. * * @param mimeType the MIME type @@ -206,10 +205,10 @@ public abstract class CommandMap { * The mechanism and semantics for determining this are determined * by the implementation of the particular CommandMap.

                            * - * The DataSource provides extra information, such as + * The {@code DataSource} provides extra information, such as * the file name, that a CommandMap implementation may use to further * refine the choice of DataContentHandler. The implementation - * in this class simply calls the createDataContentHandler + * in this class simply calls the {@code createDataContentHandler} * method that ignores this argument. * * @param mimeType the MIME type diff --git a/jaxws/src/java.activation/share/classes/javax/activation/CommandObject.java b/jaxws/src/java.activation/share/classes/javax/activation/CommandObject.java index 01602e8a92f..7dda0239819 100644 --- a/jaxws/src/java.activation/share/classes/javax/activation/CommandObject.java +++ b/jaxws/src/java.activation/share/classes/javax/activation/CommandObject.java @@ -34,7 +34,7 @@ import java.io.IOException; * data they should operate on. JavaBeans that don't implement * this interface may be used as well. Such commands may obtain * the data using the Externalizable interface, or using an - * application-specific method.

                            + * application-specific method. * * @since 1.6 */ @@ -44,7 +44,7 @@ public interface CommandObject { * Initialize the Command with the verb it is requested to handle * and the DataHandler that describes the data it will * operate on. NOTE: it is acceptable for the caller - * to pass null as the value for DataHandler. + * to pass null as the value for {@code DataHandler}. * * @param verb The Command Verb this object refers to. * @param dh The DataHandler. diff --git a/jaxws/src/java.activation/share/classes/javax/activation/DataHandler.java b/jaxws/src/java.activation/share/classes/javax/activation/DataHandler.java index 6fef9302a83..27f72484f69 100644 --- a/jaxws/src/java.activation/share/classes/javax/activation/DataHandler.java +++ b/jaxws/src/java.activation/share/classes/javax/activation/DataHandler.java @@ -54,11 +54,11 @@ import java.awt.datatransfer.UnsupportedFlavorException; * * DataHandler and CommandMaps

                            * The DataHandler keeps track of the current CommandMap that it uses to - * service requests for commands (getCommand, - * getAllCommands, getPreferredCommands). + * service requests for commands ({@code getCommand, getAllCommands, + * getPreferredCommands}). * Each instance of a DataHandler may have a CommandMap associated with - * it using the setCommandMap method. If a CommandMap was - * not set, DataHandler calls the getDefaultCommandMap + * it using the {@code setCommandMap} method. If a CommandMap was + * not set, DataHandler calls the {@code getDefaultCommandMap} * method in CommandMap and uses the value it returns. See * CommandMap for more information.

                            * @@ -105,7 +105,7 @@ public class DataHandler implements Transferable { private String shortType = null; /** - * Create a DataHandler instance referencing the + * Create a {@code DataHandler} instance referencing the * specified DataSource. The data exists in a byte stream form. * The DataSource will provide an InputStream to access the data. * @@ -118,7 +118,7 @@ public class DataHandler implements Transferable { } /** - * Create a DataHandler instance representing an object + * Create a {@code DataHandler} instance representing an object * of this MIME type. This constructor is * used when the application already has an in-memory representation * of the data in the form of a Java Object. @@ -133,8 +133,8 @@ public class DataHandler implements Transferable { } /** - * Create a DataHandler instance referencing a URL. - * The DataHandler internally creates a URLDataSource + * Create a {@code DataHandler} instance referencing a URL. + * The DataHandler internally creates a {@code URLDataSource} * instance to represent the URL. * * @param url a URL object @@ -181,7 +181,7 @@ public class DataHandler implements Transferable { /** * Return the name of the data object. If this DataHandler * was created with a DataSource, this method calls through - * to the DataSource.getName method, otherwise it + * to the {@code DataSource.getName} method, otherwise it * returns null. * * @return the name of the object @@ -211,7 +211,7 @@ public class DataHandler implements Transferable { * Get the InputStream for this object.

                            * * For DataHandlers instantiated with a DataSource, the DataHandler - * calls the DataSource.getInputStream method and + * calls the {@code DataSource.getInputStream} method and * returns the result to the caller. *

                            * For DataHandlers instantiated with an Object, the DataHandler @@ -219,11 +219,11 @@ public class DataHandler implements Transferable { * the DataHandler can not find a DataContentHandler for this MIME * type, it throws an UnsupportedDataTypeException. If it is * successful, it creates a pipe and a thread. The thread uses the - * DataContentHandler's writeTo method to write the + * DataContentHandler's {@code writeTo} method to write the * stream data into one end of the pipe. The other end of the pipe * is returned to the caller. Because a thread is created to copy * the data, IOExceptions that may occur during the copy can not be - * propagated back to the caller. The result is an empty stream.

                            + * propagated back to the caller. The result is an empty stream. * * @return the InputStream representing this data * @exception IOException if an I/O error occurs @@ -281,7 +281,7 @@ public class DataHandler implements Transferable { } /** - * Write the data to an OutputStream.

                            + * Write the data to an {@code OutputStream}.

                            * * If the DataHandler was created with a DataSource, writeTo * retrieves the InputStream and copies the bytes from the @@ -290,7 +290,7 @@ public class DataHandler implements Transferable { * If the DataHandler was created with an object, writeTo * retrieves the DataContentHandler for the object's type. * If the DataContentHandler was found, it calls the - * writeTo method on the DataContentHandler. + * {@code writeTo} method on the {@code DataContentHandler}. * * @param os the OutputStream to write to * @exception IOException if an I/O error occurs @@ -322,8 +322,8 @@ public class DataHandler implements Transferable { * Get an OutputStream for this DataHandler to allow overwriting * the underlying data. * If the DataHandler was created with a DataSource, the - * DataSource's getOutputStream method is called. - * Otherwise, null is returned. + * DataSource's {@code getOutputStream} method is called. + * Otherwise, {@code null} is returned. * * @return the OutputStream * @@ -348,12 +348,12 @@ public class DataHandler implements Transferable { * The DataHandler attempts to find a DataContentHandler that * corresponds to the MIME type of the data. If one is located, * the DataHandler calls the DataContentHandler's - * getTransferDataFlavors method.

                            + * {@code getTransferDataFlavors} method.

                            * * If a DataContentHandler can not be located, and if the * DataHandler was created with a DataSource (or URL), one * DataFlavor is returned that represents this object's MIME type - * and the java.io.InputStream class. If the + * and the {@code java.io.InputStream} class. If the * DataHandler was created with an object and a MIME type, * getTransferDataFlavors returns one DataFlavor that represents * this object's MIME type and the object's class. @@ -381,7 +381,7 @@ public class DataHandler implements Transferable { * for this object.

                            * * This method iterates through the DataFlavors returned from - * getTransferDataFlavors, comparing each with + * {@code getTransferDataFlavors}, comparing each with * the specified flavor. * * @param flavor the requested flavor for the data @@ -407,10 +407,10 @@ public class DataHandler implements Transferable { * * The DataHandler attempts to locate a DataContentHandler * for this MIME type. If one is found, the passed in DataFlavor - * and the type of the data are passed to its getTransferData + * and the type of the data are passed to its {@code getTransferData} * method. If the DataHandler fails to locate a DataContentHandler * and the flavor specifies this object's MIME type and the - * java.io.InputStream class, this object's InputStream + * {@code java.io.InputStream} class, this object's InputStream * is returned. * Otherwise it throws an UnsupportedFlavorException.

                            * @@ -438,10 +438,10 @@ public class DataHandler implements Transferable { /** * Set the CommandMap for use by this DataHandler. - * Setting it to null causes the CommandMap to revert + * Setting it to {@code null} causes the CommandMap to revert * to the CommandMap returned by the - * CommandMap.getDefaultCommandMap method. - * Changing the CommandMap, or setting it to null, + * {@code CommandMap.getDefaultCommandMap} method. + * Changing the CommandMap, or setting it to {@code null}, * clears out any data cached from the previous CommandMap. * * @param commandMap the CommandMap to use in this DataHandler @@ -460,7 +460,7 @@ public class DataHandler implements Transferable { /** * Return the preferred commands for this type of data. - * This method calls the getPreferredCommands method + * This method calls the {@code getPreferredCommands} method * in the CommandMap associated with this instance of DataHandler. * This method returns an array that represents a subset of * available commands. In cases where multiple commands for the @@ -484,7 +484,7 @@ public class DataHandler implements Transferable { * This method returns an array containing all commands * for the type of data represented by this DataHandler. The * MIME type for the underlying data represented by this DataHandler - * is used to call through to the getAllCommands method + * is used to call through to the {@code getAllCommands} method * of the CommandMap associated with this DataHandler. * * @return the CommandInfo objects representing all the commands @@ -502,7 +502,7 @@ public class DataHandler implements Transferable { * Get the command cmdName. Use the search semantics as * defined by the CommandMap installed in this DataHandler. The * MIME type for the underlying data represented by this DataHandler - * is used to call through to the getCommand method + * is used to call through to the {@code getCommand} method * of the CommandMap associated with this DataHandler. * * @param cmdName the command name @@ -527,7 +527,7 @@ public class DataHandler implements Transferable { * If the DataHandler was instantiated with a DataSource, * this method uses a DataContentHandler to return the content * object for the data represented by this DataHandler. If no - * DataContentHandler can be found for the + * {@code DataContentHandler} can be found for the * the type of this data, the DataHandler returns an * InputStream for the data. * @@ -547,9 +547,9 @@ public class DataHandler implements Transferable { * and instantiates the corresponding command, usually * a JavaBean component. *

                            - * This method calls the CommandInfo's getCommandObject - * method with the ClassLoader used to load - * the javax.activation.DataHandler class itself. + * This method calls the CommandInfo's {@code getCommandObject} + * method with the {@code ClassLoader} used to load + * the {@code javax.activation.DataHandler} class itself. * * @param cmdinfo the CommandInfo corresponding to a command * @return the instantiated command object @@ -701,16 +701,16 @@ class DataHandlerDataSource implements DataSource { } /** - * Returns an InputStream representing this object. - * @return the InputStream + * Returns an {@code InputStream} representing this object. + * @return the {@code InputStream} */ public InputStream getInputStream() throws IOException { return dataHandler.getInputStream(); } /** - * Returns the OutputStream for this object. - * @return the OutputStream + * Returns the {@code OutputStream} for this object. + * @return the {@code OutputStream} */ public OutputStream getOutputStream() throws IOException { return dataHandler.getOutputStream(); @@ -754,7 +754,7 @@ class DataSourceDataContentHandler implements DataContentHandler { } /** - * Return the DataFlavors for this DataContentHandler. + * Return the DataFlavors for this {@code DataContentHandler}. * @return the DataFlavors */ public DataFlavor[] getTransferDataFlavors() { @@ -842,7 +842,7 @@ class ObjectDataContentHandler implements DataContentHandler { } /** - * Return the DataFlavors for this DataContentHandler. + * Return the DataFlavors for this {@code DataContentHandler}. * @return the DataFlavors */ public synchronized DataFlavor[] getTransferDataFlavors() { diff --git a/jaxws/src/java.activation/share/classes/javax/activation/MailcapCommandMap.java b/jaxws/src/java.activation/share/classes/javax/activation/MailcapCommandMap.java index 7d13a9b506f..dd7530c3121 100644 --- a/jaxws/src/java.activation/share/classes/javax/activation/MailcapCommandMap.java +++ b/jaxws/src/java.activation/share/classes/javax/activation/MailcapCommandMap.java @@ -45,14 +45,13 @@ import com.sun.activation.registries.LogSupport; * system for mailcap file entries. When requests are made * to search for commands in the MailcapCommandMap, it searches * mailcap files in the following order: - *

                            *

                              *
                            1. Programatically added entries to the MailcapCommandMap instance. - *
                            2. The file .mailcap in the user's home directory. - *
                            3. The file <java.home>/lib/mailcap. - *
                            4. The file or resources named META-INF/mailcap. - *
                            5. The file or resource named META-INF/mailcap.default - * (usually found only in the activation.jar file). + *
                            6. The file {@code .mailcap} in the user's home directory. + *
                            7. The file {@literal <}java.home{@literal >}{@code /lib/mailcap}. + *
                            8. The file or resources named {@code META-INF/mailcap}. + *
                            9. The file or resource named {@code META-INF/mailcap.default} + * (usually found only in the {@code activation.jar} file). *
                            *

                            * Mailcap file format:

                            @@ -70,46 +69,43 @@ import com.sun.activation.registries.LogSupport; * * When a mailcap file is * parsed, the MailcapCommandMap recognizes certain parameter signatures, - * specifically those parameter names that begin with x-java-. + * specifically those parameter names that begin with {@code x-java-}. * The MailcapCommandMap uses this signature to find * command entries for inclusion into its registries. - * Parameter names with the form x-java-<name> + * Parameter names with the form {@code x-java-} * are read by the MailcapCommandMap as identifying a command - * with the name name. When the name is - * content-handler the MailcapCommandMap recognizes the class + * with the name name. When the name is {@code + * content-handler} the MailcapCommandMap recognizes the class * signified by this parameter as a DataContentHandler. * All other commands are handled generically regardless of command * name. The command implementation is specified by a fully qualified * class name of a JavaBean(tm) component. For example; a command for viewing - * some data can be specified as: x-java-view=com.foo.ViewBean.

                            + * some data can be specified as: {@code x-java-view=com.foo.ViewBean}.

                            * - * When the command name is fallback-entry, the value of - * the command may be true or false. An + * When the command name is {@code fallback-entry}, the value of + * the command may be {@code true} or {@code false}. An * entry for a MIME type that includes a parameter of - * x-java-fallback-entry=true defines fallback commands + * {@code x-java-fallback-entry=true} defines fallback commands * for that MIME type that will only be used if no non-fallback entry - * can be found. For example, an entry of the form text/*; ; - * x-java-fallback-entry=true; x-java-view=com.sun.TextViewer + * can be found. For example, an entry of the form {@code text/*; ; + * x-java-fallback-entry=true; x-java-view=com.sun.TextViewer} * specifies a view command to be used for any text MIME type. This * view command would only be used if a non-fallback view command for * the MIME type could not be found.

                            * * MailcapCommandMap aware mailcap files have the - * following general form:

                            - * - * # Comments begin with a '#' and continue to the end of the line.
                            - * <mime type>; ; <parameter list>
                            - * # Where a parameter list consists of one or more parameters,
                            - * # where parameters look like: x-java-view=com.sun.TextViewer
                            - * # and a parameter list looks like:
                            + * following general form: + *

                            {@code
                            + * # Comments begin with a '#' and continue to the end of the line.
                            + * ; ; 
                            + * # Where a parameter list consists of one or more parameters,
                            + * # where parameters look like: x-java-view=com.sun.TextViewer
                            + * # and a parameter list looks like:
                              * text/plain; ; x-java-view=com.sun.TextViewer; x-java-edit=com.sun.TextEdit
                            - * 
                            - * # Note that mailcap entries that do not contain 'x-java' parameters
                            - * # and comply to RFC 1524 are simply ignored:
                            - * image/gif; /usr/dt/bin/sdtimage %s
                            - * - *
                            - *

                            + * # Note that mailcap entries that do not contain 'x-java' parameters + * # and comply to RFC 1524 are simply ignored: + * image/gif; /usr/dt/bin/sdtimage %s + * }

                            * * @author Bart Calder * @author Bill Shannon @@ -451,7 +447,7 @@ public class MailcapCommandMap extends CommandMap { } /** - * Get the command corresponding to cmdName for the MIME type. + * Get the command corresponding to {@code cmdName} for the MIME type. * * @param mimeType the MIME type * @param cmdName the command name diff --git a/jaxws/src/java.activation/share/classes/javax/activation/MimetypesFileTypeMap.java b/jaxws/src/java.activation/share/classes/javax/activation/MimetypesFileTypeMap.java index fca50572047..430b43b1ed7 100644 --- a/jaxws/src/java.activation/share/classes/javax/activation/MimetypesFileTypeMap.java +++ b/jaxws/src/java.activation/share/classes/javax/activation/MimetypesFileTypeMap.java @@ -33,33 +33,32 @@ import com.sun.activation.registries.LogSupport; /** * This class extends FileTypeMap and provides data typing of files - * via their file extension. It uses the .mime.types format.

                            + * via their file extension. It uses the {@code .mime.types} format.

                            * * MIME types file search order:

                            * The MimetypesFileTypeMap looks in various places in the user's * system for MIME types file entries. When requests are made * to search for MIME types in the MimetypesFileTypeMap, it searches * MIME types files in the following order: - *

                            *

                              *
                            1. Programmatically added entries to the MimetypesFileTypeMap instance. - *
                            2. The file .mime.types in the user's home directory. - *
                            3. The file <java.home>/lib/mime.types. - *
                            4. The file or resources named META-INF/mime.types. - *
                            5. The file or resource named META-INF/mimetypes.default - * (usually found only in the activation.jar file). + *
                            6. The file {@code .mime.types} in the user's home directory. + *
                            7. The file {@literal <}java.home{@literal >}{@code /lib/mime.types}. + *
                            8. The file or resources named {@code META-INF/mime.types}. + *
                            9. The file or resource named {@code META-INF/mimetypes.default} + * (usually found only in the {@code activation.jar} file). *
                            *

                            - * MIME types file format:

                            + * MIME types file format: * - * - * # comments begin with a '#'
                            - * # the format is <mime type> <space separated file extensions>
                            - * # for example:
                            - * text/plain txt text TXT
                            - * # this would map file.txt, file.text, and file.TXT to
                            - * # the mime type "text/plain"
                            - *
                            + *

                            {@code
                            + * # comments begin with a '#'
                            + * # the format is  
                            + * # for example:
                            + * text/plain    txt text TXT
                            + * # this would map file.txt, file.text, and file.TXT to
                            + * # the mime type "text/plain"
                            + * }
                            * * @author Bart Calder * @author Bill Shannon @@ -277,7 +276,7 @@ public class MimetypesFileTypeMap extends FileTypeMap { /** * Return the MIME type of the file object. * The implementation in this class calls - * getContentType(f.getName()). + * {@code getContentType(f.getName())}. * * @param f the file * @return the file's MIME type diff --git a/jaxws/src/java.annotations.common/share/classes/javax/annotation/PostConstruct.java b/jaxws/src/java.annotations.common/share/classes/javax/annotation/PostConstruct.java index fbe226ca42e..8a7b535c694 100644 --- a/jaxws/src/java.annotations.common/share/classes/javax/annotation/PostConstruct.java +++ b/jaxws/src/java.annotations.common/share/classes/javax/annotation/PostConstruct.java @@ -39,7 +39,6 @@ import static java.lang.annotation.RetentionPolicy.*; * method can be annotated with this annotation. The method on which the * PostConstruct annotation is applied MUST fulfill all of the following * criteria: - *

                            *

                              *
                            • The method MUST NOT have any parameters except in the case of * interceptors in which case it takes an InvocationContext object as diff --git a/jaxws/src/java.annotations.common/share/classes/javax/annotation/PreDestroy.java b/jaxws/src/java.annotations.common/share/classes/javax/annotation/PreDestroy.java index eff974a5e4a..2dfbb878e08 100644 --- a/jaxws/src/java.annotations.common/share/classes/javax/annotation/PreDestroy.java +++ b/jaxws/src/java.annotations.common/share/classes/javax/annotation/PreDestroy.java @@ -38,7 +38,6 @@ import static java.lang.annotation.RetentionPolicy.*; * except the application client container in Java EE 5. The method on which * the PreDestroy annotation is applied MUST fulfill all of the following * criteria: - *

                              *

                                *
                              • The method MUST NOT have any parameters except in the case of * interceptors in which case it takes an InvocationContext object as diff --git a/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/bind/v2/ClassFactory.java b/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/bind/v2/ClassFactory.java index 4a766d39d9a..4347bff9f07 100644 --- a/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/bind/v2/ClassFactory.java +++ b/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/bind/v2/ClassFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/org/jvnet/mimepull/MIMEMessage.java b/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/org/jvnet/mimepull/MIMEMessage.java index 93339f0b9b8..1204ff59072 100644 --- a/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/org/jvnet/mimepull/MIMEMessage.java +++ b/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/org/jvnet/mimepull/MIMEMessage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * 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,12 +25,18 @@ package com.sun.xml.internal.org.jvnet.mimepull; +import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.ByteBuffer; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; @@ -40,19 +46,21 @@ import java.util.logging.Logger; * * @author Jitendra Kotamraju */ -public class MIMEMessage { +public class MIMEMessage implements Closeable { + private static final Logger LOGGER = Logger.getLogger(MIMEMessage.class.getName()); MIMEConfig config; private final InputStream in; - private final List partsList; - private final Map partsMap; private final Iterator it; private boolean parsed; // true when entire message is parsed private MIMEPart currentPart; private int currentIndex; + private final List partsList = new ArrayList(); + private final Map partsMap = new HashMap(); + /** * @see MIMEMessage(InputStream, String, MIMEConfig) */ @@ -64,9 +72,9 @@ public class MIMEMessage { * Creates a MIME message from the content's stream. The content stream * is closed when EOF is reached. * - * @param in MIME message stream + * @param in MIME message stream * @param boundary the separator for parts(pass it without --) - * @param config various configuration parameters + * @param config various configuration parameters */ public MIMEMessage(InputStream in, String boundary, MIMEConfig config) { this.in = in; @@ -74,8 +82,6 @@ public class MIMEMessage { MIMEParser parser = new MIMEParser(in, boundary, config); it = parser.iterator(); - partsList = new ArrayList(); - partsMap = new HashMap(); if (config.isParseEagerly()) { parseAll(); } @@ -108,14 +114,14 @@ public class MIMEMessage { LOGGER.log(Level.FINE, "index={0}", index); MIMEPart part = (index < partsList.size()) ? partsList.get(index) : null; if (parsed && part == null) { - throw new MIMEParsingException("There is no "+index+" attachment part "); + throw new MIMEParsingException("There is no " + index + " attachment part "); } if (part == null) { // Parsing will done lazily and will be driven by reading the part part = new MIMEPart(this); partsList.add(index, part); } - LOGGER.log(Level.FINE, "Got attachment at index={0} attachment={1}", new Object[]{index, part}); + LOGGER.log(Level.FINE, "Got attachment at index={0} attachment={1}", new Object[] {index, part}); return part; } @@ -132,14 +138,14 @@ public class MIMEMessage { LOGGER.log(Level.FINE, "Content-ID={0}", contentId); MIMEPart part = getDecodedCidPart(contentId); if (parsed && part == null) { - throw new MIMEParsingException("There is no attachment part with Content-ID = "+contentId); + throw new MIMEParsingException("There is no attachment part with Content-ID = " + contentId); } if (part == null) { // Parsing is done lazily and is driven by reading the part part = new MIMEPart(this, contentId); partsMap.put(contentId, part); } - LOGGER.log(Level.FINE, "Got attachment for Content-ID={0} attachment={1}", new Object[]{contentId, part}); + LOGGER.log(Level.FINE, "Got attachment for Content-ID={0} attachment={1}", new Object[] {contentId, part}); return part; } @@ -151,7 +157,7 @@ public class MIMEMessage { try { String tempCid = URLDecoder.decode(cid, "utf-8"); part = partsMap.get(tempCid); - } catch(UnsupportedEncodingException ue) { + } catch (UnsupportedEncodingException ue) { // Ignore it } } @@ -159,22 +165,43 @@ public class MIMEMessage { return part; } - /** * Parses the whole MIME message eagerly */ public final void parseAll() { - while(makeProgress()) { + while (makeProgress()) { // Nothing to do } } + /** + * Closes all parsed {@link com.sun.xml.internal.org.jvnet.mimepull.MIMEPart parts}. + * This method is safe to call even if parsing of message failed. + *

                                + * Does not throw {@link com.sun.xml.internal.org.jvnet.mimepull.MIMEParsingException} if an + * error occurred during closing a MIME part. The exception (if any) is + * still logged. + */ + @Override + public void close() { + close(partsList); + close(partsMap.values()); + } + + private void close(final Collection parts) { + for (final MIMEPart part : parts) { + try { + part.close(); + } catch (final MIMEParsingException closeError) { + LOGGER.log(Level.FINE, "Exception during closing MIME part", closeError); + } + } + } /** * Parses the MIME message in a pull fashion. * - * @return - * false if the parsing is completed. + * @return false if the parsing is completed. */ public synchronized boolean makeProgress() { if (!it.hasNext()) { @@ -183,23 +210,23 @@ public class MIMEMessage { MIMEEvent event = it.next(); - switch(event.getEventType()) { - case START_MESSAGE : + switch (event.getEventType()) { + case START_MESSAGE: LOGGER.log(Level.FINE, "MIMEEvent={0}", MIMEEvent.EVENT_TYPE.START_MESSAGE); break; - case START_PART : + case START_PART: LOGGER.log(Level.FINE, "MIMEEvent={0}", MIMEEvent.EVENT_TYPE.START_PART); break; - case HEADERS : + case HEADERS: LOGGER.log(Level.FINE, "MIMEEvent={0}", MIMEEvent.EVENT_TYPE.HEADERS); - MIMEEvent.Headers headers = (MIMEEvent.Headers)event; + MIMEEvent.Headers headers = (MIMEEvent.Headers) event; InternetHeaders ih = headers.getHeaders(); List cids = ih.getHeader("content-id"); - String cid = (cids != null) ? cids.get(0) : currentIndex+""; - if (cid.length() > 2 && cid.charAt(0)=='<') { - cid = cid.substring(1,cid.length()-1); + String cid = (cids != null) ? cids.get(0) : currentIndex + ""; + if (cid.length() > 2 && cid.charAt(0) == '<') { + cid = cid.substring(1, cid.length() - 1); } MIMEPart listPart = (currentIndex < partsList.size()) ? partsList.get(currentIndex) : null; MIMEPart mapPart = getDecodedCidPart(cid); @@ -219,31 +246,31 @@ public class MIMEMessage { currentPart.setHeaders(ih); break; - case CONTENT : + case CONTENT: LOGGER.log(Level.FINER, "MIMEEvent={0}", MIMEEvent.EVENT_TYPE.CONTENT); - MIMEEvent.Content content = (MIMEEvent.Content)event; + MIMEEvent.Content content = (MIMEEvent.Content) event; ByteBuffer buf = content.getData(); currentPart.addBody(buf); break; - case END_PART : + case END_PART: LOGGER.log(Level.FINE, "MIMEEvent={0}", MIMEEvent.EVENT_TYPE.END_PART); currentPart.doneParsing(); ++currentIndex; break; - case END_MESSAGE : + case END_MESSAGE: LOGGER.log(Level.FINE, "MIMEEvent={0}", MIMEEvent.EVENT_TYPE.END_MESSAGE); parsed = true; try { in.close(); - } catch(IOException ioe) { + } catch (IOException ioe) { throw new MIMEParsingException(ioe); } break; - default : - throw new MIMEParsingException("Unknown Parser state = "+event.getEventType()); + default: + throw new MIMEParsingException("Unknown Parser state = " + event.getEventType()); } return true; } diff --git a/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/org/jvnet/mimepull/MIMEPart.java b/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/org/jvnet/mimepull/MIMEPart.java index 88a6e0b358c..cbe4b448df1 100644 --- a/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/org/jvnet/mimepull/MIMEPart.java +++ b/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/org/jvnet/mimepull/MIMEPart.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * 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 com.sun.xml.internal.org.jvnet.mimepull; +import java.io.Closeable; import java.io.File; import java.io.InputStream; import java.nio.ByteBuffer; @@ -42,10 +43,11 @@ import java.util.logging.Logger; * * @author Jitendra Kotamraju, Martin Grebac */ -public class MIMEPart { +public class MIMEPart implements Closeable { private static final Logger LOGGER = Logger.getLogger(MIMEPart.class.getName()); + private volatile boolean closed; private volatile InternetHeaders headers; private volatile String contentId; private String contentType; @@ -55,6 +57,8 @@ public class MIMEPart { final MIMEMessage msg; private final DataHead dataHead; + private final Object lock = new Object(); + MIMEPart(MIMEMessage msg) { this.msg = msg; this.dataHead = new DataHead(this); @@ -91,8 +95,16 @@ public class MIMEPart { * the temp file that is used to serve this part's content). After * calling this, one shouldn't call {@link #read()} or {@link #readOnce()} */ + @Override public void close() { - dataHead.close(); + if (!closed) { + synchronized (lock) { + if (!closed) { + dataHead.close(); + closed = true; + } + } + } } /** @@ -242,6 +254,15 @@ public class MIMEPart { this.contentTransferEncoding = cte; } + /** + * Return {@code true} if this part has already been closed, {@code false} otherwise. + * + * @return {@code true} if this part has already been closed, {@code false} otherwise. + */ + public boolean isClosed() { + return closed; + } + @Override public String toString() { return "Part="+contentId+":"+contentTransferEncoding; diff --git a/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/org/jvnet/mimepull/MemoryData.java b/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/org/jvnet/mimepull/MemoryData.java index 912b9ca84b5..5413ac45de3 100644 --- a/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/org/jvnet/mimepull/MemoryData.java +++ b/jaxws/src/java.xml.bind/share/classes/com/sun/xml/internal/org/jvnet/mimepull/MemoryData.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * 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,9 +84,6 @@ final class MemoryData implements Data { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Created temp file = {0}", tempFile); } - // delete the temp file when VM exits as a last resort for file clean up - tempFile.deleteOnExit(); - if (LOGGER.isLoggable(Level.FINE)) {LOGGER.log(Level.FINE, "Created temp file = {0}", tempFile);} dataHead.dataFile = new DataFile(tempFile); } catch (IOException ioe) { throw new MIMEParsingException(ioe); diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/ContextFinder.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/ContextFinder.java index 78dd65de770..18ff8196bc7 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/ContextFinder.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/ContextFinder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * 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,7 +25,6 @@ package javax.xml.bind; -import java.util.Iterator; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -34,15 +33,13 @@ import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; +import java.security.AccessController; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; -import java.security.AccessController; - -import static javax.xml.bind.JAXBContext.JAXB_CONTEXT_FACTORY; /** @@ -55,7 +52,24 @@ import static javax.xml.bind.JAXBContext.JAXB_CONTEXT_FACTORY; * @see JAXBContext */ class ContextFinder { + + /** + * When JAXB is in J2SE, rt.jar has to have a JAXB implementation. + * However, rt.jar cannot have META-INF/services/javax.xml.bind.JAXBContext + * because if it has, it will take precedence over any file that applications have + * in their jar files. + * + *

                                + * When the user bundles his own JAXB implementation, we'd like to use it, and we + * want the platform default to be used only when there's no other JAXB provider. + * + *

                                + * For this reason, we have to hard-code the class name into the API. + */ + private static final String PLATFORM_DEFAULT_FACTORY_CLASS = "com.sun.xml.internal.bind.v2.ContextFactory"; + private static final Logger logger; + static { logger = Logger.getLogger("javax.xml.bind"); try { @@ -72,7 +86,7 @@ class ContextFinder { // to honor what other frameworks // have done on configurations. } - } catch(Throwable t) { + } catch (Throwable t) { // just to be extra safe. in particular System.getProperty may throw // SecurityException. } @@ -84,15 +98,15 @@ class ContextFinder { */ private static void handleInvocationTargetException(InvocationTargetException x) throws JAXBException { Throwable t = x.getTargetException(); - if( t != null ) { - if( t instanceof JAXBException ) + if (t != null) { + if (t instanceof JAXBException) // one of our exceptions, just re-throw - throw (JAXBException)t; - if( t instanceof RuntimeException ) + throw (JAXBException) t; + if (t instanceof RuntimeException) // avoid wrapping exceptions unnecessarily - throw (RuntimeException)t; - if( t instanceof Error ) - throw (Error)t; + throw (RuntimeException) t; + if (t instanceof Error) + throw (Error) t; } } @@ -121,18 +135,17 @@ class ContextFinder { /** * Create an instance of a class using the specified ClassLoader */ - static JAXBContext newInstance( String contextPath, - String className, - ClassLoader classLoader, - Map properties ) - throws JAXBException { + static JAXBContext newInstance(String contextPath, + String className, + ClassLoader classLoader, + Map properties) throws JAXBException { + try { - Class spFactory = safeLoadClass(className,classLoader); + Class spFactory = ServiceLoaderUtil.safeLoadClass(className, PLATFORM_DEFAULT_FACTORY_CLASS, classLoader); return newInstance(contextPath, spFactory, classLoader, properties); } catch (ClassNotFoundException x) { - throw new JAXBException( - Messages.format( Messages.PROVIDER_NOT_FOUND, className ), - x); + throw new JAXBException(Messages.format(Messages.PROVIDER_NOT_FOUND, className), x); + } catch (RuntimeException x) { // avoid wrapping RuntimeException to JAXBException, // because it indicates a bug in this code. @@ -142,18 +155,12 @@ class ContextFinder { // reflection. Root element collisions detected in the call to // createContext() are reported as JAXBExceptions - just re-throw it // some other type of exception - just wrap it - throw new JAXBException( - Messages.format( Messages.COULD_NOT_INSTANTIATE, className, x ), - x); + throw new JAXBException(Messages.format(Messages.COULD_NOT_INSTANTIATE, className, x), x); } } - static JAXBContext newInstance( String contextPath, - Class spFactory, - ClassLoader classLoader, - Map properties ) - throws JAXBException - { + static JAXBContext newInstance(String contextPath, Class spFactory, ClassLoader classLoader, Map properties) throws JAXBException { + try { /* * javax.xml.bind.context.factory points to a class which has a @@ -166,35 +173,35 @@ class ContextFinder { // first check the method that takes Map as the third parameter. // this is added in 2.0. try { - Method m = spFactory.getMethod("createContext",String.class,ClassLoader.class,Map.class); + Method m = spFactory.getMethod("createContext", String.class, ClassLoader.class, Map.class); // any failure in invoking this method would be considered fatal - context = m.invoke(null,contextPath,classLoader,properties); + context = m.invoke(null, contextPath, classLoader, properties); } catch (NoSuchMethodException e) { // it's not an error for the provider not to have this method. } - if(context==null) { + if (context == null) { // try the old method that doesn't take properties. compatible with 1.0. // it is an error for an implementation not to have both forms of the createContext method. - Method m = spFactory.getMethod("createContext",String.class,ClassLoader.class); + Method m = spFactory.getMethod("createContext", String.class, ClassLoader.class); // any failure in invoking this method would be considered fatal - context = m.invoke(null,contextPath,classLoader); + context = m.invoke(null, contextPath, classLoader); } - if(!(context instanceof JAXBContext)) { + if (!(context instanceof JAXBContext)) { // the cast would fail, so generate an exception with a nice message throw handleClassCastException(context.getClass(), JAXBContext.class); } - return (JAXBContext)context; + return (JAXBContext) context; } catch (InvocationTargetException x) { handleInvocationTargetException(x); // for other exceptions, wrap the internal target exception // with a JAXBException Throwable e = x; - if(x.getTargetException()!=null) + if (x.getTargetException() != null) e = x.getTargetException(); - throw new JAXBException( Messages.format( Messages.COULD_NOT_INSTANTIATE, spFactory, e ), e ); + throw new JAXBException(Messages.format(Messages.COULD_NOT_INSTANTIATE, spFactory, e), e); } catch (RuntimeException x) { // avoid wrapping RuntimeException to JAXBException, // because it indicates a bug in this code. @@ -204,29 +211,23 @@ class ContextFinder { // reflection. Root element collisions detected in the call to // createContext() are reported as JAXBExceptions - just re-throw it // some other type of exception - just wrap it - throw new JAXBException( - Messages.format( Messages.COULD_NOT_INSTANTIATE, spFactory, x ), - x); + throw new JAXBException(Messages.format(Messages.COULD_NOT_INSTANTIATE, spFactory, x), x); } } - /** * Create an instance of a class using the thread context ClassLoader */ - static JAXBContext newInstance( - Class[] classes, - Map properties, - String className) throws JAXBException { - ClassLoader cl = getContextClassLoader(); + static JAXBContext newInstance(Class[] classes, Map properties, String className) throws JAXBException { + Class spi; try { - spi = safeLoadClass(className,cl); + spi = ServiceLoaderUtil.safeLoadClass(className, PLATFORM_DEFAULT_FACTORY_CLASS, getContextClassLoader()); } catch (ClassNotFoundException e) { throw new JAXBException(e); } - if(logger.isLoggable(Level.FINE)) { + if (logger.isLoggable(Level.FINE)) { // extra check to avoid costly which operation if not logged logger.log(Level.FINE, "loaded {0} from {1}", new Object[]{className, which(spi)}); } @@ -237,19 +238,16 @@ class ContextFinder { static JAXBContext newInstance(Class[] classes, Map properties, Class spFactory) throws JAXBException { - Method m; - try { - m = spFactory.getMethod("createContext", Class[].class, Map.class); - } catch (NoSuchMethodException e) { - throw new JAXBException(e); - } try { + Method m = spFactory.getMethod("createContext", Class[].class, Map.class); Object context = m.invoke(null, classes, properties); - if(!(context instanceof JAXBContext)) { + if (!(context instanceof JAXBContext)) { // the cast would fail, so generate an exception with a nice message throw handleClassCastException(context.getClass(), JAXBContext.class); } - return (JAXBContext)context; + return (JAXBContext) context; + } catch (NoSuchMethodException e) { + throw new JAXBException(e); } catch (IllegalAccessException e) { throw new JAXBException(e); } catch (InvocationTargetException e) { @@ -263,241 +261,139 @@ class ContextFinder { } } - static JAXBContext find(String factoryId, String contextPath, ClassLoader classLoader, Map properties ) throws JAXBException { + static JAXBContext find(String factoryId, String contextPath, ClassLoader classLoader, Map properties) throws JAXBException { // TODO: do we want/need another layer of searching in $java.home/lib/jaxb.properties like JAXP? - final String jaxbContextFQCN = JAXBContext.class.getName(); - - // search context path for jaxb.properties first - StringBuilder propFileName; - StringTokenizer packages = new StringTokenizer( contextPath, ":" ); - String factoryClassName; - - if(!packages.hasMoreTokens()) + StringTokenizer packages = new StringTokenizer(contextPath, ":"); + if (!packages.hasMoreTokens()) { // no context is specified throw new JAXBException(Messages.format(Messages.NO_PACKAGE_IN_CONTEXTPATH)); + } - + // search for jaxb.properties in the class loader of each class first logger.fine("Searching jaxb.properties"); - - while( packages.hasMoreTokens() ) { - String packageName = packages.nextToken(":").replace('.','/'); + while (packages.hasMoreTokens()) { // com.acme.foo - > com/acme/foo/jaxb.properties - propFileName = new StringBuilder().append(packageName).append("/jaxb.properties"); - - Properties props = loadJAXBProperties( classLoader, propFileName.toString() ); - if (props != null) { - if (props.containsKey(factoryId)) { - factoryClassName = props.getProperty(factoryId); - return newInstance( contextPath, factoryClassName, classLoader, properties ); - } else { - throw new JAXBException(Messages.format(Messages.MISSING_PROPERTY, packageName, factoryId)); - } - } + String className = classNameFromPackageProperties(factoryId, classLoader, packages.nextToken(":").replace('.', '/')); + if (className != null) return newInstance(contextPath, className, classLoader, properties); } - logger.fine("Searching the system property"); + String factoryName = classNameFromSystemProperties(); + if (factoryName != null) return newInstance(contextPath, factoryName, classLoader, properties); - // search for a system property second (javax.xml.bind.JAXBContext) - factoryClassName = AccessController.doPrivileged(new GetPropertyAction(JAXBContext.JAXB_CONTEXT_FACTORY)); - if( factoryClassName != null ) { - return newInstance( contextPath, factoryClassName, classLoader, properties ); - } else { // leave this here to assure compatibility - factoryClassName = AccessController.doPrivileged(new GetPropertyAction(jaxbContextFQCN)); - if( factoryClassName != null ) { - return newInstance( contextPath, factoryClassName, classLoader, properties ); - } + Class ctxFactory = (Class) ServiceLoaderUtil.lookupUsingOSGiServiceLoader("javax.xml.bind.JAXBContext", logger); + if (ctxFactory != null) { + return newInstance(contextPath, ctxFactory, classLoader, properties); } - // OSGi search - Class jaxbContext = lookupJaxbContextUsingOsgiServiceLoader(); - if (jaxbContext != null) { - logger.fine("OSGi environment detected"); - return newInstance(contextPath, jaxbContext, classLoader, properties); - } + // TODO: SPEC change required! This is supposed to be! + // JAXBContext obj = firstByServiceLoader(JAXBContext.class, EXCEPTION_HANDLER); + // if (obj != null) return obj; - logger.fine("Searching META-INF/services"); - // search META-INF services next - BufferedReader r = null; - try { - final StringBuilder resource = new StringBuilder().append("META-INF/services/").append(jaxbContextFQCN); - final InputStream resourceStream = - classLoader.getResourceAsStream(resource.toString()); - - if (resourceStream != null) { - r = new BufferedReader(new InputStreamReader(resourceStream, "UTF-8")); - factoryClassName = r.readLine(); - if (factoryClassName != null) { - factoryClassName = factoryClassName.trim(); - } - r.close(); - return newInstance(contextPath, factoryClassName, classLoader, properties); - } else { - logger.log(Level.FINE, "Unable to load:{0}", resource.toString()); - } - } catch (UnsupportedEncodingException e) { - // should never happen - throw new JAXBException(e); - } catch (IOException e) { - throw new JAXBException(e); - } finally { - try { - if (r != null) { - r.close(); - } - } catch (IOException ex) { - Logger.getLogger(ContextFinder.class.getName()).log(Level.SEVERE, null, ex); - } - } + // TODO: Deprecated - SPEC change required! + factoryName = firstByServiceLoaderDeprecated(JAXBContext.class, classLoader); + if (factoryName != null) return newInstance(contextPath, factoryName, classLoader, properties); // else no provider found logger.fine("Trying to create the platform default provider"); return newInstance(contextPath, PLATFORM_DEFAULT_FACTORY_CLASS, classLoader, properties); } - static JAXBContext find( Class[] classes, Map properties ) throws JAXBException { - - final String jaxbContextFQCN = JAXBContext.class.getName(); - String factoryClassName; + static JAXBContext find(Class[] classes, Map properties) throws JAXBException { // search for jaxb.properties in the class loader of each class first + logger.fine("Searching jaxb.properties"); for (final Class c : classes) { // this classloader is used only to load jaxb.properties, so doing this should be safe. - ClassLoader classLoader = getClassClassLoader(c); - Package pkg = c.getPackage(); - if(pkg==null) - continue; // this is possible for primitives, arrays, and classes that are loaded by poorly implemented ClassLoaders - String packageName = pkg.getName().replace('.', '/'); + if (c.getPackage() == null) continue; // this is possible for primitives, arrays, and classes that are loaded by poorly implemented ClassLoaders // TODO: do we want to optimize away searching the same package? org.Foo, org.Bar, com.Baz - // classes from the same package might come from different class loades, so it might be a bad idea - + // classes from the same package might come from different class loades, so it might be a bad idea // TODO: it's easier to look things up from the class // c.getResourceAsStream("jaxb.properties"); - // build the resource name and use the property loader code - String resourceName = packageName+"/jaxb.properties"; - logger.log(Level.FINE, "Trying to locate {0}", resourceName); - Properties props = loadJAXBProperties(classLoader, resourceName); - if (props == null) { - logger.fine(" not found"); - } else { - logger.fine(" found"); - if (props.containsKey(JAXB_CONTEXT_FACTORY)) { - // trim() seems redundant, but adding to satisfy customer complaint - factoryClassName = props.getProperty(JAXB_CONTEXT_FACTORY).trim(); - return newInstance(classes, properties, factoryClassName); - } else { - throw new JAXBException(Messages.format(Messages.MISSING_PROPERTY, packageName, JAXB_CONTEXT_FACTORY)); - } - } + String className = classNameFromPackageProperties(JAXBContext.JAXB_CONTEXT_FACTORY, getClassClassLoader(c), c.getPackage().getName().replace('.', '/')); + if (className != null) return newInstance(classes, properties, className); } - // search for a system property second (javax.xml.bind.JAXBContext) - logger.log(Level.FINE, "Checking system property {0}", JAXBContext.JAXB_CONTEXT_FACTORY); - factoryClassName = AccessController.doPrivileged(new GetPropertyAction(JAXBContext.JAXB_CONTEXT_FACTORY)); - if (factoryClassName != null) { - logger.log(Level.FINE, " found {0}", factoryClassName); - return newInstance( classes, properties, factoryClassName ); - } else { // leave it here for compatibility reasons - logger.fine(" not found"); - logger.log(Level.FINE, "Checking system property {0}", jaxbContextFQCN); - factoryClassName = AccessController.doPrivileged(new GetPropertyAction(jaxbContextFQCN)); - if (factoryClassName != null) { - logger.log(Level.FINE, " found {0}", factoryClassName); - return newInstance( classes, properties, factoryClassName ); - } else { - logger.fine(" not found"); - } + String factoryName = classNameFromSystemProperties(); + if (factoryName != null) return newInstance(classes, properties, factoryName); + + Class ctxFactoryClass = (Class) ServiceLoaderUtil.lookupUsingOSGiServiceLoader("javax.xml.bind.JAXBContext", logger); + if (ctxFactoryClass != null) { + return newInstance(classes, properties, ctxFactoryClass); } - // OSGi search - Class jaxbContext = lookupJaxbContextUsingOsgiServiceLoader(); - if (jaxbContext != null) { - logger.fine("OSGi environment detected"); - return newInstance(classes, properties, jaxbContext); - } + // TODO: to be removed - deprecated!!! Requires SPEC change!!! + String className = firstByServiceLoaderDeprecated(JAXBContext.class, getContextClassLoader()); + if (className != null) return newInstance(classes, properties, className); - // search META-INF services next - logger.fine("Checking META-INF/services"); - BufferedReader r = null; - try { - final String resource = new StringBuilder("META-INF/services/").append(jaxbContextFQCN).toString(); - ClassLoader classLoader = getContextClassLoader(); - URL resourceURL; - if(classLoader==null) - resourceURL = ClassLoader.getSystemResource(resource); - else - resourceURL = classLoader.getResource(resource); - - if (resourceURL != null) { - logger.log(Level.FINE, "Reading {0}", resourceURL); - r = new BufferedReader(new InputStreamReader(resourceURL.openStream(), "UTF-8")); - factoryClassName = r.readLine(); - if (factoryClassName != null) { - factoryClassName = factoryClassName.trim(); - } - return newInstance(classes, properties, factoryClassName); - } else { - logger.log(Level.FINE, "Unable to find: {0}", resource); - } - } catch (UnsupportedEncodingException e) { - // should never happen - throw new JAXBException(e); - } catch (IOException e) { - throw new JAXBException(e); - } finally { - if (r != null) { - try { - r.close(); - } catch (IOException ex) { - logger.log(Level.FINE, "Unable to close stream", ex); - } - } - } + // // TODO: supposed to be: + // obj = firstByServiceLoader(JAXBContext.class, EXCEPTION_HANDLER); + // if (obj != null) return obj; // else no provider found logger.fine("Trying to create the platform default provider"); return newInstance(classes, properties, PLATFORM_DEFAULT_FACTORY_CLASS); } - private static Class lookupJaxbContextUsingOsgiServiceLoader() { - try { - // Use reflection to avoid having any dependency on ServiceLoader class - Class target = Class.forName("com.sun.org.glassfish.hk2.osgiresourcelocator.ServiceLoader"); - Method m = target.getMethod("lookupProviderClasses", Class.class); - Iterator iter = ((Iterable) m.invoke(null, JAXBContext.class)).iterator(); - return iter.hasNext() ? (Class)iter.next() : null; - } catch(Exception e) { - logger.log(Level.FINE, "Unable to find from OSGi: javax.xml.bind.JAXBContext"); - return null; + + private static String classNameFromPackageProperties(String factoryId, ClassLoader classLoader, String packageName) throws JAXBException { + String resourceName = packageName + "/jaxb.properties"; + logger.log(Level.FINE, "Trying to locate {0}", resourceName); + Properties props = loadJAXBProperties(classLoader, resourceName); + if (props != null) { + if (props.containsKey(factoryId)) { + return props.getProperty(factoryId); + } else { + throw new JAXBException(Messages.format(Messages.MISSING_PROPERTY, packageName, factoryId)); + } } + return null; } - private static Properties loadJAXBProperties( ClassLoader classLoader, - String propFileName ) - throws JAXBException { + private static String classNameFromSystemProperties() throws JAXBException { + logger.log(Level.FINE, "Checking system property {0}", JAXBContext.JAXB_CONTEXT_FACTORY); + // search for a system property second (javax.xml.bind.JAXBContext) + String factoryClassName = AccessController.doPrivileged(new GetPropertyAction(JAXBContext.JAXB_CONTEXT_FACTORY)); + if (factoryClassName != null) { + logger.log(Level.FINE, " found {0}", factoryClassName); + return factoryClassName; + } else { // leave this here to assure compatibility + logger.fine(" not found"); + logger.log(Level.FINE, "Checking system property {0}", JAXBContext.class.getName()); + factoryClassName = AccessController.doPrivileged(new GetPropertyAction(JAXBContext.class.getName())); + if (factoryClassName != null) { + logger.log(Level.FINE, " found {0}", factoryClassName); + return factoryClassName; + } else { + logger.fine(" not found"); + } + } + return null; + } + + private static Properties loadJAXBProperties(ClassLoader classLoader, String propFileName) throws JAXBException { Properties props = null; - try { URL url; - if(classLoader==null) + if (classLoader == null) url = ClassLoader.getSystemResource(propFileName); else - url = classLoader.getResource( propFileName ); + url = classLoader.getResource(propFileName); - if( url != null ) { + if (url != null) { logger.log(Level.FINE, "loading props from {0}", url); props = new Properties(); InputStream is = url.openStream(); - props.load( is ); + props.load(is); is.close(); } - } catch( IOException ioe ) { - logger.log(Level.FINE,"Unable to load "+propFileName,ioe); - throw new JAXBException( ioe.toString(), ioe ); + } catch (IOException ioe) { + logger.log(Level.FINE, "Unable to load " + propFileName, ioe); + throw new JAXBException(ioe.toString(), ioe); } return props; @@ -520,7 +416,7 @@ class ContextFinder { String classnameAsResource = clazz.getName().replace('.', '/') + ".class"; - if(loader == null) { + if (loader == null) { loader = getSystemClassLoader(); } @@ -543,50 +439,7 @@ class ContextFinder { return which(clazz, getClassClassLoader(clazz)); } - /** - * When JAXB is in J2SE, rt.jar has to have a JAXB implementation. - * However, rt.jar cannot have META-INF/services/javax.xml.bind.JAXBContext - * because if it has, it will take precedence over any file that applications have - * in their jar files. - * - *

                                - * When the user bundles his own JAXB implementation, we'd like to use it, and we - * want the platform default to be used only when there's no other JAXB provider. - * - *

                                - * For this reason, we have to hard-code the class name into the API. - */ - private static final String PLATFORM_DEFAULT_FACTORY_CLASS = "com.sun.xml.internal.bind.v2.ContextFactory"; - - /** - * Loads the class, provided that the calling thread has an access to the class being loaded. - */ - private static Class safeLoadClass(String className, ClassLoader classLoader) throws ClassNotFoundException { - logger.log(Level.FINE, "Trying to load {0}", className); - try { - // make sure that the current thread has an access to the package of the given name. - SecurityManager s = System.getSecurityManager(); - if (s != null) { - int i = className.lastIndexOf('.'); - if (i != -1) { - s.checkPackageAccess(className.substring(0,i)); - } - } - - if (classLoader == null) { - return Class.forName(className); - } else { - return classLoader.loadClass(className); - } - } catch (SecurityException se) { - // anyone can access the platform default factory class without permission - if (PLATFORM_DEFAULT_FACTORY_CLASS.equals(className)) { - return Class.forName(className); - } - throw se; - } - } - + @SuppressWarnings("unchecked") private static ClassLoader getContextClassLoader() { if (System.getSecurityManager() == null) { return Thread.currentThread().getContextClassLoader(); @@ -600,6 +453,7 @@ class ContextFinder { } } + @SuppressWarnings("unchecked") private static ClassLoader getClassClassLoader(final Class c) { if (System.getSecurityManager() == null) { return c.getClassLoader(); @@ -626,4 +480,50 @@ class ContextFinder { } } + // TODO: to be removed - SPEC change required + // ServiceLoaderUtil.firstByServiceLoaderDeprecated should be used instead. + @Deprecated + static String firstByServiceLoaderDeprecated(Class spiClass, ClassLoader classLoader) throws JAXBException { + final String jaxbContextFQCN = spiClass.getName(); + + logger.fine("Searching META-INF/services"); + + // search META-INF services next + BufferedReader r = null; + final String resource = new StringBuilder().append("META-INF/services/").append(jaxbContextFQCN).toString(); + try { + final InputStream resourceStream = + (classLoader == null) ? + ClassLoader.getSystemResourceAsStream(resource) : + classLoader.getResourceAsStream(resource); + + if (resourceStream != null) { + r = new BufferedReader(new InputStreamReader(resourceStream, "UTF-8")); + String factoryClassName = r.readLine(); + if (factoryClassName != null) { + factoryClassName = factoryClassName.trim(); + } + r.close(); + logger.log(Level.FINE, "Configured factorty class:{0}", factoryClassName); + return factoryClassName; + } else { + logger.log(Level.FINE, "Unable to load:{0}", resource); + return null; + } + } catch (UnsupportedEncodingException e) { + // should never happen + throw new JAXBException(e); + } catch (IOException e) { + throw new JAXBException(e); + } finally { + try { + if (r != null) { + r.close(); + } + } catch (IOException ex) { + logger.log(Level.SEVERE, "Unable to close resource: " + resource, ex); + } + } + } + } diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/DatatypeConverterInterface.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/DatatypeConverterInterface.java index 0f4796e0db5..80828f88e7b 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/DatatypeConverterInterface.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/DatatypeConverterInterface.java @@ -38,19 +38,16 @@ package javax.xml.bind; * functionality. Calling this api repeatedly will have no effect - the * DatatypeConverter instance passed into the first invocation is the one that * will be used from then on. - *

                                * *

                                * This interface defines the parse and print methods. There is one * parse and print method for each XML schema datatype specified in the * the default binding Table 5-1 in the JAXB specification. - *

                                * *

                                * The parse and print methods defined here are invoked by the static parse * and print methods defined in the {@link DatatypeConverter DatatypeConverter} * class. - *

                                * *

                                * A parse method for a XML schema datatype must be capable of converting any @@ -60,21 +57,23 @@ package javax.xml.bind; * If an error is encountered during conversion, then an IllegalArgumentException * or a subclass of IllegalArgumentException must be thrown by the method. * - *

                                - * *

                                * A print method for a XML schema datatype can output any lexical * representation that is valid with respect to the XML schema datatype. * If an error is encountered during conversion, then an IllegalArgumentException, * or a subclass of IllegalArgumentException must be thrown by the method. - *

                                * + *

                                * The prefix xsd: is used to refer to XML schema datatypes * XML Schema Part2: Datatypes * specification. * - *

                                - * @author

                                • Sekhar Vajjhala, Sun Microsystems, Inc.
                                • Joe Fialli, Sun Microsystems Inc.
                                • Kohsuke Kawaguchi, Sun Microsystems, Inc.
                                • Ryan Shoemaker,Sun Microsystems Inc.
                                + * @author
                                  + *
                                • Sekhar Vajjhala, Sun Microsystems, Inc.
                                • + *
                                • Joe Fialli, Sun Microsystems Inc.
                                • + *
                                • Kohsuke Kawaguchi, Sun Microsystems, Inc.
                                • + *
                                • Ryan Shoemaker,Sun Microsystems Inc.
                                • + *
                                * @see DatatypeConverter * @see ParseConversionEvent * @see PrintConversionEvent @@ -83,7 +82,6 @@ package javax.xml.bind; public interface DatatypeConverterInterface { /** - *

                                * Convert the string argument into a string. * @param lexicalXSDString * A lexical representation of the XML Schema datatype xsd:string @@ -93,91 +91,83 @@ public interface DatatypeConverterInterface { public String parseString( String lexicalXSDString ); /** - *

                                * Convert the string argument into a BigInteger value. * @param lexicalXSDInteger * A string containing a lexical representation of * xsd:integer. * @return * A BigInteger value represented by the string argument. - * @throws NumberFormatException lexicalXSDInteger is not a valid string representation of a {@link java.math.BigInteger} value. + * @throws NumberFormatException {@code lexicalXSDInteger} is not a valid string representation of a {@link java.math.BigInteger} value. */ public java.math.BigInteger parseInteger( String lexicalXSDInteger ); /** - *

                                * Convert the string argument into an int value. * @param lexicalXSDInt * A string containing a lexical representation of * xsd:int. * @return * An int value represented byte the string argument. - * @throws NumberFormatException lexicalXSDInt is not a valid string representation of an int value. + * @throws NumberFormatException {@code lexicalXSDInt} is not a valid string representation of an {@code int} value. */ public int parseInt( String lexicalXSDInt ); /** - *

                                * Converts the string argument into a long value. * @param lexicalXSDLong * A string containing lexical representation of * xsd:long. * @return * A long value represented by the string argument. - * @throws NumberFormatException lexicalXSDLong is not a valid string representation of a long value. + * @throws NumberFormatException {@code lexicalXSDLong} is not a valid string representation of a {@code long} value. */ public long parseLong( String lexicalXSDLong ); /** - *

                                * Converts the string argument into a short value. * @param lexicalXSDShort * A string containing lexical representation of * xsd:short. * @return * A short value represented by the string argument. - * @throws NumberFormatException lexicalXSDShort is not a valid string representation of a short value. + * @throws NumberFormatException {@code lexicalXSDShort} is not a valid string representation of a {@code short} value. */ public short parseShort( String lexicalXSDShort ); /** - *

                                * Converts the string argument into a BigDecimal value. * @param lexicalXSDDecimal * A string containing lexical representation of * xsd:decimal. * @return * A BigDecimal value represented by the string argument. - * @throws NumberFormatException lexicalXSDDecimal is not a valid string representation of {@link java.math.BigDecimal}. + * @throws NumberFormatException {@code lexicalXSDDecimal} is not a valid string representation of {@link java.math.BigDecimal}. */ public java.math.BigDecimal parseDecimal( String lexicalXSDDecimal ); /** - *

                                * Converts the string argument into a float value. * @param lexicalXSDFloat * A string containing lexical representation of * xsd:float. * @return * A float value represented by the string argument. - * @throws NumberFormatException lexicalXSDFloat is not a valid string representation of a float value. + * @throws NumberFormatException {@code lexicalXSDFloat} is not a valid string representation of a {@code float} value. */ public float parseFloat( String lexicalXSDFloat ); /** - *

                                * Converts the string argument into a double value. * @param lexicalXSDDouble * A string containing lexical representation of * xsd:double. * @return * A double value represented by the string argument. - * @throws NumberFormatException lexicalXSDDouble is not a valid string representation of a double value. + * @throws NumberFormatException {@code lexicalXSDDouble} is not a valid string representation of a {@code double} value. */ public double parseDouble( String lexicalXSDDouble ); /** - *

                                * Converts the string argument into a boolean value. * @param lexicalXSDBoolean * A string containing lexical representation of @@ -189,20 +179,18 @@ public interface DatatypeConverterInterface { public boolean parseBoolean( String lexicalXSDBoolean ); /** - *

                                * Converts the string argument into a byte value. * @param lexicalXSDByte * A string containing lexical representation of * xsd:byte. * @return * A byte value represented by the string argument. - * @throws NumberFormatException lexicalXSDByte does not contain a parseable byte. + * @throws NumberFormatException {@code lexicalXSDByte} does not contain a parseable byte. * @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:byte. */ public byte parseByte( String lexicalXSDByte ); /** - *

                                * Converts the string argument into a QName value. * *

                                @@ -222,7 +210,6 @@ public interface DatatypeConverterInterface { javax.xml.namespace.NamespaceContext nsc); /** - *

                                * Converts the string argument into a Calendar value. * @param lexicalXSDDateTime * A string containing lexical representation of @@ -234,7 +221,6 @@ public interface DatatypeConverterInterface { public java.util.Calendar parseDateTime( String lexicalXSDDateTime ); /** - *

                                * Converts the string argument into an array of bytes. * @param lexicalXSDBase64Binary * A string containing lexical representation @@ -246,7 +232,6 @@ public interface DatatypeConverterInterface { public byte[] parseBase64Binary( String lexicalXSDBase64Binary ); /** - *

                                * Converts the string argument into an array of bytes. * @param lexicalXSDHexBinary * A string containing lexical representation of @@ -258,7 +243,6 @@ public interface DatatypeConverterInterface { public byte[] parseHexBinary( String lexicalXSDHexBinary ); /** - *

                                * Converts the string argument into a long value. * @param lexicalXSDUnsignedInt * A string containing lexical representation @@ -270,7 +254,6 @@ public interface DatatypeConverterInterface { public long parseUnsignedInt( String lexicalXSDUnsignedInt ); /** - *

                                * Converts the string argument into an int value. * @param lexicalXSDUnsignedShort * A string containing lexical @@ -282,7 +265,6 @@ public interface DatatypeConverterInterface { public int parseUnsignedShort( String lexicalXSDUnsignedShort ); /** - *

                                * Converts the string argument into a Calendar value. * @param lexicalXSDTime * A string containing lexical representation of @@ -294,7 +276,6 @@ public interface DatatypeConverterInterface { public java.util.Calendar parseTime( String lexicalXSDTime ); /** - *

                                * Converts the string argument into a Calendar value. * @param lexicalXSDDate * A string containing lexical representation of @@ -306,7 +287,6 @@ public interface DatatypeConverterInterface { public java.util.Calendar parseDate( String lexicalXSDDate ); /** - *

                                * Return a string containing the lexical representation of the * simple type. * @param lexicalXSDAnySimpleType @@ -319,7 +299,6 @@ public interface DatatypeConverterInterface { public String parseAnySimpleType( String lexicalXSDAnySimpleType ); /** - *

                                * Converts the string argument into a string. * @param val * A string value. @@ -329,7 +308,6 @@ public interface DatatypeConverterInterface { public String printString( String val ); /** - *

                                * Converts a BigInteger value into a string. * @param val * A BigInteger value @@ -340,7 +318,6 @@ public interface DatatypeConverterInterface { public String printInteger( java.math.BigInteger val ); /** - *

                                * Converts an int value into a string. * @param val * An int value @@ -351,7 +328,6 @@ public interface DatatypeConverterInterface { /** - *

                                * Converts a long value into a string. * @param val * A long value @@ -361,7 +337,6 @@ public interface DatatypeConverterInterface { public String printLong( long val ); /** - *

                                * Converts a short value into a string. * @param val * A short value @@ -371,7 +346,6 @@ public interface DatatypeConverterInterface { public String printShort( short val ); /** - *

                                * Converts a BigDecimal value into a string. * @param val * A BigDecimal value @@ -382,7 +356,6 @@ public interface DatatypeConverterInterface { public String printDecimal( java.math.BigDecimal val ); /** - *

                                * Converts a float value into a string. * @param val * A float value @@ -392,7 +365,6 @@ public interface DatatypeConverterInterface { public String printFloat( float val ); /** - *

                                * Converts a double value into a string. * @param val * A double value @@ -402,7 +374,6 @@ public interface DatatypeConverterInterface { public String printDouble( double val ); /** - *

                                * Converts a boolean value into a string. * @param val * A boolean value @@ -412,7 +383,6 @@ public interface DatatypeConverterInterface { public String printBoolean( boolean val ); /** - *

                                * Converts a byte value into a string. * @param val * A byte value @@ -422,7 +392,6 @@ public interface DatatypeConverterInterface { public String printByte( byte val ); /** - *

                                * Converts a QName instance into a string. * @param val * A QName value @@ -437,7 +406,6 @@ public interface DatatypeConverterInterface { javax.xml.namespace.NamespaceContext nsc ); /** - *

                                * Converts a Calendar value into a string. * @param val * A Calendar value @@ -448,7 +416,6 @@ public interface DatatypeConverterInterface { public String printDateTime( java.util.Calendar val ); /** - *

                                * Converts an array of bytes into a string. * @param val * an array of bytes @@ -459,7 +426,6 @@ public interface DatatypeConverterInterface { public String printBase64Binary( byte[] val ); /** - *

                                * Converts an array of bytes into a string. * @param val * an array of bytes @@ -470,7 +436,6 @@ public interface DatatypeConverterInterface { public String printHexBinary( byte[] val ); /** - *

                                * Converts a long value into a string. * @param val * A long value @@ -480,7 +445,6 @@ public interface DatatypeConverterInterface { public String printUnsignedInt( long val ); /** - *

                                * Converts an int value into a string. * @param val * An int value @@ -490,7 +454,6 @@ public interface DatatypeConverterInterface { public String printUnsignedShort( int val ); /** - *

                                * Converts a Calendar value into a string. * @param val * A Calendar value @@ -501,7 +464,6 @@ public interface DatatypeConverterInterface { public String printTime( java.util.Calendar val ); /** - *

                                * Converts a Calendar value into a string. * @param val * A Calendar value @@ -512,7 +474,6 @@ public interface DatatypeConverterInterface { public String printDate( java.util.Calendar val ); /** - *

                                * Converts a string value into a string. * @param val * A string value diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBContext.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBContext.java index 6f435457687..d5dc7bc4a5e 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBContext.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBContext.java @@ -63,10 +63,10 @@ import java.io.InputStream; * SPEC REQUIREMENT: the provider must supply an implementation * class containing the following method signatures: * - *

                                - * public static JAXBContext createContext( String contextPath, ClassLoader classLoader, Map<String,Object> properties ) throws JAXBException
                                - * public static JAXBContext createContext( Class[] classes, Map<String,Object> properties ) throws JAXBException
                                - * 
                                + *
                                {@code
                                + * public static JAXBContext createContext( String contextPath, ClassLoader classLoader, Map properties ) throws JAXBException
                                + * public static JAXBContext createContext( Class[] classes, Map properties ) throws JAXBException
                                + * }
                                * *

                                * The following JAXB 1.0 requirement is only required for schema to @@ -352,7 +352,7 @@ public abstract class JAXBContext { *

                                * To maintain compatibility with JAXB 1.0 schema to java * interface/implementation binding, enabled by schema customization - * <jaxb:globalBindings valueClass="false">, + * {@literal }, * the JAXB provider will ensure that each package on the context path * has a jaxb.properties file which contains a value for the * javax.xml.bind.context.factory property and that all values @@ -526,7 +526,7 @@ public abstract class JAXBContext { * Not only the new context will recognize all the classes specified, * but it will also recognize any classes that are directly/indirectly * referenced statically from the specified classes. Subclasses of - * referenced classes nor @XmlTransient referenced classes + * referenced classes nor @XmlTransient referenced classes * are not registered with JAXBContext. * * For example, in the following Java code, if you do diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBIntrospector.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBIntrospector.java index ad897aeb00c..36e23b9a038 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBIntrospector.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBIntrospector.java @@ -74,7 +74,7 @@ public abstract class JAXBIntrospector { * *

                                Convenience method to abstract whether working with either * a javax.xml.bind.JAXBElement instance or an instance of - * @XmlRootElement annotated Java class.

                                + * @XmlRootElement annotated Java class.

                                * * @param jaxbElement object that #isElement(Object) returns true. * diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBPermission.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBPermission.java index 42dedafaaa6..a4d221d1af3 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBPermission.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/JAXBPermission.java @@ -40,7 +40,6 @@ import java.security.BasicPermission; * The following table lists all the possible {@code JAXBPermission} target names, * and for each provides a description of what the permission allows * and a discussion of the risks of granting code the permission. - *

                                * * * diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/SchemaOutputResolver.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/SchemaOutputResolver.java index 0e36f72591a..1d89d749b8f 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/SchemaOutputResolver.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/SchemaOutputResolver.java @@ -70,11 +70,11 @@ public abstract class SchemaOutputResolver { * * If the {@link Result} object has a system ID, it must be an * absolute system ID. Those system IDs are relativized by the caller and used - * for <xs:import> statements. + * for {@literal } statements. * * If the {@link Result} object does not have a system ID, a schema * for the namespace URI is generated but it won't be explicitly - * <xs:import>ed from other schemas. + * {@literal }ed from other schemas. * * If {@code null} is returned, the schema generation for this * namespace URI will be skipped. diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/ServiceLoaderUtil.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/ServiceLoaderUtil.java new file mode 100644 index 00000000000..159a7c13ca5 --- /dev/null +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/ServiceLoaderUtil.java @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package javax.xml.bind; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Iterator; +import java.util.Properties; +import java.util.ServiceLoader; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Shared ServiceLoader/FactoryFinder Utils shared among SAAJ, JAXB and JAXWS + * - this class must be duplicated to all those projects, but it's + * basically generic code and we want to have it everywhere same. + * + * @author Miroslav.Kos@oracle.com + */ +class ServiceLoaderUtil { + + private static final String OSGI_SERVICE_LOADER_CLASS_NAME = "com.sun.org.glassfish.hk2.osgiresourcelocator.ServiceLoader"; + private static final String OSGI_SERVICE_LOADER_METHOD_NAME = "lookupProviderClasses"; + + static

                                P firstByServiceLoader(Class

                                spiClass, Logger logger) { + // service discovery + ServiceLoader

                                serviceLoader = ServiceLoader.load(spiClass); + for (P impl : serviceLoader) { + logger.fine("ServiceProvider loading Facility used; returning object [" + impl.getClass().getName() + "]"); + return impl; + } + return null; + } + + static boolean isOsgi(Logger logger) { + try { + Class.forName(OSGI_SERVICE_LOADER_CLASS_NAME); + return true; + } catch (ClassNotFoundException ignored) { + logger.log(Level.FINE, "OSGi classes not found, OSGi not available.", ignored); + } + return false; + } + + static Object lookupUsingOSGiServiceLoader(String factoryId, Logger logger) { + try { + // Use reflection to avoid having any dependendcy on ServiceLoader class + Class serviceClass = Class.forName(factoryId); + Class target = Class.forName(OSGI_SERVICE_LOADER_CLASS_NAME); + Method m = target.getMethod(OSGI_SERVICE_LOADER_METHOD_NAME, Class.class); + Iterator iter = ((Iterable) m.invoke(null, serviceClass)).iterator(); + if (iter.hasNext()) { + Object next = iter.next(); + logger.fine("Found implementation using OSGi facility; returning object [" + next.getClass().getName() + "]."); + return next; + } else { + return null; + } + } catch (Exception ignored) { + logger.log(Level.FINE, "Unable to find from OSGi: [" + factoryId + "]", ignored); + return null; + } + } + + static String propertyFileLookup(final String configFullPath, final String factoryId) throws IOException { + File f = new File(configFullPath); + String factoryClassName = null; + if (f.exists()) { + Properties props = new Properties(); + FileInputStream stream = null; + try { + stream = new FileInputStream(f); + props.load(stream); + factoryClassName = props.getProperty(factoryId); + } finally { + if (stream != null) { + try { + stream.close(); + } catch (IOException ignored) { + } + } + } + } + return factoryClassName; + } + + static void checkPackageAccess(String className) { + // make sure that the current thread has an access to the package of the given name. + SecurityManager s = System.getSecurityManager(); + if (s != null) { + int i = className.lastIndexOf('.'); + if (i != -1) { + s.checkPackageAccess(className.substring(0, i)); + } + } + } + + static Class nullSafeLoadClass(String className, ClassLoader classLoader) throws ClassNotFoundException { + if (classLoader == null) { + return Class.forName(className); + } else { + return classLoader.loadClass(className); + } + } + + /** + * Returns instance of required class. It checks package access (security) unless it is defaultClassname. It means if you + * are trying to instantiate default implementation (fallback), pass the class name to both first and second parameter. + * + * @param className class to be instantiated + * @param isDefaultClassname says whether default implementation class + * @param handler exception handler - necessary for wrapping exceptions and logging + * @param Type of exception being thrown (necessary to distinguish between Runtime and checked exceptions) + * @return instantiated object or throws Runtime/checked exception, depending on ExceptionHandler's type + * @throws T + */ + static Object newInstance(String className, String defaultImplClassName, final ExceptionHandler handler) throws T { + try { + return safeLoadClass(className, defaultImplClassName, contextClassLoader(handler)).newInstance(); + } catch (ClassNotFoundException x) { + throw handler.createException(x, "Provider " + className + " not found"); + } catch (Exception x) { + throw handler.createException(x, "Provider " + className + " could not be instantiated: " + x); + } + } + + static Class safeLoadClass(String className, String defaultImplClassName, ClassLoader classLoader) throws ClassNotFoundException { + try { + checkPackageAccess(className); + } catch (SecurityException se) { + // anyone can access the platform default factory class without permission + if (defaultImplClassName != null && defaultImplClassName.equals(className)) { + return Class.forName(className); + } + // not platform default implementation ... + throw se; + } + return nullSafeLoadClass(className, classLoader); + } + + static String getJavaHomeLibConfigPath(String filename) { + String javah = AccessController.doPrivileged(new PrivilegedAction() { + @Override + public String run() { + return System.getProperty("java.home"); + } + }); + return javah + File.separator + "lib" + File.separator + filename; + } + + static ClassLoader contextClassLoader(ExceptionHandler exceptionHandler) throws Exception { + try { + return Thread.currentThread().getContextClassLoader(); + } catch (Exception x) { + throw exceptionHandler.createException(x, x.toString()); + } + } + + static abstract class ExceptionHandler { + + public abstract T createException(Throwable throwable, String message); + + } + +} diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/Unmarshaller.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/Unmarshaller.java index d966659fd2d..fa183ad07b1 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/Unmarshaller.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/Unmarshaller.java @@ -73,12 +73,12 @@ import java.io.Reader; * Unmarshalling from a StringBuffer using a * javax.xml.transform.stream.StreamSource: *

                                - *
                                + *    
                                {@code
                                  *       JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
                                  *       Unmarshaller u = jc.createUnmarshaller();
                                - *       StringBuffer xmlStr = new StringBuffer( "<?xml version="1.0"?>..." );
                                + *       StringBuffer xmlStr = new StringBuffer( "..." );
                                  *       Object o = u.unmarshal( new StreamSource( new StringReader( xmlStr.toString() ) ) );
                                - *    
                                + * }
                                *
                                * *

                                @@ -238,7 +238,7 @@ import java.io.Reader; * to a JAXB mapped class by {@link JAXBContext}, that the root * element's xsi:type attribute takes * precedence over the unmarshal methods declaredType parameter. - * These methods always return a JAXBElement<declaredType> + * These methods always return a {@literal JAXBElement} * instance. The table below shows how the properties of the returned JAXBElement * instance are set. * @@ -281,21 +281,21 @@ import java.io.Reader; *

                                * Unmarshal by declaredType from a org.w3c.dom.Node: *

                                - *
                                + *    
                                {@code
                                  *       Schema fragment for example
                                - *       <xs:schema>
                                - *          <xs:complexType name="FooType">...<\xs:complexType>
                                - *          <!-- global element declaration "PurchaseOrder" -->
                                - *          <xs:element name="PurchaseOrder">
                                - *              <xs:complexType>
                                - *                 <xs:sequence>
                                - *                    <!-- local element declaration "foo" -->
                                - *                    <xs:element name="foo" type="FooType"/>
                                + *       
                                + *          ...<\xs:complexType>
                                + *          
                                + *          
                                + *              
                                + *                 
                                + *                    
                                + *                    
                                  *                    ...
                                - *                 </xs:sequence>
                                - *              </xs:complexType>
                                - *          </xs:element>
                                - *       </xs:schema>
                                + *                 
                                + *              
                                + *          
                                + *       
                                  *
                                  *       JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
                                  *       Unmarshaller u = jc.createUnmarshaller();
                                @@ -308,8 +308,8 @@ import java.io.Reader;
                                  *                                  // local element declaration in schema.
                                  *
                                  *       // FooType is the JAXB mapping of the type of local element declaration foo.
                                - *       JAXBElement<FooType> foo = u.unmarshal( fooSubtree, FooType.class);
                                - *    
                                + * JAXBElement foo = u.unmarshal( fooSubtree, FooType.class); + * }
                                *
                                * *

                                diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlAnyElement.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlAnyElement.java index 0fcd2dc372f..ce76369549a 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlAnyElement.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlAnyElement.java @@ -94,15 +94,15 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; *

                                Schema To Java example

                                * * The following schema would produce the following Java class: - *
                                - * <xs:complexType name="foo">
                                - *   <xs:sequence>
                                - *     <xs:element name="a" type="xs:int" />
                                - *     <xs:element name="b" type="xs:int" />
                                - *     <xs:any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded" />
                                - *   </xs:sequence>
                                - * </xs:complexType>
                                - * 
                                + *
                                {@code
                                + * 
                                + *   
                                + *     
                                + *     
                                + *     
                                + *   
                                + * 
                                + * }
                                * *
                                  * class Foo {
                                @@ -115,30 +115,30 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
                                  *
                                  * It can unmarshal instances like
                                  *
                                - * 
                                - * <foo xmlns:e="extra">
                                - *   <a>1</a>
                                - *   <e:other />  // this will be bound to DOM, because unmarshalling is orderless
                                - *   <b>3</b>
                                - *   <e:other />
                                - *   <c>5</c>     // this will be bound to DOM, because the annotation doesn't remember namespaces.
                                - * </foo>
                                - * 
                                + *
                                {@code
                                + * 
                                + *   1
                                + *     // this will be bound to DOM, because unmarshalling is orderless
                                + *   3
                                + *   
                                + *   5     // this will be bound to DOM, because the annotation doesn't remember namespaces.
                                + * 
                                + * }
                                * * * * The following schema would produce the following Java class: - *
                                - * <xs:complexType name="bar">
                                - *   <xs:complexContent>
                                - *   <xs:extension base="foo">
                                - *     <xs:sequence>
                                - *       <xs:element name="c" type="xs:int" />
                                - *       <xs:any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded" />
                                - *     </xs:sequence>
                                - *   </xs:extension>
                                - * </xs:complexType>
                                - * 
                                + *
                                {@code
                                + * 
                                + *   
                                + *   
                                + *     
                                + *       
                                + *       
                                + *     
                                + *   
                                + * 
                                + * }
                                * *
                                  * class Bar extends Foo {
                                @@ -150,16 +150,16 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
                                  *
                                  * It can unmarshal instances like
                                  *
                                - * 
                                - * <bar xmlns:e="extra">
                                - *   <a>1</a>
                                - *   <e:other />  // this will be bound to DOM, because unmarshalling is orderless
                                - *   <b>3</b>
                                - *   <e:other />
                                - *   <c>5</c>     // this now goes to Bar.c
                                - *   <e:other />  // this will go to Foo.any
                                - * </bar>
                                - * 
                                + *
                                {@code
                                + * 
                                + *   1
                                + *     // this will be bound to DOM, because unmarshalling is orderless
                                + *   3
                                + *   
                                + *   5     // this now goes to Bar.c
                                + *     // this will go to Foo.any
                                + * 
                                + * }
                                * * * @@ -171,15 +171,15 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; * *

                                * The following schema would produce the following Java class: - *

                                - * <xs:complexType name="foo">
                                - *   <xs:choice maxOccurs="unbounded" minOccurs="0">
                                - *     <xs:element name="a" type="xs:int" />
                                - *     <xs:element name="b" type="xs:int" />
                                - *     <xs:any namespace="##other" processContents="lax" />
                                - *   </xs:choice>
                                - * </xs:complexType>
                                - * 
                                + *
                                {@code
                                + * 
                                + *   
                                + *     
                                + *     
                                + *     
                                + *   
                                + * 
                                + * }
                                * *
                                  * class Foo {
                                @@ -204,11 +204,11 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
                                  * It can unmarshal instances like
                                  *
                                  * 
                                - * <foo xmlns:e="extra">
                                - *   <a>1</a>     // this will unmarshal to a {@link JAXBElement} instance whose value is 1.
                                - *   <e:other />  // this will unmarshal to a DOM {@link Element}.
                                - *   <b>3</b>     // this will unmarshal to a {@link JAXBElement} instance whose value is 1.
                                - * </foo>
                                + *{@code }
                                + *{@code   1}     // this will unmarshal to a {@link JAXBElement} instance whose value is 1.
                                + *{@code   }  // this will unmarshal to a DOM {@link Element}.
                                + *{@code   3}     // this will unmarshal to a {@link JAXBElement} instance whose value is 1.
                                + *{@code }
                                  * 
                                * * @@ -225,11 +225,11 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; * } *
                                * then the following document will unmarshal like this: - *
                                - * <foo>
                                - *   <unknown />
                                - *   <foo />
                                - * </foo>
                                + * 
                                {@code
                                + * 
                                + *   
                                + *   
                                + * 
                                  *
                                  * Foo foo = unmarshal();
                                  * // 1 for 'unknown', another for 'foo'
                                @@ -239,7 +239,7 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
                                  * // because of lax=true, the 'foo' element eagerly
                                  * // unmarshals to a Foo object.
                                  * assert foo.others[1] instanceof Foo;
                                - * 
                                + * }
                                * * @author Kohsuke Kawaguchi * @since 1.6, JAXB 2.0 diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlAttachmentRef.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlAttachmentRef.java index 92d8e91eb3a..a658a0801cb 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlAttachmentRef.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlAttachmentRef.java @@ -51,16 +51,16 @@ import java.lang.annotation.Target; * } *
                                * The above code maps to the following XML: - *
                                - * <xs:element name="foo" xmlns:ref="http://ws-i.org/profiles/basic/1.1/xsd">
                                - *   <xs:complexType>
                                - *     <xs:sequence>
                                - *       <xs:element name="body" type="ref:swaRef" minOccurs="0" />
                                - *     </xs:sequence>
                                - *     <xs:attribute name="data" type="ref:swaRef" use="optional" />
                                - *   </xs:complexType>
                                - * </xs:element>
                                - * 
                                + *
                                {@code
                                + * 
                                + *   
                                + *     
                                + *       
                                + *     
                                + *     
                                + *   
                                + * 
                                + * }
                                * *

                                * The above binding supports WS-I AP 1.0 WS-I Attachments Profile Version 1.0. diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlAttribute.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlAttribute.java index 8e367582ca3..713c5c0f5c0 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlAttribute.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlAttribute.java @@ -89,14 +89,15 @@ import static java.lang.annotation.RetentionPolicy.*; * public java.math.BigDecimal getPrice() {...} ; * public void setPrice(java.math.BigDecimal ) {...}; * } + * {@code * - * <!-- Example: XML Schema fragment --> - * <xs:complexType name="USPrice"> - * <xs:sequence> - * </xs:sequence> - * <xs:attribute name="price" type="xs:decimal"/> - * </xs:complexType> - *

                                + * + * + * + * + * + * + * } * *

                                Example 2: Map a JavaBean property to an XML attribute with anonymous type.

                                * See Example 7 in @{@link XmlType}. @@ -108,17 +109,18 @@ import static java.lang.annotation.RetentionPolicy.*; * ... * @XmlAttribute List<Integer> items; * } + * {@code * - * <!-- Example: XML Schema fragment --> - * <xs:complexType name="foo"> + * + * * ... - * <xs:attribute name="items"> - * <xs:simpleType> - * <xs:list itemType="xs:int"/> - * </xs:simpleType> - * </xs:complexType> + * + * + * + * + * * - * + * } * @author Sekhar Vajjhala, Sun Microsystems, Inc. * @see XmlType * @since 1.6, JAXB 2.0 diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElement.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElement.java index 3d7c89dc836..aa752d31040 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElement.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElement.java @@ -36,7 +36,7 @@ import static java.lang.annotation.RetentionPolicy.*; /** * Maps a JavaBean property to a XML element derived from property name. * - *

                                Usage

                                + *

                                Usage *

                                * @XmlElement annotation can be used with the following program * elements: @@ -44,8 +44,6 @@ import static java.lang.annotation.RetentionPolicy.*; *

                              • a JavaBean property
                              • *
                              • non static, non transient field
                              • *
                              • within {@link XmlElements} - *

                                - * * * * The usage is subject to the following constraints: @@ -79,59 +77,59 @@ import static java.lang.annotation.RetentionPolicy.*; *

                                  *     //Example: Code fragment
                                  *     public class USPrice {
                                - *         @XmlElement(name="itemprice")
                                + *        {@literal @}XmlElement(name="itemprice")
                                  *         public java.math.BigDecimal price;
                                  *     }
                                + * {@code
                                  *
                                - *     <!-- Example: Local XML Schema element -->
                                - *     <xs:complexType name="USPrice"/>
                                - *       <xs:sequence>
                                - *         <xs:element name="itemprice" type="xs:decimal" minOccurs="0"/>
                                - *       </sequence>
                                - *     </xs:complexType>
                                - *   
                                + * + * + * + * + * + * + * } *

                                * * Example 2: Map a field to a nillable element. *

                                - *
                                  *     //Example: Code fragment
                                  *     public class USPrice {
                                - *         @XmlElement(nillable=true)
                                + *        {@literal @}XmlElement(nillable=true)
                                  *         public java.math.BigDecimal price;
                                  *     }
                                + * {@code
                                  *
                                - *     <!-- Example: Local XML Schema element -->
                                - *     <xs:complexType name="USPrice">
                                - *       <xs:sequence>
                                - *         <xs:element name="price" type="xs:decimal" nillable="true" minOccurs="0"/>
                                - *       </sequence>
                                - *     </xs:complexType>
                                - *   
                                + * + * + * + * + * + * + * } *

                                * Example 3: Map a field to a nillable, required element. *

                                - *
                                  *     //Example: Code fragment
                                  *     public class USPrice {
                                - *         @XmlElement(nillable=true, required=true)
                                + *        {@literal @}XmlElement(nillable=true, required=true)
                                  *         public java.math.BigDecimal price;
                                  *     }
                                + * {@code
                                  *
                                - *     <!-- Example: Local XML Schema element -->
                                - *     <xs:complexType name="USPrice">
                                - *       <xs:sequence>
                                - *         <xs:element name="price" type="xs:decimal" nillable="true" minOccurs="1"/>
                                - *       </sequence>
                                - *     </xs:complexType>
                                - *   
                                + * + * + * + * + * + * + * } * *

                                Example 4: Map a JavaBean property to an XML element * with anonymous type.

                                *

                                * See Example 6 in @{@link XmlType}. * - *

                                * @author Sekhar Vajjhala, Sun Microsystems, Inc. * @since 1.6, JAXB 2.0 */ @@ -179,7 +177,7 @@ public @interface XmlElement { * the enclosing class. * *

                              • - * Otherwise '' (which produces unqualified element in the default + * Otherwise {@literal ''} (which produces unqualified element in the default * namespace. * */ diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElementDecl.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElementDecl.java index 6920957a5e6..6d791e95c05 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElementDecl.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElementDecl.java @@ -65,21 +65,22 @@ import static java.lang.annotation.ElementType.METHOD; * JAXBElement<String> createFoo(String s) { ... } * } * - *
                                - *     <!-- XML input -->
                                - *       <foo>string</foo>
                                + * 
                                 {@code
                                + *
                                + *     
                                + *     string
                                  *
                                  *     // Example: code fragment corresponding to XML input
                                - *     JAXBElement<String> o =
                                - *     (JAXBElement<String>)unmarshaller.unmarshal(aboveDocument);
                                + *     JAXBElement o =
                                + *     (JAXBElement)unmarshaller.unmarshal(aboveDocument);
                                  *     // print JAXBElement instance to show values
                                  *     System.out.println(o.getName());   // prints  "{}foo"
                                  *     System.out.println(o.getValue());  // prints  "string"
                                  *     System.out.println(o.getValue().getClass()); // prints "java.lang.String"
                                  *
                                - *     <!-- Example: XML schema definition -->
                                - *     <xs:element name="foo" type="xs:string"/>
                                - * 
                                + * + * + * }
                                * *

                                Example 2: Element declaration with non local scope *

                                @@ -90,18 +91,18 @@ import static java.lang.annotation.ElementType.METHOD; * The following example may be replaced in a future revision of * this javadoc. * - *

                                - *     <!-- Example: XML schema definition -->
                                - *     <xs:schema>
                                - *       <xs:complexType name="pea">
                                - *         <xs:choice maxOccurs="unbounded">
                                - *           <xs:element name="foo" type="xs:string"/>
                                - *           <xs:element name="bar" type="xs:string"/>
                                - *         </xs:choice>
                                - *       </xs:complexType>
                                - *       <xs:element name="foo" type="xs:int"/>
                                - *     </xs:schema>
                                - * 
                                + *
                                {@code
                                + *     
                                + *     
                                + *       
                                + *         
                                + *           
                                + *           
                                + *         
                                + *       
                                + *       
                                + *     
                                + * }
                                *
                                  *     // Example: expected default binding
                                  *     class Pea {
                                diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElementRef.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElementRef.java
                                index 9f99ca3d80b..b420d7b1414 100644
                                --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElementRef.java
                                +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElementRef.java
                                @@ -56,10 +56,10 @@ import static java.lang.annotation.ElementType.METHOD;
                                  * support for substitution groups using an element property,
                                  * (section 5.5.5, "Element Property" of JAXB 2.0 specification). An
                                  * element property method signature is of the form:
                                - * 
                                - *     public void setTerm(JAXBElement<? extends Operator>);
                                - *     public JAXBElement<? extends Operator> getTerm();
                                - * 
                                + *
                                {@code
                                + *     public void setTerm(JAXBElement);
                                + *     public JAXBElement getTerm();
                                + * }
                                *

                                * An element factory method annotated with {@link XmlElementDecl} is * used to create a JAXBElement instance, containing an XML @@ -121,19 +121,20 @@ import static java.lang.annotation.ElementType.METHOD; * class JavacTask extends Task { * ... * } + * {@code * - * <!-- XML Schema fragment --> - * <xs:element name="target" type="Target"> - * <xs:complexType name="Target"> - * <xs:sequence> - * <xs:choice maxOccurs="unbounded"> - * <xs:element ref="jar"> - * <xs:element ref="javac"> - * </xs:choice> - * </xs:sequence> - * </xs:complexType> + * + * + * + * + * + * + * + * + * + * * - *

                                + * } *

                                * Thus the following code fragment: *

                                @@ -143,16 +144,16 @@ import static java.lang.annotation.ElementType.METHOD;
                                  *     marshal(target);
                                  * 
                                * will produce the following XML output: - *
                                - *     <target>
                                - *       <jar>
                                + * 
                                {@code
                                + *     
                                + *       
                                  *         ....
                                - *       </jar>
                                - *       <javac>
                                + *       
                                + *       
                                  *         ....
                                - *       </javac>
                                - *     </target>
                                - * 
                                + * + * + * }
                                *

                                * It is not an error to have a class that extends Task * that doesn't have {@link XmlRootElement}. But they can't show up in an @@ -207,11 +208,11 @@ import static java.lang.annotation.ElementType.METHOD; * marshal(m); * * will produce the following XML output: - *

                                - *     <math>
                                - *       <add>...</add>
                                - *     </math>
                                - * 
                                + *
                                {@code
                                + *     
                                + *       ...
                                + *     
                                + * }
                                * * * @author
                                • Kohsuke Kawaguchi, Sun Microsystems,Inc.
                                • Sekhar Vajjhala, Sun Microsystems, Inc.
                                diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElementWrapper.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElementWrapper.java index fc7d09c05e8..69f50411fdc 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElementWrapper.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElementWrapper.java @@ -39,21 +39,21 @@ import java.lang.annotation.Target; * XML element around collections. The annotation therefore supports * two forms of serialization shown below. * - *
                                + * 
                                {@code
                                  *    //Example: code fragment
                                  *      int[] names;
                                  *
                                  *    // XML Serialization Form 1 (Unwrapped collection)
                                - *    <names> ... </names>
                                - *    <names> ... </names>
                                + *     ... 
                                + *     ... 
                                  *
                                  *    // XML Serialization Form 2 ( Wrapped collection )
                                - *    <wrapperElement>
                                - *       <names> value-of-item </names>
                                - *       <names> value-of-item </names>
                                + *    
                                + *        value-of-item 
                                + *        value-of-item 
                                  *       ....
                                - *    </wrapperElement>
                                - * 
                                + * + * }
                                * *

                                The two serialized XML forms allow a null collection to be * represented either by absence or presence of an element with a diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElements.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElements.java index e15bb1e4146..fb64513d697 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElements.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlElements.java @@ -44,7 +44,7 @@ import java.lang.annotation.Target; * @XmlElements({ @XmlElement(...),@XmlElement(...) }) * * - *

                                The @XmlElements annnotation can be used with the + *

                                The @XmlElements annotation can be used with the * following program elements:

                                *
                                  *
                                • a JavaBean property
                                • @@ -78,28 +78,29 @@ import java.lang.annotation.Target; * @XmlElements( * @XmlElement(name="A", type=Integer.class), * @XmlElement(name="B", type=Float.class) - * } + * ) * public List items; * } + * {@code * - * <!-- XML Representation for a List of {1,2.5} - * XML output is not wrapped using another element --> + * * ... - * <A> 1 </A> - * <B> 2.5 </B> + * 1 + * 2.5 * ... * - * <!-- XML Schema fragment --> - * <xs:complexType name="Foo"> - * <xs:sequence> - * <xs:choice minOccurs="0" maxOccurs="unbounded"> - * <xs:element name="A" type="xs:int"/> - * <xs:element name="B" type="xs:float"/> - * <xs:choice> - * </xs:sequence> - * </xs:complexType> + * + * + * + * + * + * + * + * + * * - * + * } * *

                                  Example 2: Map to a list of elements wrapped with another element *

                                  @@ -114,21 +115,22 @@ import java.lang.annotation.Target; * } * public List items; * } + * {@code * - * <!-- XML Schema fragment --> - * <xs:complexType name="Foo"> - * <xs:sequence> - * <xs:element name="bar"> - * <xs:complexType> - * <xs:choice minOccurs="0" maxOccurs="unbounded"> - * <xs:element name="A" type="xs:int"/> - * <xs:element name="B" type="xs:float"/> - * </xs:choice> - * </xs:complexType> - * </xs:element> - * </xs:sequence> - * </xs:complexType> - * + * + * + * + * + * + * + * + * + * + * + * + * + * + * } * *

                                  Example 3: Change element name based on type using an adapter. *

                                  @@ -145,21 +147,22 @@ import java.lang.annotation.Target; * @XmlType abstract class P {...} * @XmlType(name="PX") class PX extends P {...} * @XmlType(name="PY") class PY extends P {...} + * {@code * - * <!-- XML Schema fragment --> - * <xs:complexType name="Foo"> - * <xs:sequence> - * <xs:element name="bar"> - * <xs:complexType> - * <xs:choice minOccurs="0" maxOccurs="unbounded"> - * <xs:element name="A" type="PX"/> - * <xs:element name="B" type="PY"/> - * </xs:choice> - * </xs:complexType> - * </xs:element> - * </xs:sequence> - * </xs:complexType> - * + * + * + * + * + * + * + * + * + * + * + * + * + * + * } * * @author
                                  • Kohsuke Kawaguchi, Sun Microsystems, Inc.
                                  • Sekhar Vajjhala, Sun Microsystems, Inc.
                                  * @see XmlElement diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlEnumValue.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlEnumValue.java index bcdebcb1a5f..fc29ac0786b 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlEnumValue.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlEnumValue.java @@ -56,23 +56,24 @@ import static java.lang.annotation.ElementType.FIELD; *

                                  In the absence of this annotation, {@link Enum#name()} is used * as the XML representation. * - *

                                  Example 1: Map enum constant name -> enumeration facet

                                  + *

                                  Example 1: Map enum constant name {@literal ->} enumeration facet

                                  *
                                    *     //Example: Code fragment
                                    *     @XmlEnum(String.class)
                                    *     public enum Card { CLUBS, DIAMONDS, HEARTS, SPADES }
                                  + * {@code
                                    *
                                  - *     <!-- Example: XML Schema fragment -->
                                  - *     <xs:simpleType name="Card">
                                  - *       <xs:restriction base="xs:string"/>
                                  - *         <xs:enumeration value="CLUBS"/>
                                  - *         <xs:enumeration value="DIAMONDS"/>
                                  - *         <xs:enumeration value="HEARTS"/>
                                  - *         <xs:enumeration value="SPADES"/>
                                  - *     </xs:simpleType>
                                  - * 
                                  + * + * + * + * + * + * + * + * + * } * - *

                                  Example 2: Map enum constant name(value) -> enumeration facet

                                  + *

                                  Example 2: Map enum constant name(value) {@literal ->} enumeration facet

                                  *
                                    *     //Example: code fragment
                                    *     @XmlType
                                  @@ -82,19 +83,20 @@ import static java.lang.annotation.ElementType.FIELD;
                                    *         @XmlEnumValue("5") NICKEL(5),
                                    *         @XmlEnumValue("10") DIME(10),
                                    *         @XmlEnumValue("25") QUARTER(25) }
                                  + * {@code
                                    *
                                  - *     <!-- Example: XML Schema fragment -->
                                  - *     <xs:simpleType name="Coin">
                                  - *       <xs:restriction base="xs:int">
                                  - *         <xs:enumeration value="1"/>
                                  - *         <xs:enumeration value="5"/>
                                  - *         <xs:enumeration value="10"/>
                                  - *         <xs:enumeration value="25"/>
                                  - *       </xs:restriction>
                                  - *     </xs:simpleType>
                                  - * 
                                  + * + * + * + * + * + * + * + * + * + * } * - *

                                  Example 3: Map enum constant name -> enumeration facet

                                  + *

                                  Example 3: Map enum constant name {@literal ->} enumeration facet

                                  * *
                                    *     //Code fragment
                                  @@ -104,15 +106,16 @@ import static java.lang.annotation.ElementType.FIELD;
                                    *         @XmlEnumValue("1") ONE,
                                    *         @XmlEnumValue("2") TWO;
                                    *     }
                                  + * {@code
                                    *
                                  - *     <!-- Example: XML Schema fragment -->
                                  - *     <xs:simpleType name="Code">
                                  - *       <xs:restriction base="xs:int">
                                  - *         <xs:enumeration value="1"/>
                                  - *         <xs:enumeration value="2"/>
                                  - *       </xs:restriction>
                                  - *     </xs:simpleType>
                                  - * 
                                  + * + * + * + * + * + * + * + * } * * @since 1.6, JAXB 2.0 */ diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlID.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlID.java index 441dc5d101b..52d03609f02 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlID.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlID.java @@ -73,17 +73,18 @@ import static java.lang.annotation.RetentionPolicy.*; * public void setCustomerID(String id); * .... other properties not shown * } + * {@code * - * <!-- Example: XML Schema fragment --> - * <xs:complexType name="Customer"> - * <xs:complexContent> - * <xs:sequence> + * + * + * + * * .... - * </xs:sequence> - * <xs:attribute name="customerID" type="xs:ID"/> - * </xs:complexContent> - * </xs:complexType> - * + * + * + * + * + * } * * @author Sekhar Vajjhala, Sun Microsystems, Inc. * @see XmlIDREF diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlIDREF.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlIDREF.java index 2ad68419da9..503f936d03e 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlIDREF.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlIDREF.java @@ -37,7 +37,7 @@ import static java.lang.annotation.RetentionPolicy.*; *

                                  * To preserve referential integrity of an object graph across XML * serialization followed by a XML deserialization, requires an object - * reference to be marshalled by reference or containment + * reference to be marshaled by reference or containment * appropriately. Annotations @XmlID and @XmlIDREF * together allow a customized mapping of a JavaBean property's * type by containment or reference. @@ -82,18 +82,19 @@ import static java.lang.annotation.RetentionPolicy.*; * public void setCustomer(Customer customer); * .... * } + * {@code * - * <!-- Example: XML Schema fragment --> - * <xs:complexType name="Shipping"> - * <xs:complexContent> - * <xs:sequence> - * <xs:element name="customer" type="xs:IDREF"/> + * + * + * + * + * * .... - * </xs:sequence> - * </xs:complexContent> - * </xs:complexType> + * + * + * * - * + * } * * *

                                  Example 2: The following is a complete example of @@ -142,64 +143,65 @@ import static java.lang.annotation.RetentionPolicy.*; * // maps reference to Invoice by containment by default. * public Invoice getInvoice(); * } + * {@code * - * <!-- XML Schema mapping for above code frament --> + * * - * <xs:complexType name="Invoice"> - * <xs:complexContent> - * <xs:sequence> - * <xs:element name="customer" type="xs:IDREF"/> + * + * + * + * * .... - * </xs:sequence> - * </xs:complexContent> - * </xs:complexType> + * + * + * * - * <xs:complexType name="Shipping"> - * <xs:complexContent> - * <xs:sequence> - * <xs:element name="customer" type="xs:IDREF"/> + * + * + * + * * .... - * </xs:sequence> - * </xs:complexContent> - * </xs:complexType> + * + * + * * - * <xs:complexType name="Customer"> - * <xs:complexContent> - * <xs:sequence> + * + * + * * .... - * </xs:sequence> - * <xs:attribute name="CustomerID" type="xs:ID"/> - * </xs:complexContent> - * </xs:complexType> + * + * + * + * * - * <xs:complexType name="CustomerData"> - * <xs:complexContent> - * <xs:sequence> - * <xs:element name="customer" type="xs:Customer"/> - * <xs:element name="shipping" type="xs:Shipping"/> - * <xs:element name="invoice" type="xs:Invoice"/> - * </xs:sequence> - * </xs:complexContent> - * </xs:complexType> + * + * + * + * + * + * + * + * + * * - * <xs:element name"customerData" type="xs:CustomerData"/> + * * - * <!-- Instance document conforming to the above XML Schema --> - * <customerData> - * <customer customerID="Alice"> + * + * + * * .... - * </customer> + * * - * <shipping customer="Alice"> + * * .... - * </shipping> + * * - * <invoice customer="Alice"> + * * .... - * </invoice> - * </customerData> + * + * * - * + * } * *

                                  Example 3: Mapping List to repeating element of type IDREF *

                                  @@ -209,16 +211,17 @@ import static java.lang.annotation.RetentionPolicy.*;
                                    *         @XmlElement(name="Alice")
                                    *             public List customers;
                                    *     }
                                  + * {@code
                                    *
                                  - *     <!-- XML schema fragment -->
                                  - *     <xs:complexType name="Shipping">
                                  - *       <xs:sequence>
                                  - *         <xs:choice minOccurs="0" maxOccurs="unbounded">
                                  - *           <xs:element name="Alice" type="xs:IDREF"/>
                                  - *         </xs:choice>
                                  - *       </xs:sequence>
                                  - *     </xs:complexType>
                                  - * 
                                  + * + * + * + * + * + * + * + * + * } * *

                                  Example 4: Mapping a List to a list of elements of type IDREF. *

                                  @@ -230,17 +233,18 @@ import static java.lang.annotation.RetentionPolicy.*;
                                    *              @XmlElement(name="John", type="InternationalCustomer.class")
                                    *         public List customers;
                                    *     }
                                  + * {@code
                                    *
                                  - *     <!-- XML Schema fragment -->
                                  - *     <xs:complexType name="Shipping">
                                  - *       <xs:sequence>
                                  - *         <xs:choice minOccurs="0" maxOccurs="unbounded">
                                  - *           <xs:element name="Alice" type="xs:IDREF"/>
                                  - *           <xs:element name="John" type="xs:IDREF"/>
                                  - *         </xs:choice>
                                  - *       </xs:sequence>
                                  - *     </xs:complexType>
                                  - * 
                                  + * + * + * + * + * + * + * + * + * + * } * @author Sekhar Vajjhala, Sun Microsystems, Inc. * @see XmlID * @since 1.6, JAXB 2.0 diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlList.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlList.java index 9bd81d03355..675fbb4b7f2 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlList.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlList.java @@ -59,12 +59,12 @@ import static java.lang.annotation.ElementType.PARAMETER; * * would produce XML like this: * - *
                                  - * <foo>
                                  - *   <data>abc</data>
                                  - *   <data>def</data>
                                  - * </foo>
                                  - * 
                                  + *
                                  {@code
                                  + * 
                                  + *   abc
                                  + *   def
                                  + * 
                                  + * }
                                  * * @XmlList annotation, on the other hand, allows multiple values to be * represented as whitespace-separated tokens in a single element. For example, @@ -80,11 +80,11 @@ import static java.lang.annotation.ElementType.PARAMETER; * * the above code will produce XML like this: * - *
                                  - * <foo>
                                  - *   <data>abc def</data>
                                  - * </foo>
                                  - * 
                                  + *
                                  {@code
                                  + * 
                                  + *   abc def
                                  + * 
                                  + * }
                                  * *

                                  This annotation can be used with the following annotations: * {@link XmlElement}, diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlMixed.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlMixed.java index 83c5da66d12..87d160d54d6 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlMixed.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlMixed.java @@ -56,32 +56,33 @@ import javax.xml.bind.JAXBElement; *

                                * * Below is an example of binding and creation of mixed content. - *
                                - *  <!-- schema fragment having  mixed content -->
                                - *  <xs:complexType name="letterBody" mixed="true">
                                - *    <xs:sequence>
                                - *      <xs:element name="name" type="xs:string"/>
                                - *      <xs:element name="quantity" type="xs:positiveInteger"/>
                                - *      <xs:element name="productName" type="xs:string"/>
                                - *      <!-- etc. -->
                                - *    </xs:sequence>
                                - *  </xs:complexType>
                                - *  <xs:element name="letterBody" type="letterBody"/>
                                + * 
                                {@code
                                + *
                                + *  
                                + *  
                                + *    
                                + *      
                                + *      
                                + *      
                                + *      
                                + *    
                                + *  
                                + *  
                                  *
                                  * // Schema-derived Java code:
                                  * // (Only annotations relevant to mixed content are shown below,
                                - * //  others are ommitted.)
                                + * //  others are omitted.)
                                  * import java.math.BigInteger;
                                  * public class ObjectFactory {
                                  *      // element instance factories
                                - *      JAXBElement<LetterBody> createLetterBody(LetterBody value);
                                - *      JAXBElement<String>     createLetterBodyName(String value);
                                - *      JAXBElement<BigInteger> createLetterBodyQuantity(BigInteger value);
                                - *      JAXBElement<String>     createLetterBodyProductName(String value);
                                + *      JAXBElement createLetterBody(LetterBody value);
                                + *      JAXBElement     createLetterBodyName(String value);
                                + *      JAXBElement createLetterBodyQuantity(BigInteger value);
                                + *      JAXBElement     createLetterBodyProductName(String value);
                                  *      // type instance factory
                                  *      LetterBody createLetterBody();
                                  * }
                                - * 
                                + * }
                                *
                                  * public class LetterBody {
                                  *      // Mixed content can contain instances of Element classes
                                @@ -96,17 +97,17 @@ import javax.xml.bind.JAXBElement;
                                  * }
                                  * 
                                * The following is an XML instance document with mixed content - *
                                - * <letterBody>
                                - * Dear Mr.<name>Robert Smith</name>
                                - * Your order of <quantity>1</quantity> <productName>Baby
                                - * Monitor</productName> shipped from our warehouse. ....
                                - * </letterBody>
                                - * 
                                + *
                                {@code
                                + * 
                                + * Dear Mr.Robert Smith
                                + * Your order of 1 Baby
                                + * Monitor shipped from our warehouse. ....
                                + * 
                                + * }
                                * that can be constructed using following JAXB API calls. - *
                                + * 
                                {@code
                                  * LetterBody lb = ObjectFactory.createLetterBody();
                                - * JAXBElement<LetterBody> lbe = ObjectFactory.createLetterBody(lb);
                                + * JAXBElement lbe = ObjectFactory.createLetterBody(lb);
                                  * List gcl = lb.getContent();  //add mixed content to general content property.
                                  * gcl.add("Dear Mr.");  // add text information item as a String.
                                  *
                                @@ -119,7 +120,7 @@ import javax.xml.bind.JAXBElement;
                                  *                      createLetterBodyQuantity(new BigInteger("1")));
                                  * gcl.add(ObjectFactory.createLetterBodyProductName("Baby Monitor"));
                                  * gcl.add("shipped from our warehouse");  // add text information item
                                - * 
                                + * }
                                * *

                                See "Package Specification" in javax.xml.bind.package javadoc for * additional common information.

                                diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlRootElement.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlRootElement.java index b84e71beca2..fbbf2f69dc9 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlRootElement.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlRootElement.java @@ -73,28 +73,30 @@ import static java.lang.annotation.ElementType.TYPE; * marshal( new Point(3,5), System.out); * * - *
                                - *     <!-- Example: XML output -->
                                - *     <point>
                                - *       <x> 3 </x>
                                - *       <y> 5 </y>
                                - *     </point>
                                - * 
                                + *
                                {@code
                                + *
                                + *     
                                + *     
                                + *        3 
                                + *        5 
                                + *     
                                + * }
                                * * The annotation causes an global element declaration to be produced * in the schema. The global element declaration is associated with * the XML schema type to which the class is mapped. * - *
                                - *     <!-- Example: XML schema definition -->
                                - *     <xs:element name="point" type="point"/>
                                - *     <xs:complexType name="point">
                                - *       <xs:sequence>
                                - *         <xs:element name="x" type="xs:int"/>
                                - *         <xs:element name="y" type="xs:int"/>
                                - *       </xs:sequence>
                                - *     </xs:complexType>
                                - * 
                                + *
                                {@code
                                + *
                                + *     
                                + *     
                                + *     
                                + *       
                                + *         
                                + *         
                                + *       
                                + *     
                                + * }
                                * *

                                * @@ -113,27 +115,28 @@ import static java.lang.annotation.ElementType.TYPE; * * //Example: Code fragment corresponding to XML output * * marshal( new Point3D(3,5,0), System.out ); + * {@code * - * <!-- Example: XML output --> - * <!-- The element name is point3D not point --> - * <point3D> - * <x>3</x> - * <y>5</y> - * <z>0</z> - * </point3D> + * + * + * + * 3 + * 5 + * 0 + * * - * <!-- Example: XML schema definition --> - * <xs:element name="point3D" type="point3D"/> - * <xs:complexType name="point3D"> - * <xs:complexContent> - * <xs:extension base="point"> - * <xs:sequence> - * <xs:element name="z" type="xs:int"/> - * </xs:sequence> - * </xs:extension> - * </xs:complexContent> - * </xs:complexType> - * + * + * + * + * + * + * + * + * + * + * + * + * } * * Example 3: Associate a global element with XML Schema type * to which the class is mapped. @@ -144,15 +147,16 @@ import static java.lang.annotation.ElementType.TYPE; * @XmlElement * public java.math.BigDecimal price; * } + * {@code * - * <!-- Example: XML schema definition --> - * <xs:element name="PriceElement" type="USPrice"/> - * <xs:complexType name="USPrice"> - * <xs:sequence> - * <xs:element name="price" type="xs:decimal"/> - * </sequence> - * </xs:complexType> - * + * + * + * + * + * + * + * + * } * * @author Sekhar Vajjhala, Sun Microsystems, Inc. * @since 1.6, JAXB 2.0 diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlSchema.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlSchema.java index 6d25d57a266..db25ef00765 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlSchema.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlSchema.java @@ -63,16 +63,17 @@ import static java.lang.annotation.RetentionPolicy.*; * @javax.xml.bind.annotation.XmlSchema ( * namespace = "http://www.example.com/MYPO1" * ) + * {@code * - * <!-- XML Schema fragment --> - * <schema + * + * + * > + * + * } * *

                                Example 2: Customize namespace prefix, namespace URI * mapping

                                @@ -86,16 +87,17 @@ import static java.lang.annotation.RetentionPolicy.*; * * @javax.xml.bind.annotation.XmlNs(prefix="xs", * namespaceURI="http://www.w3.org/2001/XMLSchema") - * ) + * } * ) + * {@code * - * <!-- XML Schema fragment --> - * <schema + * + * * - * + * } * *

                                Example 3: Customize elementFormDefault

                                *
                                @@ -103,14 +105,15 @@ import static java.lang.annotation.RetentionPolicy.*;
                                  *      elementFormDefault=XmlNsForm.UNQUALIFIED
                                  *      ...
                                  *    )
                                + * {@code
                                  *
                                - *    <!-- XML Schema fragment -->
                                - *    <schema
                                + *    
                                + *    
                                  *
                                - * 
                                + * } * @author Sekhar Vajjhala, Sun Microsystems, Inc. * @since 1.6, JAXB 2.0 diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlSchemaType.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlSchemaType.java index a25b291df06..a1d2859eceb 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlSchemaType.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlSchemaType.java @@ -65,14 +65,15 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; * @XmlSchemaType(name="date") * public XMLGregorianCalendar date; * } + * {@code * - * <!-- Example: Local XML Schema element --> - * <xs:complexType name="USPrice"/> - * <xs:sequence> - * <xs:element name="date" type="xs:date"/> - * </sequence> - * </xs:complexType> - * + * + * + * + * + * + * + * } * *

                                Example 2: Customize mapping of XMLGregorianCalendar at package * level

                                diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlTransient.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlTransient.java index 055e90e3ca0..b3394d5465f 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlTransient.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlTransient.java @@ -78,14 +78,15 @@ import static java.lang.annotation.RetentionPolicy.*; * String setName() {..}; * } * + * {@code * - * <!-- Example: XML Schema fragment --> - * <xs:complexType name="USAddress"> - * <xs:sequence> - * <xs:element name="name" type="xs:string"/> - * </xs:sequence> - * </xs:complexType> - * + * + * + * + * + * + * + * } * * @author Sekhar Vajjhala, Sun Microsystems, Inc. * @since 1.6, JAXB 2.0 diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlType.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlType.java index 42e71396338..f20d4055860 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlType.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlType.java @@ -112,7 +112,7 @@ import java.lang.annotation.Target; * The following table shows the mapping of the class to a XML Schema * complex type or simple type. The notational symbols used in the table are: *
                                  - *
                                • -> : represents a mapping
                                • + *
                                • {@literal ->} : represents a mapping
                                • *
                                • [x]+ : one or more occurances of x
                                • *
                                • [ @XmlValue property ]: JavaBean property annotated with * @XmlValue
                                • @@ -132,7 +132,7 @@ import java.lang.annotation.Target; *
                              • * * - * + * * * * @@ -140,7 +140,7 @@ import java.lang.annotation.Target; * * * - * + * * * * @@ -148,7 +148,7 @@ import java.lang.annotation.Target; * * * - * + * * * * @@ -156,7 +156,7 @@ import java.lang.annotation.Target; * * * - * + * * * * @@ -164,7 +164,7 @@ import java.lang.annotation.Target; * * * - * + * * * * @@ -208,35 +208,37 @@ import java.lang.annotation.Target; * java.math.BigDecimal getZip() {..}; * void setZip(java.math.BigDecimal) {..}; * } + * {@code * - * <!-- XML Schema mapping for USAddress --> - * <xs:complexType name="USAddress"> - * <xs:sequence> - * <xs:element name="street" type="xs:string"/> - * <xs:element name="city" type="xs:string"/> - * <xs:element name="state" type="xs:string"/> - * <xs:element name="zip" type="xs:decimal"/> - * <xs:element name="name" type="xs:string"/> - * </xs:all> - * </xs:complexType> - * + * + * + * + * + * + * + * + * + * + * + * } *

                                Example 2: Map a class to a complex type with * xs:all

                                *
                                  * @XmlType(propOrder={})
                                  * public class USAddress { ...}
                                + * {@code
                                  *
                                - * <!-- XML Schema mapping for USAddress -->
                                - * <xs:complexType name="USAddress">
                                - *   <xs:all>
                                - *     <xs:element name="name" type="xs:string"/>
                                - *     <xs:element name="street" type="xs:string"/>
                                - *     <xs:element name="city" type="xs:string"/>
                                - *     <xs:element name="state" type="xs:string"/>
                                - *     <xs:element name="zip" type="xs:decimal"/>
                                - *   </xs:sequence>
                                - * </xs:complexType>
                                - *
                                + * + * + * + * + * + * + * + * + * + * + *} *

                                Example 3: Map a class to a global element with an * anonymous type. *

                                @@ -244,20 +246,21 @@ import java.lang.annotation.Target; * @XmlRootElement * @XmlType(name="") * public class USAddress { ...} + * {@code * - * <!-- XML Schema mapping for USAddress --> - * <xs:element name="USAddress"> - * <xs:complexType> - * <xs:sequence> - * <xs:element name="name" type="xs:string"/> - * <xs:element name="street" type="xs:string"/> - * <xs:element name="city" type="xs:string"/> - * <xs:element name="state" type="xs:string"/> - * <xs:element name="zip" type="xs:decimal"/> - * </xs:sequence> - * </xs:complexType> - * </xs:element> - * + * + * + * + * + * + * + * + * + * + * + * + * + * } * *

                                Example 4: Map a property to a local element with * anonymous type. @@ -271,22 +274,23 @@ import java.lang.annotation.Target; * @XmlType(name="") * public class USAddress { ... } * } + * {@code * - * <!-- XML Schema mapping for USAddress --> - * <xs:complexType name="Invoice"> - * <xs:sequence> - * <xs:element name="addr"> - * <xs:complexType> - * <xs:element name="name", type="xs:string"/> - * <xs:element name="city", type="xs:string"/> - * <xs:element name="city" type="xs:string"/> - * <xs:element name="state" type="xs:string"/> - * <xs:element name="zip" type="xs:decimal"/> - * </xs:complexType> + * + * + * + * + * + * + * + * + * + * + * * ... - * </xs:sequence> - * </xs:complexType> - * + * + * + * } * *

                                Example 5: Map a property to an attribute with * anonymous type. @@ -306,19 +310,20 @@ import java.lang.annotation.Target; * @XmlValue * public java.math.BigDecimal price; * } + * {@code * - * <!-- Example: XML Schema fragment --> - * <xs:complexType name="Item"> - * <xs:sequence> - * <xs:element name="name" type="xs:string"/> - * <xs:attribute name="price"> - * <xs:simpleType> - * <xs:restriction base="xs:decimal"/> - * </xs:simpleType> - * </xs:attribute> - * </xs:sequence> - * </xs:complexType> - * + * + * + * + * + * + * + * + * + * + * + * + * } * *

                                Example 6: Define a factoryClass and factoryMethod * diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlValue.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlValue.java index 1ab10854a4f..675305b5821 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlValue.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/XmlValue.java @@ -87,13 +87,14 @@ import static java.lang.annotation.RetentionPolicy.*; * @XmlValue * public java.math.BigDecimal price; * } + * {@code * - * <!-- Example 1: XML Schema fragment --> - * <xs:simpleType name="USPrice"> - * <xs:restriction base="xs:decimal"/> - * </xs:simpleType> + * + * + * + * * - * + * } * *

                                Example 2: Map a class to XML Schema complexType with * with simpleContent.

                                @@ -108,17 +109,18 @@ import static java.lang.annotation.RetentionPolicy.*; * @XmlAttribute * public String currency; * } + * {@code * - * <!-- Example 2: XML Schema fragment --> - * <xs:complexType name="InternationalPrice"> - * <xs:simpleContent> - * <xs:extension base="xs:decimal"> - * <xs:attribute name="currency" type="xs:string"/> - * </xs:extension> - * </xs:simpleContent> - * </xs:complexType> + * + * + * + * + * + * + * + * * - * + * } * * @author Sekhar Vajjhala, Sun Microsystems, Inc. * @see XmlType diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/adapters/CollapsedStringAdapter.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/adapters/CollapsedStringAdapter.java index 9a589653c12..38865a0c32f 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/adapters/CollapsedStringAdapter.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/adapters/CollapsedStringAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,7 @@ package javax.xml.bind.annotation.adapters; * *

                                * This adapter removes leading and trailing whitespaces, then truncate any - * sequnce of tab, CR, LF, and SP by a single whitespace character ' '. + * sequence of tab, CR, LF, and SP by a single whitespace character ' '. * * @author Kohsuke Kawaguchi * @since 1.6, JAXB 2.0 @@ -41,7 +41,7 @@ public class CollapsedStringAdapter extends XmlAdapter { /** * Removes leading and trailing whitespaces of the string * given as the parameter, then truncate any - * sequnce of tab, CR, LF, and SP by a single whitespace character ' '. + * sequence of tab, CR, LF, and SP by a single whitespace character ' '. */ public String unmarshal(String text) { if(text==null) return null; // be defensive diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/adapters/XmlAdapter.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/adapters/XmlAdapter.java index 4a500814f02..3c5bd422512 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/adapters/XmlAdapter.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/adapters/XmlAdapter.java @@ -75,35 +75,35 @@ package javax.xml.bind.annotation.adapters; * *

                                Step 1: Determine the desired XML representation for HashMap. * - *

                                - *     <hashmap>
                                - *         <entry key="id123">this is a value</entry>
                                - *         <entry key="id312">this is another value</entry>
                                + * 
                                {@code
                                + *     
                                + *         this is a value
                                + *         this is another value
                                  *         ...
                                - *       </hashmap>
                                - * 
                                + * + * }
                                * *

                                Step 2: Determine the schema definition that the * desired XML representation shown above should follow. * - *

                                + * 
                                {@code
                                  *
                                - *     <xs:complexType name="myHashMapType">
                                - *       <xs:sequence>
                                - *         <xs:element name="entry" type="myHashMapEntryType"
                                - *                        minOccurs = "0" maxOccurs="unbounded"/>
                                - *       </xs:sequence>
                                - *     </xs:complexType>
                                + *     
                                + *       
                                + *         
                                + *       
                                + *     
                                  *
                                - *     <xs:complexType name="myHashMapEntryType">
                                - *       <xs:simpleContent>
                                - *         <xs:extension base="xs:string">
                                - *           <xs:attribute name="key" type="xs:int"/>
                                - *         </xs:extension>
                                - *       </xs:simpleContent>
                                - *     </xs:complexType>
                                + *     
                                + *       
                                + *         
                                + *           
                                + *         
                                + *       
                                + *     
                                  *
                                - * 
                                + * }
                                * *

                                Step 3: Write value types that can generate the above * schema definition. @@ -125,11 +125,11 @@ package javax.xml.bind.annotation.adapters; *

                                Step 4: Write the adapter that adapts the value type, * MyHashMapType to a bound type, HashMap, used by the application. * - *

                                + * 
                                {@code
                                  *     public final class MyHashMapAdapter extends
                                - *                        XmlAdapter<MyHashMapType,HashMap> { ... }
                                + *                        XmlAdapter { ... }
                                  *
                                - * 
                                + * }
                                * *

                                Step 5: Use the adapter. * @@ -143,13 +143,13 @@ package javax.xml.bind.annotation.adapters; * * The above code fragment will map to the following schema: * - *

                                - *     <xs:complexType name="Foo">
                                - *       <xs:sequence>
                                - *         <xs:element name="hashmap" type="myHashMapType">
                                - *       </xs:sequence>
                                - *     </xs:complexType>
                                - * 
                                + *
                                {@code
                                + *     
                                + *       
                                + *         
                                + *       
                                + *     
                                + * }
                                * * @param * The type that JAXB doesn't know how to handle. An adapter is written diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/adapters/XmlJavaTypeAdapters.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/adapters/XmlJavaTypeAdapters.java index 6cebcf89dc9..2f1ee037750 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/adapters/XmlJavaTypeAdapters.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/annotation/adapters/XmlJavaTypeAdapters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ import java.lang.annotation.Target; * @XmlJavaTypeAdapters ({ @XmlJavaTypeAdapter(...),@XmlJavaTypeAdapter(...) }) * * - *

                                The @XmlJavaTypeAdapters annnotation is useful for + *

                                The @XmlJavaTypeAdapters annotation is useful for * defining {@link XmlJavaTypeAdapter} annotations for different types * at the package level. * diff --git a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/attachment/AttachmentMarshaller.java b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/attachment/AttachmentMarshaller.java index dd291917a70..8edbc8812eb 100644 --- a/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/attachment/AttachmentMarshaller.java +++ b/jaxws/src/java.xml.bind/share/classes/javax/xml/bind/attachment/AttachmentMarshaller.java @@ -29,22 +29,22 @@ import javax.activation.DataHandler; import javax.xml.bind.Marshaller; /** - *

                                Enable JAXB marshalling to optimize storage of binary data.

                                + *

                                Enable JAXB marshalling to optimize storage of binary data. * *

                                This API enables an efficient cooperative creation of optimized * binary data formats between a JAXB marshalling process and a MIME-based package * processor. A JAXB implementation marshals the root body of a MIME-based package, * delegating the creation of referenceable MIME parts to - * the MIME-based package processor that implements this abstraction.

                                + * the MIME-based package processor that implements this abstraction. * *

                                XOP processing is enabled when {@link #isXOPPackage()} is true. * See {@link #addMtomAttachment(DataHandler, String, String)} for details. - *

                                + * * *

                                WS-I Attachment Profile 1.0 is supported by * {@link #addSwaRefAttachment(DataHandler)} being called by the * marshaller for each JAXB property related to - * {http://ws-i.org/profiles/basic/1.1/xsd}swaRef.

                                + * {http://ws-i.org/profiles/basic/1.1/xsd}swaRef. * * * @author Marc Hadley @@ -60,33 +60,33 @@ import javax.xml.bind.Marshaller; public abstract class AttachmentMarshaller { /** - *

                                Consider MIME content data for optimized binary storage as an attachment. + *

                                Consider MIME content {@code data} for optimized binary storage as an attachment. * *

                                * This method is called by JAXB marshal process when {@link #isXOPPackage()} is - * true, for each element whose datatype is "base64Binary", as described in + * {@code true}, for each element whose datatype is "base64Binary", as described in * Step 3 in * Creating XOP Packages. * *

                                - * The method implementor determines whether data shall be attached separately + * The method implementor determines whether {@code data} shall be attached separately * or inlined as base64Binary data. If the implementation chooses to optimize the storage - * of the binary data as a MIME part, it is responsible for attaching data to the + * of the binary data as a MIME part, it is responsible for attaching {@code data} to the * MIME-based package, and then assigning an unique content-id, cid, that identifies * the MIME part within the MIME message. This method returns the cid, * which enables the JAXB marshaller to marshal a XOP element that refers to that cid in place * of marshalling the binary data. When the method returns null, the JAXB marshaller - * inlines data as base64binary data. + * inlines {@code data} as base64binary data. * *

                                * The caller of this method is required to meet the following constraint. - * If the element infoset item containing data has the attribute - * xmime:contentType or if the JAXB property/field representing - * datais annotated with a known MIME type, - * data.getContentType() should be set to that MIME type. + * If the element infoset item containing {@code data} has the attribute + * {@code xmime:contentType} or if the JAXB property/field representing + * {@code data} is annotated with a known MIME type, + * {@code data.getContentType()} should be set to that MIME type. * *

                                - * The elementNamespace and elementLocalName + * The {@code elementNamespace} and {@code elementLocalName} * parameters provide the * context that contains the binary data. This information could * be used by the MIME-based package processor to determine if the @@ -101,7 +101,7 @@ public abstract class AttachmentMarshaller { * The local name of the element. Always a non-null valid string. * * @return - * a valid content-id URI (see RFC 2387) that identifies the attachment containing data. + * a valid content-id URI (see RFC 2387) that identifies the attachment containing {@code data}. * Otherwise, null if the attachment was not added and should instead be inlined in the message. * * @see XML-binary Optimized Packaging @@ -110,12 +110,12 @@ public abstract class AttachmentMarshaller { public abstract String addMtomAttachment(DataHandler data, String elementNamespace, String elementLocalName); /** - *

                                Consider binary data for optimized binary storage as an attachment. + *

                                Consider binary {@code data} for optimized binary storage as an attachment. * - *

                                Since content type is not known, the attachment's MIME content type must be set to "application/octet-stream".

                                + *

                                Since content type is not known, the attachment's MIME content type must be set to "application/octet-stream". * *

                                - * The elementNamespace and elementLocalName + * The {@code elementNamespace} and {@code elementLocalName} * parameters provide the * context that contains the binary data. This information could * be used by the MIME-based package processor to determine if the @@ -146,21 +146,21 @@ public abstract class AttachmentMarshaller { * The local name of the element. Always a non-null valid string. * * @return content-id URI, cid, to the attachment containing - * data or null if data should be inlined. + * {@code data} or null if data should be inlined. * * @see #addMtomAttachment(DataHandler, String, String) */ public abstract String addMtomAttachment(byte[] data, int offset, int length, String mimeType, String elementNamespace, String elementLocalName); /** - *

                                Read-only property that returns true if JAXB marshaller should enable XOP creation.

                                + *

                                Read-only property that returns true if JAXB marshaller should enable XOP creation. * *

                                This value must not change during the marshalling process. When this - * value is true, the addMtomAttachment(...) method + * value is true, the {@code addMtomAttachment(...)} method * is invoked when the appropriate binary datatypes are encountered by - * the marshal process.

                                + * the marshal process. * - *

                                Marshaller.marshal() must throw IllegalStateException if this value is true + *

                                Marshaller.marshal() must throw IllegalStateException if this value is {@code true} * and the XML content to be marshalled violates Step 1 in * Creating XOP Pacakges * http://www.w3.org/TR/2005/REC-xop10-20050125/#creating_xop_packages. @@ -168,18 +168,18 @@ public abstract class AttachmentMarshaller { * [namespace name] of "http://www.w3.org/2004/08/xop/include" and a [local name] of Include" * *

                                When this method returns true and during the marshal process - * at least one call to addMtomAttachment(...) returns + * at least one call to {@code addMtomAttachment(...)} returns * a content-id, the MIME-based package processor must label the * root part with the application/xop+xml media type as described in * Step 5 of - * Creating XOP Pacakges.

                                + * Creating XOP Pacakges. * * @return true when MIME context is a XOP Package. */ public boolean isXOPPackage() { return false; } /** - *

                                Add MIME data as an attachment and return attachment's content-id, cid.

                                + *

                                Add MIME {@code data} as an attachment and return attachment's content-id, cid. * *

                                * This method is called by JAXB marshal process for each element/attribute typed as @@ -188,7 +188,7 @@ public abstract class AttachmentMarshaller { * MIME attachment, and generating a content-id, cid, that uniquely identifies the attachment * within the MIME-based package. * - *

                                Caller inserts the returned content-id, cid, into the XML content being marshalled.

                                + *

                                Caller inserts the returned content-id, cid, into the XML content being marshalled. * * @param data * represents the data to be attached. Must be non-null. diff --git a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/api/addressing/EPRHeader.java b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/api/addressing/EPRHeader.java index 3c73af04610..642dee10f70 100644 --- a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/api/addressing/EPRHeader.java +++ b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/api/addressing/EPRHeader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -119,7 +119,7 @@ final class EPRHeader extends AbstractHeaderImpl { epr.writeTo(localName, w); w.flush(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); + DocumentBuilderFactory fac = XmlUtil.newDocumentBuilderFactory(false); fac.setNamespaceAware(true); Node eprNode = fac.newDocumentBuilder().parse(bais).getDocumentElement(); Node eprNodeToAdd = header.getOwnerDocument().importNode(eprNode, true); diff --git a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/api/pipe/Engine.java b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/api/pipe/Engine.java index 516f51107c0..29b94bf98c2 100644 --- a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/api/pipe/Engine.java +++ b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/api/pipe/Engine.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -108,7 +108,8 @@ public class Engine { } public Thread newThread(Runnable r) { - Thread t = new Thread(null, r, namePrefix + threadNumber.getAndIncrement(), 0); + Thread t = ThreadHelper.createNewThread(r); + t.setName(namePrefix + threadNumber.getAndIncrement()); if (!t.isDaemon()) { t.setDaemon(true); } diff --git a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/api/pipe/ThreadHelper.java b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/api/pipe/ThreadHelper.java new file mode 100644 index 00000000000..1c74d10a220 --- /dev/null +++ b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/api/pipe/ThreadHelper.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package com.sun.xml.internal.ws.api.pipe; + +import java.lang.reflect.Constructor; +import java.security.AccessController; +import java.security.PrivilegedAction; + +/** + * Simple utility class to instantiate correct Thread instance + * depending on runtime context (jdk/non-jdk usage) + * + * @author miroslav.kos@oracle.com + */ +final class ThreadHelper { + + private static final String SAFE_THREAD_NAME = "sun.misc.ManagedLocalsThread"; + private static final Constructor THREAD_CONSTRUCTOR; + + // no instantiating wanted + private ThreadHelper() { + } + + static { + THREAD_CONSTRUCTOR = AccessController.doPrivileged( + new PrivilegedAction () { + @Override + public Constructor run() { + try { + Class cls = Class.forName(SAFE_THREAD_NAME); + if (cls != null) { + return cls.getConstructor(Runnable.class); + } + } catch (ClassNotFoundException ignored) { + } catch (NoSuchMethodException ignored) { + } + return null; + } + } + ); + } + + static Thread createNewThread(final Runnable r) { + if (isJDKInternal()) { + return AccessController.doPrivileged( + new PrivilegedAction() { + @Override + public Thread run() { + try { + return (Thread) THREAD_CONSTRUCTOR.newInstance(r); + } catch (Exception e) { + return new Thread(r); + } + } + } + ); + } else { + return new Thread(r); + } + } + + private static boolean isJDKInternal() { + String className = ThreadHelper.class.getName(); + return className.contains(".internal."); + } +} diff --git a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/client/WSServiceDelegate.java b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/client/WSServiceDelegate.java index 1c054547a4e..2b384af2919 100644 --- a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/client/WSServiceDelegate.java +++ b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/client/WSServiceDelegate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -894,15 +894,6 @@ public class WSServiceDelegate extends WSService { return wsdlService; } - static class DaemonThreadFactory implements ThreadFactory { - @Override - public Thread newThread(Runnable r) { - Thread daemonThread = new Thread(r); - daemonThread.setDaemon(Boolean.TRUE); - return daemonThread; - } - } - protected static final WebServiceFeature[] EMPTY_FEATURES = new WebServiceFeature[0]; private static ClassLoader getDelegatingLoader(ClassLoader loader1, ClassLoader loader2) { diff --git a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/message/stream/StreamHeader.java b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/message/stream/StreamHeader.java index 6415f1319bb..ae268e2f86f 100644 --- a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/message/stream/StreamHeader.java +++ b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/message/stream/StreamHeader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -194,7 +194,7 @@ public abstract class StreamHeader extends AbstractHeaderImpl { // TODO what about in-scope namespaces // Not very efficient consider implementing a stream buffer // processor that produces a DOM node from the buffer. - TransformerFactory tf = XmlUtil.newTransformerFactory(); + TransformerFactory tf = XmlUtil.newTransformerFactory(true); Transformer t = tf.newTransformer(); XMLStreamBufferSource source = new XMLStreamBufferSource(_mark); DOMResult result = new DOMResult(); diff --git a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/spi/db/BindingHelper.java b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/spi/db/BindingHelper.java index 86d36466e45..a69edb430a5 100644 --- a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/spi/db/BindingHelper.java +++ b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/spi/db/BindingHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/DOMUtil.java b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/DOMUtil.java index e5f8cb7c0ad..47fb059f2c5 100644 --- a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/DOMUtil.java +++ b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/DOMUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -56,7 +56,7 @@ public class DOMUtil { synchronized (DOMUtil.class) { if (db == null) { try { - DocumentBuilderFactory dbf = XmlUtil.newDocumentBuilderFactory(); + DocumentBuilderFactory dbf = XmlUtil.newDocumentBuilderFactory(true); dbf.setNamespaceAware(true); db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { diff --git a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/pipe/AbstractSchemaValidationTube.java b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/pipe/AbstractSchemaValidationTube.java index 6241299d41a..9a8641035bd 100644 --- a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/pipe/AbstractSchemaValidationTube.java +++ b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/pipe/AbstractSchemaValidationTube.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -92,7 +92,7 @@ public abstract class AbstractSchemaValidationTube extends AbstractFilterTubeImp super(next); this.binding = binding; feature = binding.getFeature(SchemaValidationFeature.class); - sf = allowExternalAccess(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI), "file", false); + sf = allowExternalAccess(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI), "all", false); } protected AbstractSchemaValidationTube(AbstractSchemaValidationTube that, TubeCloner cloner) { diff --git a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/version.properties b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/version.properties index b18bbc710b0..8cc250fb181 100644 --- a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/version.properties +++ b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/version.properties @@ -1,5 +1,5 @@ # -# Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ # questions. # -build-id=2.2.11-b150127.1410 -build-version=JAX-WS RI 2.2.11-b150127.1410 +build-id=2.2.11-b150402.1412 +build-version=JAX-WS RI 2.2.11-b150402.1412 major-version=2.2.11 -svn-revision=28121d09ed8ac02b76788709ccb4cdb66e03bbfa +svn-revision=f923291dedcf386c5f408263984a99d7cedf0012 diff --git a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/xml/XMLStreamReaderToXMLStreamWriter.java b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/xml/XMLStreamReaderToXMLStreamWriter.java index 14ad9743353..d30bb8aba62 100644 --- a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/xml/XMLStreamReaderToXMLStreamWriter.java +++ b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/xml/XMLStreamReaderToXMLStreamWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -187,14 +187,11 @@ public class XMLStreamReaderToXMLStreamWriter { protected void handleStartElement() throws XMLStreamException { String nsUri = in.getNamespaceURI(); - if(nsUri==null) - out.writeStartElement(in.getLocalName()); - else - out.writeStartElement( - fixNull(in.getPrefix()), - in.getLocalName(), - nsUri - ); + out.writeStartElement( + fixNull(in.getPrefix()), + in.getLocalName(), + fixNull(nsUri) + ); // start namespace bindings int nsCount = in.getNamespaceCount(); diff --git a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/xml/XmlUtil.java b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/xml/XmlUtil.java index 10ad6086112..18d7fcd55ed 100644 --- a/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/xml/XmlUtil.java +++ b/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/ws/util/xml/XmlUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -231,7 +231,7 @@ public class XmlUtil { static final ContextClassloaderLocal saxParserFactory = new ContextClassloaderLocal() { @Override protected SAXParserFactory initialValue() throws Exception { - SAXParserFactory factory = SAXParserFactory.newInstance(); + SAXParserFactory factory = newSAXParserFactory(true); factory.setNamespaceAware(true); return factory; } @@ -371,57 +371,49 @@ public class XmlUtil { } }; - public static DocumentBuilderFactory newDocumentBuilderFactory() { - return newDocumentBuilderFactory(true); - } - - public static DocumentBuilderFactory newDocumentBuilderFactory(boolean secureXmlProcessing) { + public static DocumentBuilderFactory newDocumentBuilderFactory(boolean disableSecurity) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessing)); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !xmlSecurityDisabled(disableSecurity)); } catch (ParserConfigurationException e) { LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[] { factory.getClass().getName() } ); } return factory; } - public static TransformerFactory newTransformerFactory(boolean secureXmlProcessingEnabled) { + public static TransformerFactory newTransformerFactory(boolean disableSecurity) { TransformerFactory factory = TransformerFactory.newInstance(); try { - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessingEnabled)); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !xmlSecurityDisabled(disableSecurity)); } catch (TransformerConfigurationException e) { LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[]{factory.getClass().getName()}); } return factory; } - public static TransformerFactory newTransformerFactory() { - return newTransformerFactory(true); - } - - public static SAXParserFactory newSAXParserFactory(boolean secureXmlProcessingEnabled) { + public static SAXParserFactory newSAXParserFactory(boolean disableSecurity) { SAXParserFactory factory = SAXParserFactory.newInstance(); try { - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessingEnabled)); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !xmlSecurityDisabled(disableSecurity)); } catch (Exception e) { LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[]{factory.getClass().getName()}); } return factory; } - public static XPathFactory newXPathFactory(boolean secureXmlProcessingEnabled) { + public static XPathFactory newXPathFactory(boolean disableSecurity) { XPathFactory factory = XPathFactory.newInstance(); try { - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessingEnabled)); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !xmlSecurityDisabled(disableSecurity)); } catch (XPathFactoryConfigurationException e) { LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[] { factory.getClass().getName() } ); } return factory; } - public static XMLInputFactory newXMLInputFactory(boolean secureXmlProcessingEnabled) { + public static XMLInputFactory newXMLInputFactory(boolean disableSecurity) { XMLInputFactory factory = XMLInputFactory.newInstance(); - if (isXMLSecurityDisabled(secureXmlProcessingEnabled)) { + if (xmlSecurityDisabled(disableSecurity)) { // TODO-Miran: are those apppropriate defaults? factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); @@ -429,14 +421,14 @@ public class XmlUtil { return factory; } - private static boolean isXMLSecurityDisabled(boolean runtimeDisabled) { + private static boolean xmlSecurityDisabled(boolean runtimeDisabled) { return XML_SECURITY_DISABLED || runtimeDisabled; } - public static SchemaFactory allowExternalAccess(SchemaFactory sf, String value, boolean disableSecureProcessing) { + public static SchemaFactory allowExternalAccess(SchemaFactory sf, String value, boolean disableSecurity) { // if xml security (feature secure processing) disabled, nothing to do, no restrictions applied - if (isXMLSecurityDisabled(disableSecureProcessing)) { + if (xmlSecurityDisabled(disableSecurity)) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Xml Security disabled, no JAXP xsd external access configuration necessary."); } diff --git a/jaxws/src/java.xml.ws/share/classes/javax/jws/soap/InitParam.java b/jaxws/src/java.xml.ws/share/classes/javax/jws/soap/InitParam.java index 43088e25e20..15e276d7d0f 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/jws/soap/InitParam.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/jws/soap/InitParam.java @@ -27,7 +27,7 @@ package javax.jws.soap; /** * @since 1.6 - * @Deprecated + * @deprecated */ @Deprecated public @interface InitParam { String name(); diff --git a/jaxws/src/java.xml.ws/share/classes/javax/jws/soap/SOAPMessageHandler.java b/jaxws/src/java.xml.ws/share/classes/javax/jws/soap/SOAPMessageHandler.java index fe974e3e090..79dea42b59e 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/jws/soap/SOAPMessageHandler.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/jws/soap/SOAPMessageHandler.java @@ -27,7 +27,7 @@ package javax.jws.soap; /** * @since 1.6 - * @Deprecated + * @deprecated */ @Deprecated public @interface SOAPMessageHandler { String name() default ""; diff --git a/jaxws/src/java.xml.ws/share/classes/javax/jws/soap/SOAPMessageHandlers.java b/jaxws/src/java.xml.ws/share/classes/javax/jws/soap/SOAPMessageHandlers.java index c255f756c1a..fa104740c44 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/jws/soap/SOAPMessageHandlers.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/jws/soap/SOAPMessageHandlers.java @@ -29,7 +29,7 @@ import static java.lang.annotation.ElementType.*; /** * @since 1.6 - * @Deprecated + * @deprecated */ @Retention(value=RetentionPolicy.RUNTIME) @Target({TYPE}) diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/AttachmentPart.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/AttachmentPart.java index ae3390c82c1..f597e0dc866 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/AttachmentPart.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/AttachmentPart.java @@ -32,54 +32,53 @@ import java.util.Iterator; import javax.activation.DataHandler; /** - * A single attachment to a SOAPMessage object. A SOAPMessage - * object may contain zero, one, or many AttachmentPart objects. - * Each AttachmentPart object consists of two parts, + * A single attachment to a {@code SOAPMessage} object. A {@code SOAPMessage} + * object may contain zero, one, or many {@code AttachmentPart} objects. + * Each {@code AttachmentPart} object consists of two parts, * application-specific content and associated MIME headers. The * MIME headers consists of name/value pairs that can be used to * identify and describe the content. *

                                - * An AttachmentPart object must conform to certain standards. + * An {@code AttachmentPart} object must conform to certain standards. *

                                  *
                                1. It must conform to * MIME [RFC2045] standards *
                                2. It MUST contain content *
                                3. The header portion MUST include the following header: *
                                    - *
                                  • Content-Type
                                    + *
                                  • {@code Content-Type}
                                    * This header identifies the type of data in the content of an - * AttachmentPart object and MUST conform to [RFC2045]. + * {@code AttachmentPart} object and MUST conform to [RFC2045]. * The following is an example of a Content-Type header: *
                                      *       Content-Type:  application/xml
                                      *       
                                    - * The following line of code, in which ap is an - * AttachmentPart object, sets the header shown in + * The following line of code, in which {@code ap} is an + * {@code AttachmentPart} object, sets the header shown in * the previous example. *
                                      *       ap.setMimeHeader("Content-Type", "application/xml");
                                      *       
                                    - *

                                    *

                                  *
                                *

                                - * There are no restrictions on the content portion of an - * AttachmentPart object. The content may be anything from a + * There are no restrictions on the content portion of an {@code + * AttachmentPart} object. The content may be anything from a * simple plain text object to a complex XML document or image file. * *

                                - * An AttachmentPart object is created with the method - * SOAPMessage.createAttachmentPart. After setting its MIME headers, - * the AttachmentPart object is added to the message - * that created it with the method SOAPMessage.addAttachmentPart. + * An {@code AttachmentPart} object is created with the method + * {@code SOAPMessage.createAttachmentPart}. After setting its MIME headers, + * the {@code AttachmentPart} object is added to the message + * that created it with the method {@code SOAPMessage.addAttachmentPart}. * *

                                - * The following code fragment, in which m is a - * SOAPMessage object and contentStringl is a - * String, creates an instance of AttachmentPart, - * sets the AttachmentPart object with some content and - * header information, and adds the AttachmentPart object to - * the SOAPMessage object. + * The following code fragment, in which {@code m} is a + * {@code SOAPMessage} object and {@code contentStringl} is a + * {@code String}, creates an instance of {@code AttachmentPart}, + * sets the {@code AttachmentPart} object with some content and + * header information, and adds the {@code AttachmentPart} object to + * the {@code SOAPMessage} object. *

                                  *     AttachmentPart ap1 = m.createAttachmentPart();
                                  *     ap1.setContent(contentString1, "text/plain");
                                @@ -89,7 +88,7 @@ import javax.activation.DataHandler;
                                  *
                                  * 

                                * The following code fragment creates and adds a second - * AttachmentPart instance to the same message. jpegData + * {@code AttachmentPart} instance to the same message. {@code jpegData} * is a binary byte buffer representing the jpeg file. *

                                  *     AttachmentPart ap2 = m.createAttachmentPart();
                                @@ -98,19 +97,19 @@ import javax.activation.DataHandler;
                                  *     m.addAttachmentPart(ap2);
                                  * 
                                *

                                - * The getContent method retrieves the contents and header from - * an AttachmentPart object. Depending on the - * DataContentHandler objects present, the returned - * Object can either be a typed Java object corresponding - * to the MIME type or an InputStream object that contains the + * The {@code getContent} method retrieves the contents and header from + * an {@code AttachmentPart} object. Depending on the + * {@code DataContentHandler} objects present, the returned + * {@code Object} can either be a typed Java object corresponding + * to the MIME type or an {@code InputStream} object that contains the * content as bytes. *

                                  *     String content1 = ap1.getContent();
                                  *     java.io.InputStream content2 = ap2.getContent();
                                  * 
                                * - * The method clearContent removes all the content from an - * AttachmentPart object but does not affect its header information. + * The method {@code clearContent} removes all the content from an + * {@code AttachmentPart} object but does not affect its header information. *
                                  *     ap1.clearContent();
                                  * 
                                @@ -120,10 +119,10 @@ import javax.activation.DataHandler; public abstract class AttachmentPart { /** - * Returns the number of bytes in this AttachmentPart + * Returns the number of bytes in this {@code AttachmentPart} * object. * - * @return the size of this AttachmentPart object in bytes + * @return the size of this {@code AttachmentPart} object in bytes * or -1 if the size cannot be determined * @exception SOAPException if the content of this attachment is * corrupted of if there was an exception while trying @@ -132,52 +131,52 @@ public abstract class AttachmentPart { public abstract int getSize() throws SOAPException; /** - * Clears out the content of this AttachmentPart object. + * Clears out the content of this {@code AttachmentPart} object. * The MIME header portion is left untouched. */ public abstract void clearContent(); /** - * Gets the content of this AttachmentPart object as a Java + * Gets the content of this {@code AttachmentPart} object as a Java * object. The type of the returned Java object depends on (1) the - * DataContentHandler object that is used to interpret the bytes - * and (2) the Content-Type given in the header. + * {@code DataContentHandler} object that is used to interpret the bytes + * and (2) the {@code Content-Type} given in the header. *

                                * For the MIME content types "text/plain", "text/html" and "text/xml", the - * DataContentHandler object does the conversions to and + * {@code DataContentHandler} object does the conversions to and * from the Java types corresponding to the MIME types. - * For other MIME types,the DataContentHandler object - * can return an InputStream object that contains the content data + * For other MIME types,the {@code DataContentHandler} object + * can return an {@code InputStream} object that contains the content data * as raw bytes. *

                                * A SAAJ-compliant implementation must, as a minimum, return a - * java.lang.String object corresponding to any content - * stream with a Content-Type value of - * text/plain, a - * javax.xml.transform.stream.StreamSource object corresponding to a - * content stream with a Content-Type value of - * text/xml, a java.awt.Image object + * {@code java.lang.String} object corresponding to any content + * stream with a {@code Content-Type} value of + * {@code text/plain}, a + * {@code javax.xml.transform.stream.StreamSource} object corresponding to a + * content stream with a {@code Content-Type} value of + * {@code text/xml}, a {@code java.awt.Image} object * corresponding to a content stream with a - * Content-Type value of image/gif or - * image/jpeg. For those content types that an - * installed DataContentHandler object does not understand, the - * DataContentHandler object is required to return a - * java.io.InputStream object with the raw bytes. + * {@code Content-Type} value of {@code image/gif} or + * {@code image/jpeg}. For those content types that an + * installed {@code DataContentHandler} object does not understand, the + * {@code DataContentHandler} object is required to return a + * {@code java.io.InputStream} object with the raw bytes. * - * @return a Java object with the content of this AttachmentPart + * @return a Java object with the content of this {@code AttachmentPart} * object * * @exception SOAPException if there is no content set into this - * AttachmentPart object or if there was a data + * {@code AttachmentPart} object or if there was a data * transformation error */ public abstract Object getContent() throws SOAPException; /** - * Gets the content of this AttachmentPart object as an - * InputStream as if a call had been made to getContent and no - * DataContentHandler had been registered for the - * content-type of this AttachmentPart. + * Gets the content of this {@code AttachmentPart} object as an + * InputStream as if a call had been made to {@code getContent} and no + * {@code DataContentHandler} had been registered for the + * {@code content-type} of this {@code AttachmentPart}. *

                                * Note that reading from the returned InputStream would result in consuming * the data in the stream. It is the responsibility of the caller to reset @@ -185,11 +184,11 @@ public abstract class AttachmentPart { * of the raw attachment content is required then the {@link #getRawContentBytes} API * should be used instead. * - * @return an InputStream from which the raw data contained by - * the AttachmentPart can be accessed. + * @return an {@code InputStream} from which the raw data contained by + * the {@code AttachmentPart} can be accessed. * * @throws SOAPException if there is no content set into this - * AttachmentPart object or if there was a data + * {@code AttachmentPart} object or if there was a data * transformation error. * * @since 1.6, SAAJ 1.3 @@ -198,16 +197,16 @@ public abstract class AttachmentPart { public abstract InputStream getRawContent() throws SOAPException; /** - * Gets the content of this AttachmentPart object as a - * byte[] array as if a call had been made to getContent and no - * DataContentHandler had been registered for the - * content-type of this AttachmentPart. + * Gets the content of this {@code AttachmentPart} object as a + * byte[] array as if a call had been made to {@code getContent} and no + * {@code DataContentHandler} had been registered for the + * {@code content-type} of this {@code AttachmentPart}. * - * @return a byte[] array containing the raw data of the - * AttachmentPart. + * @return a {@code byte[]} array containing the raw data of the + * {@code AttachmentPart}. * * @throws SOAPException if there is no content set into this - * AttachmentPart object or if there was a data + * {@code AttachmentPart} object or if there was a data * transformation error. * * @since 1.6, SAAJ 1.3 @@ -215,16 +214,16 @@ public abstract class AttachmentPart { public abstract byte[] getRawContentBytes() throws SOAPException; /** - * Returns an InputStream which can be used to obtain the - * content of AttachmentPart as Base64 encoded + * Returns an {@code InputStream} which can be used to obtain the + * content of {@code AttachmentPart} as Base64 encoded * character data, this method would base64 encode the raw bytes * of the attachment and return. * - * @return an InputStream from which the Base64 encoded - * AttachmentPart can be read. + * @return an {@code InputStream} from which the Base64 encoded + * {@code AttachmentPart} can be read. * * @throws SOAPException if there is no content set into this - * AttachmentPart object or if there was a data + * {@code AttachmentPart} object or if there was a data * transformation error. * * @since 1.6, SAAJ 1.3 @@ -233,11 +232,11 @@ public abstract class AttachmentPart { /** * Sets the content of this attachment part to that of the given - * Object and sets the value of the Content-Type + * {@code Object} and sets the value of the {@code Content-Type} * header to the given type. The type of the - * Object should correspond to the value given for the - * Content-Type. This depends on the particular - * set of DataContentHandler objects in use. + * {@code Object} should correspond to the value given for the + * {@code Content-Type}. This depends on the particular + * set of {@code DataContentHandler} objects in use. * * * @param object the Java object that makes up the content for @@ -247,7 +246,7 @@ public abstract class AttachmentPart { * * @exception IllegalArgumentException may be thrown if the contentType * does not match the type of the content object, or if there - * was no DataContentHandler object for this + * was no {@code DataContentHandler} object for this * content object * * @see #getContent @@ -256,31 +255,31 @@ public abstract class AttachmentPart { /** * Sets the content of this attachment part to that contained by the - * InputStream content and sets the value of the - * Content-Type header to the value contained in - * contentType. + * {@code InputStream} {@code content} and sets the value of the + * {@code Content-Type} header to the value contained in + * {@code contentType}. *

                                * A subsequent call to getSize() may not be an exact measure * of the content size. * * @param content the raw data to add to the attachment part - * @param contentType the value to set into the Content-Type + * @param contentType the value to set into the {@code Content-Type} * header * * @exception SOAPException if an there is an error in setting the content - * @exception NullPointerException if content is null + * @exception NullPointerException if {@code content} is null * @since 1.6, SAAJ 1.3 */ public abstract void setRawContent(InputStream content, String contentType) throws SOAPException; /** * Sets the content of this attachment part to that contained by the - * byte[] array content and sets the value of the - * Content-Type header to the value contained in - * contentType. + * {@code byte[]} array {@code content} and sets the value of the + * {@code Content-Type} header to the value contained in + * {@code contentType}. * * @param content the raw data to add to the attachment part - * @param contentType the value to set into the Content-Type + * @param contentType the value to set into the {@code Content-Type} * header * @param offset the offset in the byte array of the content * @param len the number of bytes that form the content @@ -296,20 +295,20 @@ public abstract class AttachmentPart { /** * Sets the content of this attachment part from the Base64 source - * InputStream and sets the value of the - * Content-Type header to the value contained in - * contentType, This method would first decode the base64 + * {@code InputStream} and sets the value of the + * {@code Content-Type} header to the value contained in + * {@code contentType}, This method would first decode the base64 * input and write the resulting raw bytes to the attachment. *

                                * A subsequent call to getSize() may not be an exact measure * of the content size. * * @param content the base64 encoded data to add to the attachment part - * @param contentType the value to set into the Content-Type + * @param contentType the value to set into the {@code Content-Type} * header * * @exception SOAPException if an there is an error in setting the content - * @exception NullPointerException if content is null + * @exception NullPointerException if {@code content} is null * * @since 1.6, SAAJ 1.3 */ @@ -318,30 +317,30 @@ public abstract class AttachmentPart { /** - * Gets the DataHandler object for this AttachmentPart + * Gets the {@code DataHandler} object for this {@code AttachmentPart} * object. * - * @return the DataHandler object associated with this - * AttachmentPart object + * @return the {@code DataHandler} object associated with this + * {@code AttachmentPart} object * * @exception SOAPException if there is no data in - * this AttachmentPart object + * this {@code AttachmentPart} object */ public abstract DataHandler getDataHandler() throws SOAPException; /** - * Sets the given DataHandler object as the data handler - * for this AttachmentPart object. Typically, on an incoming + * Sets the given {@code DataHandler} object as the data handler + * for this {@code AttachmentPart} object. Typically, on an incoming * message, the data handler is automatically set. When * a message is being created and populated with content, the - * setDataHandler method can be used to get data from + * {@code setDataHandler} method can be used to get data from * various data sources into the message. * - * @param dataHandler the DataHandler object to be set + * @param dataHandler the {@code DataHandler} object to be set * * @exception IllegalArgumentException if there was a problem with - * the specified DataHandler object + * the specified {@code DataHandler} object */ public abstract void setDataHandler(DataHandler dataHandler); @@ -349,8 +348,8 @@ public abstract class AttachmentPart { /** * Gets the value of the MIME header whose name is "Content-ID". * - * @return a String giving the value of the - * "Content-ID" header or null if there + * @return a {@code String} giving the value of the + * "Content-ID" header or {@code null} if there * is none * @see #setContentId */ @@ -364,8 +363,8 @@ public abstract class AttachmentPart { /** * Gets the value of the MIME header whose name is "Content-Location". * - * @return a String giving the value of the - * "Content-Location" header or null if there + * @return a {@code String} giving the value of the + * "Content-Location" header or {@code null} if there * is none */ public String getContentLocation() { @@ -378,8 +377,8 @@ public abstract class AttachmentPart { /** * Gets the value of the MIME header whose name is "Content-Type". * - * @return a String giving the value of the - * "Content-Type" header or null if there + * @return a {@code String} giving the value of the + * "Content-Type" header or {@code null} if there * is none */ public String getContentType() { @@ -392,11 +391,11 @@ public abstract class AttachmentPart { /** * Sets the MIME header whose name is "Content-ID" with the given value. * - * @param contentId a String giving the value of the + * @param contentId a {@code String} giving the value of the * "Content-ID" header * * @exception IllegalArgumentException if there was a problem with - * the specified contentId value + * the specified {@code contentId} value * @see #getContentId */ public void setContentId(String contentId) @@ -409,7 +408,7 @@ public abstract class AttachmentPart { * Sets the MIME header whose name is "Content-Location" with the given value. * * - * @param contentLocation a String giving the value of the + * @param contentLocation a {@code String} giving the value of the * "Content-Location" header * @exception IllegalArgumentException if there was a problem with * the specified content location @@ -422,7 +421,7 @@ public abstract class AttachmentPart { /** * Sets the MIME header whose name is "Content-Type" with the given value. * - * @param contentType a String giving the value of the + * @param contentType a {@code String} giving the value of the * "Content-Type" header * * @exception IllegalArgumentException if there was a problem with @@ -449,10 +448,10 @@ public abstract class AttachmentPart { /** * Gets all the values of the header identified by the given - * String. + * {@code String}. * * @param name the name of the header; example: "Content-Type" - * @return a String array giving the value for the + * @return a {@code String} array giving the value for the * specified header * @see #setMimeHeader */ @@ -466,9 +465,9 @@ public abstract class AttachmentPart { * * Note that RFC822 headers can only contain US-ASCII characters. * - * @param name a String giving the name of the header + * @param name a {@code String} giving the name of the header * for which to search - * @param value a String giving the value to be set for + * @param value a {@code String} giving the value to be set for * the header whose name matches the given name * * @exception IllegalArgumentException if there was a problem with @@ -479,13 +478,13 @@ public abstract class AttachmentPart { /** * Adds a MIME header with the specified name and value to this - * AttachmentPart object. + * {@code AttachmentPart} object. *

                                * Note that RFC822 headers can contain only US-ASCII characters. * - * @param name a String giving the name of the header + * @param name a {@code String} giving the name of the header * to be added - * @param value a String giving the value of the header + * @param value a {@code String} giving the value of the header * to be added * * @exception IllegalArgumentException if there was a problem with @@ -494,35 +493,35 @@ public abstract class AttachmentPart { public abstract void addMimeHeader(String name, String value); /** - * Retrieves all the headers for this AttachmentPart object - * as an iterator over the MimeHeader objects. + * Retrieves all the headers for this {@code AttachmentPart} object + * as an iterator over the {@code MimeHeader} objects. * - * @return an Iterator object with all of the Mime - * headers for this AttachmentPart object + * @return an {@code Iterator} object with all of the Mime + * headers for this {@code AttachmentPart} object */ public abstract Iterator getAllMimeHeaders(); /** - * Retrieves all MimeHeader objects that match a name in + * Retrieves all {@code MimeHeader} objects that match a name in * the given array. * - * @param names a String array with the name(s) of the + * @param names a {@code String} array with the name(s) of the * MIME headers to be returned * @return all of the MIME headers that match one of the names in the - * given array as an Iterator object + * given array as an {@code Iterator} object */ public abstract Iterator getMatchingMimeHeaders(String[] names); /** - * Retrieves all MimeHeader objects whose name does + * Retrieves all {@code MimeHeader} objects whose name does * not match a name in the given array. * - * @param names a String array with the name(s) of the + * @param names a {@code String} array with the name(s) of the * MIME headers not to be returned - * @return all of the MIME headers in this AttachmentPart object + * @return all of the MIME headers in this {@code AttachmentPart} object * except those that match one of the names in the * given array. The nonmatching MIME headers are returned as an - * Iterator object. + * {@code Iterator} object. */ public abstract Iterator getNonMatchingMimeHeaders(String[] names); } diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/Name.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/Name.java index 7c227f19eb3..3f0ef4db6a5 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/Name.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/Name.java @@ -32,52 +32,50 @@ package javax.xml.soap; * to get the URI of the namespace. *

                                * The following is an example of a namespace declaration in an element. - *

                                - *   <wombat:GetLastTradePrice xmlns:wombat="http://www.wombat.org/trader">
                                - * 
                                + * {@code } * ("xmlns" stands for "XML namespace".) * The following - * shows what the methods in the Name interface will return. + * shows what the methods in the {@code Name} interface will return. *
                                  - *
                                • getQualifiedName will return "prefix:LocalName" = + *
                                • {@code getQualifiedName} will return "prefix:LocalName" = * "WOMBAT:GetLastTradePrice" - *
                                • getURI will return "http://www.wombat.org/trader" - *
                                • getLocalName will return "GetLastTracePrice" - *
                                • getPrefix will return "WOMBAT" + *
                                • {@code getURI} will return "http://www.wombat.org/trader" + *
                                • {@code getLocalName} will return "GetLastTracePrice" + *
                                • {@code getPrefix} will return "WOMBAT" *
                                *

                                * XML namespaces are used to disambiguate SOAP identifiers from * application-specific identifiers. *

                                - * Name objects are created using the method - * SOAPEnvelope.createName, which has two versions. - * One method creates Name objects with + * {@code Name} objects are created using the method + * {@code SOAPEnvelope.createName}, which has two versions. + * One method creates {@code Name} objects with * a local name, a namespace prefix, and a namespace URI. - * and the second creates Name objects with just a local name. + * and the second creates {@code Name} objects with just a local name. * The following line of - * code, in which se is a SOAPEnvelope object, creates a new - * Name object with all three. + * code, in which se is a {@code SOAPEnvelope} object, creates a new + * {@code Name} object with all three. *

                                  *     Name name = se.createName("GetLastTradePrice", "WOMBAT",
                                  *                                "http://www.wombat.org/trader");
                                  * 
                                - * The following line of code gives an example of how a Name object - * can be used. The variable element is a SOAPElement object. - * This code creates a new SOAPElement object with the given name and + * The following line of code gives an example of how a {@code Name} object + * can be used. The variable element is a {@code SOAPElement} object. + * This code creates a new {@code SOAPElement} object with the given name and * adds it to element. *
                                  *     element.addChildElement(name);
                                  * 
                                *

                                - * The Name interface may be deprecated in a future release of SAAJ - * in favor of javax.xml.namespace.QName + * The {@code Name} interface may be deprecated in a future release of SAAJ + * in favor of {@code javax.xml.namespace.QName} * @see SOAPEnvelope#createName(String, String, String) SOAPEnvelope.createName * @see SOAPFactory#createName(String, String, String) SOAPFactory.createName * @since 1.6 */ public interface Name { /** - * Gets the local name part of the XML name that this Name + * Gets the local name part of the XML name that this {@code Name} * object represents. * * @return a string giving the local name @@ -86,16 +84,16 @@ public interface Name { /** * Gets the namespace-qualified name of the XML name that this - * Name object represents. + * {@code Name} object represents. * * @return the namespace-qualified name as a string */ String getQualifiedName(); /** - * Returns the prefix that was specified when this Name object + * Returns the prefix that was specified when this {@code Name} object * was initialized. This prefix is associated with the namespace for the XML - * name that this Name object represents. + * name that this {@code Name} object represents. * * @return the prefix as a string */ @@ -103,7 +101,7 @@ public interface Name { /** * Returns the URI of the namespace for the XML - * name that this Name object represents. + * name that this {@code Name} object represents. * * @return the URI as a string */ diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPBody.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPBody.java index ca4a9210f30..ba0ddd74ea7 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPBody.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPBody.java @@ -36,10 +36,10 @@ import javax.xml.namespace.QName; * element in a SOAP message. A SOAP body element consists of XML data * that affects the way the application-specific content is processed. *

                                - * A SOAPBody object contains SOAPBodyElement + * A {@code SOAPBody} object contains {@code SOAPBodyElement} * objects, which have the content for the SOAP body. - * A SOAPFault object, which carries status and/or - * error information, is an example of a SOAPBodyElement object. + * A {@code SOAPFault} object, which carries status and/or + * error information, is an example of a {@code SOAPBodyElement} object. * * @see SOAPFault * @since 1.6 @@ -47,47 +47,47 @@ import javax.xml.namespace.QName; public interface SOAPBody extends SOAPElement { /** - * Creates a new SOAPFault object and adds it to - * this SOAPBody object. The new SOAPFault will + * Creates a new {@code SOAPFault} object and adds it to + * this {@code SOAPBody} object. The new {@code SOAPFault} will * have default values set for the mandatory child elements. The type of - * the SOAPFault will be a SOAP 1.1 or a SOAP 1.2 SOAPFault - * depending on the protocol specified while creating the - * MessageFactory instance. + * the {@code SOAPFault} will be a SOAP 1.1 or a SOAP 1.2 {@code SOAPFault} + * depending on the {@code protocol} specified while creating the + * {@code MessageFactory} instance. *

                                - * A SOAPBody may contain at most one SOAPFault + * A {@code SOAPBody} may contain at most one {@code SOAPFault} * child element. * - * @return the new SOAPFault object + * @return the new {@code SOAPFault} object * @exception SOAPException if there is a SOAP error */ public SOAPFault addFault() throws SOAPException; /** - * Creates a new SOAPFault object and adds it to - * this SOAPBody object. The type of the - * SOAPFault will be a SOAP 1.1 or a SOAP 1.2 - * SOAPFault depending on the protocol - * specified while creating the MessageFactory instance. + * Creates a new {@code SOAPFault} object and adds it to + * this {@code SOAPBody} object. The type of the + * {@code SOAPFault} will be a SOAP 1.1 or a SOAP 1.2 + * {@code SOAPFault} depending on the {@code protocol} + * specified while creating the {@code MessageFactory} instance. *

                                - * For SOAP 1.2 the faultCode parameter is the value of the - * Fault/Code/Value element and the faultString parameter + * For SOAP 1.2 the {@code faultCode} parameter is the value of the + * Fault/Code/Value element and the {@code faultString} parameter * is the value of the Fault/Reason/Text element. For SOAP 1.1 - * the faultCode parameter is the value of the faultcode - * element and the faultString parameter is the value of the faultstring + * the {@code faultCode} parameter is the value of the {@code faultcode} + * element and the {@code faultString} parameter is the value of the {@code faultstring} * element. *

                                - * A SOAPBody may contain at most one SOAPFault + * A {@code SOAPBody} may contain at most one {@code SOAPFault} * child element. * - * @param faultCode a Name object giving the fault + * @param faultCode a {@code Name} object giving the fault * code to be set; must be one of the fault codes defined in the Version * of SOAP specification in use - * @param faultString a String giving an explanation of + * @param faultString a {@code String} giving an explanation of * the fault * @param locale a {@link java.util.Locale} object indicating - * the native language of the faultString - * @return the new SOAPFault object + * the native language of the {@code faultString} + * @return the new {@code SOAPFault} object * @exception SOAPException if there is a SOAP error * @see SOAPFault#setFaultCode * @see SOAPFault#setFaultString @@ -96,32 +96,32 @@ public interface SOAPBody extends SOAPElement { public SOAPFault addFault(Name faultCode, String faultString, Locale locale) throws SOAPException; /** - * Creates a new SOAPFault object and adds it to this - * SOAPBody object. The type of the SOAPFault - * will be a SOAP 1.1 or a SOAP 1.2 SOAPFault depending on - * the protocol specified while creating the MessageFactory + * Creates a new {@code SOAPFault} object and adds it to this + * {@code SOAPBody} object. The type of the {@code SOAPFault} + * will be a SOAP 1.1 or a SOAP 1.2 {@code SOAPFault} depending on + * the {@code protocol} specified while creating the {@code MessageFactory} * instance. *

                                - * For SOAP 1.2 the faultCode parameter is the value of the - * Fault/Code/Value element and the faultString parameter + * For SOAP 1.2 the {@code faultCode} parameter is the value of the + * Fault/Code/Value element and the {@code faultString} parameter * is the value of the Fault/Reason/Text element. For SOAP 1.1 - * the faultCode parameter is the value of the faultcode - * element and the faultString parameter is the value of the faultstring + * the {@code faultCode} parameter is the value of the {@code faultcode} + * element and the {@code faultString} parameter is the value of the {@code faultstring} * element. *

                                - * A SOAPBody may contain at most one SOAPFault + * A {@code SOAPBody} may contain at most one {@code SOAPFault} * child element. * * @param faultCode - * a QName object giving the fault code to be + * a {@code QName} object giving the fault code to be * set; must be one of the fault codes defined in the version * of SOAP specification in use. * @param faultString - * a String giving an explanation of the fault + * a {@code String} giving an explanation of the fault * @param locale * a {@link java.util.Locale Locale} object indicating the - * native language of the faultString - * @return the new SOAPFault object + * native language of the {@code faultString} + * @return the new {@code SOAPFault} object * @exception SOAPException * if there is a SOAP error * @see SOAPFault#setFaultCode @@ -134,33 +134,33 @@ public interface SOAPBody extends SOAPElement { throws SOAPException; /** - * Creates a new SOAPFault object and adds it to this - * SOAPBody object. The type of the SOAPFault - * will be a SOAP 1.1 or a SOAP 1.2 SOAPFault depending on - * the protocol specified while creating the MessageFactory + * Creates a new {@code SOAPFault} object and adds it to this + * {@code SOAPBody} object. The type of the {@code SOAPFault} + * will be a SOAP 1.1 or a SOAP 1.2 {@code SOAPFault} depending on + * the {@code protocol} specified while creating the {@code MessageFactory} * instance. *

                                - * For SOAP 1.2 the faultCode parameter is the value of the - * Fault/Code/Value element and the faultString parameter + * For SOAP 1.2 the {@code faultCode} parameter is the value of the + * Fault/Code/Value element and the {@code faultString} parameter * is the value of the Fault/Reason/Text element. For SOAP 1.1 - * the faultCode parameter is the value of the faultcode - * element and the faultString parameter is the value of the faultstring + * the {@code faultCode} parameter is the value of the faultcode + * element and the {@code faultString} parameter is the value of the faultstring * element. *

                                - * In case of a SOAP 1.2 fault, the default value for the mandatory xml:lang + * In case of a SOAP 1.2 fault, the default value for the mandatory {@code xml:lang} * attribute on the Fault/Reason/Text element will be set to - * java.util.Locale.getDefault() + * {@code java.util.Locale.getDefault()} *

                                - * A SOAPBody may contain at most one SOAPFault + * A {@code SOAPBody} may contain at most one {@code SOAPFault} * child element. * * @param faultCode - * a Name object giving the fault code to be set; + * a {@code Name} object giving the fault code to be set; * must be one of the fault codes defined in the version of SOAP * specification in use * @param faultString - * a String giving an explanation of the fault - * @return the new SOAPFault object + * a {@code String} giving an explanation of the fault + * @return the new {@code SOAPFault} object * @exception SOAPException * if there is a SOAP error * @see SOAPFault#setFaultCode @@ -171,33 +171,33 @@ public interface SOAPBody extends SOAPElement { throws SOAPException; /** - * Creates a new SOAPFault object and adds it to this SOAPBody - * object. The type of the SOAPFault - * will be a SOAP 1.1 or a SOAP 1.2 SOAPFault depending on - * the protocol specified while creating the MessageFactory + * Creates a new {@code SOAPFault} object and adds it to this {@code SOAPBody} + * object. The type of the {@code SOAPFault} + * will be a SOAP 1.1 or a SOAP 1.2 {@code SOAPFault} depending on + * the {@code protocol} specified while creating the {@code MessageFactory} * instance. *

                                - * For SOAP 1.2 the faultCode parameter is the value of the - * Fault/Code/Value element and the faultString parameter + * For SOAP 1.2 the {@code faultCode} parameter is the value of the + * Fault/Code/Value element and the {@code faultString} parameter * is the value of the Fault/Reason/Text element. For SOAP 1.1 - * the faultCode parameter is the value of the faultcode - * element and the faultString parameter is the value of the faultstring + * the {@code faultCode} parameter is the value of the faultcode + * element and the {@code faultString} parameter is the value of the faultstring * element. *

                                - * In case of a SOAP 1.2 fault, the default value for the mandatory xml:lang + * In case of a SOAP 1.2 fault, the default value for the mandatory {@code xml:lang} * attribute on the Fault/Reason/Text element will be set to - * java.util.Locale.getDefault() + * {@code java.util.Locale.getDefault()} *

                                - * A SOAPBody may contain at most one SOAPFault + * A {@code SOAPBody} may contain at most one {@code SOAPFault} * child element * * @param faultCode - * a QName object giving the fault code to be + * a {@code QName} object giving the fault code to be * set; must be one of the fault codes defined in the version * of SOAP specification in use * @param faultString - * a String giving an explanation of the fault - * @return the new SOAPFault object + * a {@code String} giving an explanation of the fault + * @return the new {@code SOAPFault} object * @exception SOAPException * if there is a SOAP error * @see SOAPFault#setFaultCode @@ -209,32 +209,32 @@ public interface SOAPBody extends SOAPElement { throws SOAPException; /** - * Indicates whether a SOAPFault object exists in this - * SOAPBody object. + * Indicates whether a {@code SOAPFault} object exists in this + * {@code SOAPBody} object. * - * @return true if a SOAPFault object exists - * in this SOAPBody object; false + * @return {@code true} if a {@code SOAPFault} object exists + * in this {@code SOAPBody} object; {@code false} * otherwise */ public boolean hasFault(); /** - * Returns the SOAPFault object in this SOAPBody + * Returns the {@code SOAPFault} object in this {@code SOAPBody} * object. * - * @return the SOAPFault object in this SOAPBody + * @return the {@code SOAPFault} object in this {@code SOAPBody} * object if present, null otherwise. */ public SOAPFault getFault(); /** - * Creates a new SOAPBodyElement object with the specified - * name and adds it to this SOAPBody object. + * Creates a new {@code SOAPBodyElement} object with the specified + * name and adds it to this {@code SOAPBody} object. * * @param name - * a Name object with the name for the new SOAPBodyElement + * a {@code Name} object with the name for the new {@code SOAPBodyElement} * object - * @return the new SOAPBodyElement object + * @return the new {@code SOAPBodyElement} object * @exception SOAPException * if a SOAP error occurs * @see SOAPBody#addBodyElement(javax.xml.namespace.QName) @@ -243,13 +243,13 @@ public interface SOAPBody extends SOAPElement { /** - * Creates a new SOAPBodyElement object with the specified - * QName and adds it to this SOAPBody object. + * Creates a new {@code SOAPBodyElement} object with the specified + * QName and adds it to this {@code SOAPBody} object. * * @param qname - * a QName object with the qname for the new - * SOAPBodyElement object - * @return the new SOAPBodyElement object + * a {@code QName} object with the qname for the new + * {@code SOAPBodyElement} object + * @return the new {@code SOAPBodyElement} object * @exception SOAPException * if a SOAP error occurs * @see SOAPBody#addBodyElement(Name) @@ -259,20 +259,20 @@ public interface SOAPBody extends SOAPElement { /** * Adds the root node of the DOM {@link org.w3c.dom.Document} - * to this SOAPBody object. + * to this {@code SOAPBody} object. *

                                - * Calling this method invalidates the document parameter. - * The client application should discard all references to this Document - * and its contents upon calling addDocument. The behavior + * Calling this method invalidates the {@code document} parameter. + * The client application should discard all references to this {@code Document} + * and its contents upon calling {@code addDocument}. The behavior * of an application that continues to use such references is undefined. * * @param document - * the Document object whose root node will be - * added to this SOAPBody. - * @return the SOAPBodyElement that represents the root node + * the {@code Document} object whose root node will be + * added to this {@code SOAPBody}. + * @return the {@code SOAPBodyElement} that represents the root node * that was added. * @exception SOAPException - * if the Document cannot be added + * if the {@code Document} cannot be added * @since 1.6, SAAJ 1.2 */ public SOAPBodyElement addDocument(org.w3c.dom.Document document) @@ -280,16 +280,16 @@ public interface SOAPBody extends SOAPElement { /** * Creates a new DOM {@link org.w3c.dom.Document} and sets - * the first child of this SOAPBody as it's document - * element. The child SOAPElement is removed as part of the + * the first child of this {@code SOAPBody} as it's document + * element. The child {@code SOAPElement} is removed as part of the * process. * * @return the {@link org.w3c.dom.Document} representation - * of the SOAPBody content. + * of the {@code SOAPBody} content. * * @exception SOAPException - * if there is not exactly one child SOAPElement of the - * SOAPBody. + * if there is not exactly one child {@code SOAPElement} of the + * {@code SOAPBody}. * * @since 1.6, SAAJ 1.3 */ diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPElement.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPElement.java index b4d8bca6006..d74eb598c24 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPElement.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPElement.java @@ -38,7 +38,7 @@ import javax.xml.namespace.QName; * Methods in this interface that are required to return SAAJ specific objects * may "silently" replace nodes in the tree as required to successfully return * objects of the correct type. See {@link #getChildElements()} and - * {@link javax.xml.soap} + * {@link javax.xml.soap} * for details. * * @since 1.6 @@ -46,115 +46,115 @@ import javax.xml.namespace.QName; public interface SOAPElement extends Node, org.w3c.dom.Element { /** - * Creates a new SOAPElement object initialized with the - * given Name object and adds the new element to this - * SOAPElement object. + * Creates a new {@code SOAPElement} object initialized with the + * given {@code Name} object and adds the new element to this + * {@code SOAPElement} object. *

                                * This method may be deprecated in a future release of SAAJ in favor of * addChildElement(javax.xml.namespace.QName) * - * @param name a Name object with the XML name for the + * @param name a {@code Name} object with the XML name for the * new element * - * @return the new SOAPElement object that was created + * @return the new {@code SOAPElement} object that was created * @exception SOAPException if there is an error in creating the - * SOAPElement object + * {@code SOAPElement} object * @see SOAPElement#addChildElement(javax.xml.namespace.QName) */ public SOAPElement addChildElement(Name name) throws SOAPException; /** - * Creates a new SOAPElement object initialized with the given - * QName object and adds the new element to this SOAPElement + * Creates a new {@code SOAPElement} object initialized with the given + * {@code QName} object and adds the new element to this {@code SOAPElement} * object. The namespace, localname and prefix of the new - * SOAPElement are all taken from the qname argument. + * {@code SOAPElement} are all taken from the {@code qname} argument. * - * @param qname a QName object with the XML name for the + * @param qname a {@code QName} object with the XML name for the * new element * - * @return the new SOAPElement object that was created + * @return the new {@code SOAPElement} object that was created * @exception SOAPException if there is an error in creating the - * SOAPElement object + * {@code SOAPElement} object * @see SOAPElement#addChildElement(Name) * @since 1.6, SAAJ 1.3 */ public SOAPElement addChildElement(QName qname) throws SOAPException; /** - * Creates a new SOAPElement object initialized with the + * Creates a new {@code SOAPElement} object initialized with the * specified local name and adds the new element to this - * SOAPElement object. - * The new SOAPElement inherits any in-scope default namespace. + * {@code SOAPElement} object. + * The new {@code SOAPElement} inherits any in-scope default namespace. * - * @param localName a String giving the local name for + * @param localName a {@code String} giving the local name for * the element - * @return the new SOAPElement object that was created + * @return the new {@code SOAPElement} object that was created * @exception SOAPException if there is an error in creating the - * SOAPElement object + * {@code SOAPElement} object */ public SOAPElement addChildElement(String localName) throws SOAPException; /** - * Creates a new SOAPElement object initialized with the + * Creates a new {@code SOAPElement} object initialized with the * specified local name and prefix and adds the new element to this - * SOAPElement object. + * {@code SOAPElement} object. * - * @param localName a String giving the local name for + * @param localName a {@code String} giving the local name for * the new element - * @param prefix a String giving the namespace prefix for + * @param prefix a {@code String} giving the namespace prefix for * the new element * - * @return the new SOAPElement object that was created - * @exception SOAPException if the prefix is not valid in the - * context of this SOAPElement or if there is an error in creating the - * SOAPElement object + * @return the new {@code SOAPElement} object that was created + * @exception SOAPException if the {@code prefix} is not valid in the + * context of this {@code SOAPElement} or if there is an error in creating the + * {@code SOAPElement} object */ public SOAPElement addChildElement(String localName, String prefix) throws SOAPException; /** - * Creates a new SOAPElement object initialized with the + * Creates a new {@code SOAPElement} object initialized with the * specified local name, prefix, and URI and adds the new element to this - * SOAPElement object. + * {@code SOAPElement} object. * - * @param localName a String giving the local name for + * @param localName a {@code String} giving the local name for * the new element - * @param prefix a String giving the namespace prefix for + * @param prefix a {@code String} giving the namespace prefix for * the new element - * @param uri a String giving the URI of the namespace + * @param uri a {@code String} giving the URI of the namespace * to which the new element belongs * - * @return the new SOAPElement object that was created + * @return the new {@code SOAPElement} object that was created * @exception SOAPException if there is an error in creating the - * SOAPElement object + * {@code SOAPElement} object */ public SOAPElement addChildElement(String localName, String prefix, String uri) throws SOAPException; /** - * Add a SOAPElement as a child of this - * SOAPElement instance. The SOAPElement + * Add a {@code SOAPElement} as a child of this + * {@code SOAPElement} instance. The {@code SOAPElement} * is expected to be created by a - * SOAPFactory. Callers should not rely on the + * {@code SOAPFactory}. Callers should not rely on the * element instance being added as is into the XML * tree. Implementations could end up copying the content - * of the SOAPElement passed into an instance of - * a different SOAPElement implementation. For - * instance if addChildElement() is called on a - * SOAPHeader, element will be copied - * into an instance of a SOAPHeaderElement. + * of the {@code SOAPElement} passed into an instance of + * a different {@code SOAPElement} implementation. For + * instance if {@code addChildElement()} is called on a + * {@code SOAPHeader}, {@code element} will be copied + * into an instance of a {@code SOAPHeaderElement}. * - *

                                The fragment rooted in element is either added + *

                                The fragment rooted in {@code element} is either added * as a whole or not at all, if there was an error. * - *

                                The fragment rooted in element cannot contain + *

                                The fragment rooted in {@code element} cannot contain * elements named "Envelope", "Header" or "Body" and in the SOAP * namespace. Any namespace prefixes present in the fragment * should be fully resolved using appropriate namespace * declarations within the fragment itself. * - * @param element the SOAPElement to be added as a + * @param element the {@code SOAPElement} to be added as a * new child * * @exception SOAPException if there was an error in adding this @@ -167,10 +167,10 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { throws SOAPException; /** - * Detaches all children of this SOAPElement. + * Detaches all children of this {@code SOAPElement}. *

                                * This method is useful for rolling back the construction of partially - * completed SOAPHeaders and SOAPBodys in + * completed {@code SOAPHeaders} and {@code SOAPBodys} in * preparation for sending a fault when an error condition is detected. It * is also useful for recycling portions of a document within a SOAP * message. @@ -180,33 +180,33 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { public abstract void removeContents(); /** - * Creates a new Text object initialized with the given - * String and adds it to this SOAPElement object. + * Creates a new {@code Text} object initialized with the given + * {@code String} and adds it to this {@code SOAPElement} object. * - * @param text a String object with the textual content to be added + * @param text a {@code String} object with the textual content to be added * - * @return the SOAPElement object into which - * the new Text object was inserted + * @return the {@code SOAPElement} object into which + * the new {@code Text} object was inserted * @exception SOAPException if there is an error in creating the - * new Text object or if it is not legal to + * new {@code Text} object or if it is not legal to * attach it as a child to this - * SOAPElement + * {@code SOAPElement} */ public SOAPElement addTextNode(String text) throws SOAPException; /** * Adds an attribute with the specified name and value to this - * SOAPElement object. + * {@code SOAPElement} object. * - * @param name a Name object with the name of the attribute - * @param value a String giving the value of the attribute - * @return the SOAPElement object into which the attribute was + * @param name a {@code Name} object with the name of the attribute + * @param value a {@code String} giving the value of the attribute + * @return the {@code SOAPElement} object into which the attribute was * inserted * * @exception SOAPException if there is an error in creating the * Attribute, or it is invalid to set - an attribute with Name - name on this SOAPElement. + an attribute with {@code Name} + {@code name} on this SOAPElement. * @see SOAPElement#addAttribute(javax.xml.namespace.QName, String) */ public SOAPElement addAttribute(Name name, String value) @@ -214,17 +214,17 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { /** * Adds an attribute with the specified name and value to this - * SOAPElement object. + * {@code SOAPElement} object. * - * @param qname a QName object with the name of the attribute - * @param value a String giving the value of the attribute - * @return the SOAPElement object into which the attribute was + * @param qname a {@code QName} object with the name of the attribute + * @param value a {@code String} giving the value of the attribute + * @return the {@code SOAPElement} object into which the attribute was * inserted * * @exception SOAPException if there is an error in creating the * Attribute, or it is invalid to set - an attribute with QName - qname on this SOAPElement. + an attribute with {@code QName} + {@code qname} on this SOAPElement. * @see SOAPElement#addAttribute(Name, String) * @since 1.6, SAAJ 1.3 */ @@ -233,11 +233,11 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { /** * Adds a namespace declaration with the specified prefix and URI to this - * SOAPElement object. + * {@code SOAPElement} object. * - * @param prefix a String giving the prefix of the namespace - * @param uri a String giving the uri of the namespace - * @return the SOAPElement object into which this + * @param prefix a {@code String} giving the prefix of the namespace + * @param uri a {@code String} giving the uri of the namespace + * @return the {@code SOAPElement} object into which this * namespace declaration was inserted. * * @exception SOAPException if there is an error in creating the @@ -249,8 +249,8 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { /** * Returns the value of the attribute with the specified name. * - * @param name a Name object with the name of the attribute - * @return a String giving the value of the specified + * @param name a {@code Name} object with the name of the attribute + * @return a {@code String} giving the value of the specified * attribute, Null if there is no such attribute * @see SOAPElement#getAttributeValue(javax.xml.namespace.QName) */ @@ -259,8 +259,8 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { /** * Returns the value of the attribute with the specified qname. * - * @param qname a QName object with the qname of the attribute - * @return a String giving the value of the specified + * @param qname a {@code QName} object with the qname of the attribute + * @return a {@code String} giving the value of the specified * attribute, Null if there is no such attribute * @see SOAPElement#getAttributeValue(Name) * @since 1.6, SAAJ 1.3 @@ -268,11 +268,11 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { public String getAttributeValue(QName qname); /** - * Returns an Iterator over all of the attribute - * Name objects in this - * SOAPElement object. The iterator can be used to get + * Returns an {@code Iterator} over all of the attribute + * {@code Name} objects in this + * {@code SOAPElement} object. The iterator can be used to get * the attribute names, which can then be passed to the method - * getAttributeValue to retrieve the value of each + * {@code getAttributeValue} to retrieve the value of each * attribute. * * @see SOAPElement#getAllAttributesAsQNames() @@ -281,10 +281,10 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { public Iterator getAllAttributes(); /** - * Returns an Iterator over all of the attributes - * in this SOAPElement as QName objects. + * Returns an {@code Iterator} over all of the attributes + * in this {@code SOAPElement} as {@code QName} objects. * The iterator can be used to get the attribute QName, which can then - * be passed to the method getAttributeValue to retrieve + * be passed to the method {@code getAttributeValue} to retrieve * the value of each attribute. * * @return an iterator over the QNames of the attributes @@ -297,94 +297,94 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { /** * Returns the URI of the namespace that has the given prefix. * - * @param prefix a String giving the prefix of the namespace + * @param prefix a {@code String} giving the prefix of the namespace * for which to search - * @return a String with the uri of the namespace that has + * @return a {@code String} with the uri of the namespace that has * the given prefix */ public String getNamespaceURI(String prefix); /** - * Returns an Iterator over the namespace prefix - * Strings declared by this element. The prefixes returned by + * Returns an {@code Iterator} over the namespace prefix + * {@code String}s declared by this element. The prefixes returned by * this iterator can be passed to the method - * getNamespaceURI to retrieve the URI of each namespace. + * {@code getNamespaceURI} to retrieve the URI of each namespace. * * @return an iterator over the namespace prefixes in this - * SOAPElement object + * {@code SOAPElement} object */ public Iterator getNamespacePrefixes(); /** - * Returns an Iterator over the namespace prefix - * Strings visible to this element. The prefixes returned by + * Returns an {@code Iterator} over the namespace prefix + * {@code String}s visible to this element. The prefixes returned by * this iterator can be passed to the method - * getNamespaceURI to retrieve the URI of each namespace. + * {@code getNamespaceURI} to retrieve the URI of each namespace. * * @return an iterator over the namespace prefixes are within scope of this - * SOAPElement object + * {@code SOAPElement} object * * @since 1.6, SAAJ 1.2 */ public Iterator getVisibleNamespacePrefixes(); /** - * Creates a QName whose namespace URI is the one associated - * with the parameter, prefix, in the context of this - * SOAPElement. The remaining elements of the new - * QName are taken directly from the parameters, - * localName and prefix. + * Creates a {@code QName} whose namespace URI is the one associated + * with the parameter, {@code prefix}, in the context of this + * {@code SOAPElement}. The remaining elements of the new + * {@code QName} are taken directly from the parameters, + * {@code localName} and {@code prefix}. * * @param localName - * a String containing the local part of the name. + * a {@code String} containing the local part of the name. * @param prefix - * a String containing the prefix for the name. + * a {@code String} containing the prefix for the name. * - * @return a QName with the specified localName - * and prefix, and with a namespace that is associated - * with the prefix in the context of this - * SOAPElement. This namespace will be the same as + * @return a {@code QName} with the specified {@code localName} + * and {@code prefix}, and with a namespace that is associated + * with the {@code prefix} in the context of this + * {@code SOAPElement}. This namespace will be the same as * the one that would be returned by * {@link #getNamespaceURI(String)} if it were given - * prefix as it's parameter. + * {@code prefix} as it's parameter. * - * @exception SOAPException if the QName cannot be created. + * @exception SOAPException if the {@code QName} cannot be created. * * @since 1.6, SAAJ 1.3 */ public QName createQName(String localName, String prefix) throws SOAPException; /** - * Returns the name of this SOAPElement object. + * Returns the name of this {@code SOAPElement} object. * - * @return a Name object with the name of this - * SOAPElement object + * @return a {@code Name} object with the name of this + * {@code SOAPElement} object */ public Name getElementName(); /** - * Returns the qname of this SOAPElement object. + * Returns the qname of this {@code SOAPElement} object. * - * @return a QName object with the qname of this - * SOAPElement object + * @return a {@code QName} object with the qname of this + * {@code SOAPElement} object * @see SOAPElement#getElementName() * @since 1.6, SAAJ 1.3 */ public QName getElementQName(); /** - * Changes the name of this Element to newName if + * Changes the name of this {@code Element} to {@code newName} if * possible. SOAP Defined elements such as SOAPEnvelope, SOAPHeader, SOAPBody * etc. cannot have their names changed using this method. Any attempt to do * so will result in a SOAPException being thrown. *

                                * Callers should not rely on the element instance being renamed as is. * Implementations could end up copying the content of the - * SOAPElement to a renamed instance. + * {@code SOAPElement} to a renamed instance. * - * @param newName the new name for the Element. + * @param newName the new name for the {@code Element}. * - * @exception SOAPException if changing the name of this Element + * @exception SOAPException if changing the name of this {@code Element} * is not allowed. * @return The renamed Node * @@ -395,10 +395,10 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { /** * Removes the attribute with the specified name. * - * @param name the Name object with the name of the + * @param name the {@code Name} object with the name of the * attribute to be removed - * @return true if the attribute was - * removed successfully; false if it was not + * @return {@code true} if the attribute was + * removed successfully; {@code false} if it was not * @see SOAPElement#removeAttribute(javax.xml.namespace.QName) */ public boolean removeAttribute(Name name); @@ -406,10 +406,10 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { /** * Removes the attribute with the specified qname. * - * @param qname the QName object with the qname of the + * @param qname the {@code QName} object with the qname of the * attribute to be removed - * @return true if the attribute was - * removed successfully; false if it was not + * @return {@code true} if the attribute was + * removed successfully; {@code false} if it was not * @see SOAPElement#removeAttribute(Name) * @since 1.6, SAAJ 1.3 */ @@ -418,84 +418,84 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { /** * Removes the namespace declaration corresponding to the given prefix. * - * @param prefix a String giving the prefix for which + * @param prefix a {@code String} giving the prefix for which * to search - * @return true if the namespace declaration was - * removed successfully; false if it was not + * @return {@code true} if the namespace declaration was + * removed successfully; {@code false} if it was not */ public boolean removeNamespaceDeclaration(String prefix); /** - * Returns an Iterator over all the immediate child - * {@link Node}s of this element. This includes javax.xml.soap.Text - * objects as well as SOAPElement objects. + * Returns an {@code Iterator} over all the immediate child + * {@link Node}s of this element. This includes {@code javax.xml.soap.Text} + * objects as well as {@code SOAPElement} objects. *

                                - * Calling this method may cause child Element, - * SOAPElement and org.w3c.dom.Text nodes to be - * replaced by SOAPElement, SOAPHeaderElement, - * SOAPBodyElement or javax.xml.soap.Text nodes as + * Calling this method may cause child {@code Element}, + * {@code SOAPElement} and {@code org.w3c.dom.Text} nodes to be + * replaced by {@code SOAPElement}, {@code SOAPHeaderElement}, + * {@code SOAPBodyElement} or {@code javax.xml.soap.Text} nodes as * appropriate for the type of this parent node. As a result the calling * application must treat any existing references to these child nodes that * have been obtained through DOM APIs as invalid and either discard them or - * refresh them with the values returned by this Iterator. This + * refresh them with the values returned by this {@code Iterator}. This * behavior can be avoided by calling the equivalent DOM APIs. See - * {@link javax.xml.soap} + * {@link javax.xml.soap} * for more details. * - * @return an iterator with the content of this SOAPElement + * @return an iterator with the content of this {@code SOAPElement} * object */ public Iterator getChildElements(); /** - * Returns an Iterator over all the immediate child + * Returns an {@code Iterator} over all the immediate child * {@link Node}s of this element with the specified name. All of these - * children will be SOAPElement nodes. + * children will be {@code SOAPElement} nodes. *

                                - * Calling this method may cause child Element, - * SOAPElement and org.w3c.dom.Text nodes to be - * replaced by SOAPElement, SOAPHeaderElement, - * SOAPBodyElement or javax.xml.soap.Text nodes as + * Calling this method may cause child {@code Element}, + * {@code SOAPElement} and {@code org.w3c.dom.Text} nodes to be + * replaced by {@code SOAPElement}, {@code SOAPHeaderElement}, + * {@code SOAPBodyElement} or {@code javax.xml.soap.Text} nodes as * appropriate for the type of this parent node. As a result the calling * application must treat any existing references to these child nodes that * have been obtained through DOM APIs as invalid and either discard them or - * refresh them with the values returned by this Iterator. This + * refresh them with the values returned by this {@code Iterator}. This * behavior can be avoided by calling the equivalent DOM APIs. See - * {@link javax.xml.soap} + * {@link javax.xml.soap} * for more details. * - * @param name a Name object with the name of the child + * @param name a {@code Name} object with the name of the child * elements to be returned * - * @return an Iterator object over all the elements - * in this SOAPElement object with the + * @return an {@code Iterator} object over all the elements + * in this {@code SOAPElement} object with the * specified name * @see SOAPElement#getChildElements(javax.xml.namespace.QName) */ public Iterator getChildElements(Name name); /** - * Returns an Iterator over all the immediate child + * Returns an {@code Iterator} over all the immediate child * {@link Node}s of this element with the specified qname. All of these - * children will be SOAPElement nodes. + * children will be {@code SOAPElement} nodes. *

                                - * Calling this method may cause child Element, - * SOAPElement and org.w3c.dom.Text nodes to be - * replaced by SOAPElement, SOAPHeaderElement, - * SOAPBodyElement or javax.xml.soap.Text nodes as + * Calling this method may cause child {@code Element}, + * {@code SOAPElement} and {@code org.w3c.dom.Text} nodes to be + * replaced by {@code SOAPElement}, {@code SOAPHeaderElement}, + * {@code SOAPBodyElement} or {@code javax.xml.soap.Text} nodes as * appropriate for the type of this parent node. As a result the calling * application must treat any existing references to these child nodes that * have been obtained through DOM APIs as invalid and either discard them or - * refresh them with the values returned by this Iterator. This + * refresh them with the values returned by this {@code Iterator}. This * behavior can be avoided by calling the equivalent DOM APIs. See - * {@link javax.xml.soap} + * {@link javax.xml.soap} * for more details. * - * @param qname a QName object with the qname of the child + * @param qname a {@code QName} object with the qname of the child * elements to be returned * - * @return an Iterator object over all the elements - * in this SOAPElement object with the + * @return an {@code Iterator} object over all the elements + * in this {@code SOAPElement} object with the * specified qname * @see SOAPElement#getChildElements(Name) * @since 1.6, SAAJ 1.3 @@ -503,10 +503,10 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { public Iterator getChildElements(QName qname); /** - * Sets the encoding style for this SOAPElement object + * Sets the encoding style for this {@code SOAPElement} object * to one specified. * - * @param encodingStyle a String giving the encoding style + * @param encodingStyle a {@code String} giving the encoding style * * @exception IllegalArgumentException if there was a problem in the * encoding style being set. @@ -516,9 +516,9 @@ public interface SOAPElement extends Node, org.w3c.dom.Element { public void setEncodingStyle(String encodingStyle) throws SOAPException; /** - * Returns the encoding style for this SOAPElement object. + * Returns the encoding style for this {@code SOAPElement} object. * - * @return a String giving the encoding style + * @return a {@code String} giving the encoding style * * @see #setEncodingStyle */ diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPMessage.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPMessage.java index 821c64817e9..a1fef3d693a 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPMessage.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPMessage.java @@ -36,24 +36,24 @@ import javax.activation.DataHandler; * message is an XML document or a MIME message whose first body part is an * XML/SOAP document. *

                                - * A SOAPMessage object consists of a SOAP part and optionally - * one or more attachment parts. The SOAP part for a SOAPMessage - * object is a SOAPPart object, which contains information used + * A {@code SOAPMessage} object consists of a SOAP part and optionally + * one or more attachment parts. The SOAP part for a {@code SOAPMessage} + * object is a {@code SOAPPart} object, which contains information used * for message routing and identification, and which can contain * application-specific content. All data in the SOAP Part of a message must be * in XML format. *

                                - * A new SOAPMessage object contains the following by default: + * A new {@code SOAPMessage} object contains the following by default: *

                                  - *
                                • A SOAPPart object - *
                                • A SOAPEnvelope object - *
                                • A SOAPBody object - *
                                • A SOAPHeader object + *
                                • A {@code SOAPPart} object + *
                                • A {@code SOAPEnvelope} object + *
                                • A {@code SOAPBody} object + *
                                • A {@code SOAPHeader} object *
                                - * The SOAP part of a message can be retrieved by calling the method SOAPMessage.getSOAPPart(). - * The SOAPEnvelope object is retrieved from the SOAPPart - * object, and the SOAPEnvelope object is used to retrieve the - * SOAPBody and SOAPHeader objects. + * The SOAP part of a message can be retrieved by calling the method {@code SOAPMessage.getSOAPPart()}. + * The {@code SOAPEnvelope} object is retrieved from the {@code SOAPPart} + * object, and the {@code SOAPEnvelope} object is used to retrieve the + * {@code SOAPBody} and {@code SOAPHeader} objects. * *
                                  *     SOAPPart sp = message.getSOAPPart();
                                @@ -63,32 +63,32 @@ import javax.activation.DataHandler;
                                  * 
                                * *

                                - * In addition to the mandatory SOAPPart object, a SOAPMessage - * object may contain zero or more AttachmentPart objects, each - * of which contains application-specific data. The SOAPMessage - * interface provides methods for creating AttachmentPart - * objects and also for adding them to a SOAPMessage object. A - * party that has received a SOAPMessage object can examine its + * In addition to the mandatory {@code SOAPPart} object, a {@code SOAPMessage} + * object may contain zero or more {@code AttachmentPart} objects, each + * of which contains application-specific data. The {@code SOAPMessage} + * interface provides methods for creating {@code AttachmentPart} + * objects and also for adding them to a {@code SOAPMessage} object. A + * party that has received a {@code SOAPMessage} object can examine its * contents by retrieving individual attachment parts. *

                                * Unlike the rest of a SOAP message, an attachment is not required to be in * XML format and can therefore be anything from simple text to an image file. * Consequently, any message content that is not in XML format must be in an - * AttachmentPart object. + * {@code AttachmentPart} object. *

                                - * A MessageFactory object may create SOAPMessage + * A {@code MessageFactory} object may create {@code SOAPMessage} * objects with behavior that is specialized to a particular implementation or - * application of SAAJ. For instance, a MessageFactory object - * may produce SOAPMessage objects that conform to a particular - * Profile such as ebXML. In this case a MessageFactory object - * might produce SOAPMessage objects that are initialized with + * application of SAAJ. For instance, a {@code MessageFactory} object + * may produce {@code SOAPMessage} objects that conform to a particular + * Profile such as ebXML. In this case a {@code MessageFactory} object + * might produce {@code SOAPMessage} objects that are initialized with * ebXML headers. *

                                * In order to ensure backward source compatibility, methods that are added to * this class after version 1.1 of the SAAJ specification are all concrete * instead of abstract and they all have default implementations. Unless * otherwise noted in the JavaDocs for those methods the default - * implementations simply throw an UnsupportedOperationException + * implementations simply throw an {@code UnsupportedOperationException} * and the SAAJ implementation code must override them with methods that * provide the specified behavior. Legacy client code does not have this * restriction, however, so long as there is no claim made that it conforms to @@ -126,41 +126,40 @@ public abstract class SOAPMessage { "javax.xml.soap.write-xml-declaration"; /** - * Sets the description of this SOAPMessage object's + * Sets the description of this {@code SOAPMessage} object's * content with the given description. * - * @param description a String describing the content of this + * @param description a {@code String} describing the content of this * message * @see #getContentDescription */ public abstract void setContentDescription(String description); /** - * Retrieves a description of this SOAPMessage object's + * Retrieves a description of this {@code SOAPMessage} object's * content. * - * @return a String describing the content of this - * message or null if no description has been set + * @return a {@code String} describing the content of this + * message or {@code null} if no description has been set * @see #setContentDescription */ public abstract String getContentDescription(); /** - * Gets the SOAP part of this SOAPMessage object. + * Gets the SOAP part of this {@code SOAPMessage} object. *

                                - * SOAPMessage object contains one or more attachments, the + * {@code SOAPMessage} object contains one or more attachments, the * SOAP Part must be the first MIME body part in the message. * - * @return the SOAPPart object for this SOAPMessage + * @return the {@code SOAPPart} object for this {@code SOAPMessage} * object */ public abstract SOAPPart getSOAPPart(); /** - * Gets the SOAP Body contained in this SOAPMessage object. - *

                                + * Gets the SOAP Body contained in this {@code SOAPMessage} object. * - * @return the SOAPBody object contained by this SOAPMessage + * @return the {@code SOAPBody} object contained by this {@code SOAPMessage} * object * @exception SOAPException * if the SOAP Body does not exist or cannot be retrieved @@ -171,23 +170,21 @@ public abstract class SOAPMessage { } /** - * Gets the SOAP Header contained in this SOAPMessage - * object. - *

                                - * - * @return the SOAPHeader object contained by this SOAPMessage - * object - * @exception SOAPException - * if the SOAP Header does not exist or cannot be retrieved - * @since 1.6, SAAJ 1.2 - */ + * Gets the SOAP Header contained in this {@code SOAPMessage} object. + * + * @return the {@code SOAPHeader} object contained + * by this {@code SOAPMessage} object + * @exception SOAPException + * if the SOAP Header does not exist or cannot be retrieved + * @since 1.6, SAAJ 1.2 + */ public SOAPHeader getSOAPHeader() throws SOAPException { throw new UnsupportedOperationException("getSOAPHeader must be overridden by all subclasses of SOAPMessage"); } /** - * Removes all AttachmentPart objects that have been added - * to this SOAPMessage object. + * Removes all {@code AttachmentPart} objects that have been added + * to this {@code SOAPMessage} object. *

                                * This method does not touch the SOAP part. */ @@ -197,26 +194,26 @@ public abstract class SOAPMessage { * Gets a count of the number of attachments in this message. This count * does not include the SOAP part. * - * @return the number of AttachmentPart objects that are - * part of this SOAPMessage object + * @return the number of {@code AttachmentPart} objects that are + * part of this {@code SOAPMessage} object */ public abstract int countAttachments(); /** - * Retrieves all the AttachmentPart objects that are part of - * this SOAPMessage object. + * Retrieves all the {@code AttachmentPart} objects that are part of + * this {@code SOAPMessage} object. * * @return an iterator over all the attachments in this message */ public abstract Iterator getAttachments(); /** - * Retrieves all the AttachmentPart objects that have header + * Retrieves all the {@code AttachmentPart} objects that have header * entries that match the specified headers. Note that a returned * attachment could have headers in addition to those specified. * * @param headers - * a MimeHeaders object containing the MIME + * a {@code MimeHeaders} object containing the MIME * headers for which to search * @return an iterator over all attachments that have a header that matches * one of the given headers @@ -224,12 +221,12 @@ public abstract class SOAPMessage { public abstract Iterator getAttachments(MimeHeaders headers); /** - * Removes all the AttachmentPart objects that have header + * Removes all the {@code AttachmentPart} objects that have header * entries that match the specified headers. Note that the removed * attachment could have headers in addition to those specified. * * @param headers - * a MimeHeaders object containing the MIME + * a {@code MimeHeaders} object containing the MIME * headers for which to search * @since 1.6, SAAJ 1.3 */ @@ -237,25 +234,26 @@ public abstract class SOAPMessage { /** - * Returns an AttachmentPart object that is associated with an - * attachment that is referenced by this SOAPElement or - * null if no such attachment exists. References can be made - * via an href attribute as described in - * {@link SOAP Messages with Attachments}, - * or via a single Text child node containing a URI as + * Returns an {@code AttachmentPart} object that is associated with an + * attachment that is referenced by this {@code SOAPElement} or + * {@code null} if no such attachment exists. References can be made + * via an {@code href} attribute as described in + * SOAP Messages with Attachments, + * or via a single {@code Text} child node containing a URI as * described in the WS-I Attachments Profile 1.0 for elements of schema - * type {@link ref:swaRef}. These two mechanisms must be supported. - * The support for references via href attribute also implies that + * type ref:swaRef. + * These two mechanisms must be supported. + * The support for references via {@code href} attribute also implies that * this method should also be supported on an element that is an * xop:Include element ( - * {@link XOP}). + * XOP). * other reference mechanisms may be supported by individual * implementations of this standard. Contact your vendor for details. * - * @param element The SOAPElement containing the reference to an Attachment - * @return the referenced AttachmentPart or null if no such - * AttachmentPart exists or no reference can be - * found in this SOAPElement. + * @param element The {@code SOAPElement} containing the reference to an Attachment + * @return the referenced {@code AttachmentPart} or null if no such + * {@code AttachmentPart} exists or no reference can be + * found in this {@code SOAPElement}. * @throws SOAPException if there is an error in the attempt to access the * attachment * @@ -265,40 +263,40 @@ public abstract class SOAPMessage { /** - * Adds the given AttachmentPart object to this SOAPMessage - * object. An AttachmentPart object must be created before + * Adds the given {@code AttachmentPart} object to this {@code SOAPMessage} + * object. An {@code AttachmentPart} object must be created before * it can be added to a message. * * @param AttachmentPart - * an AttachmentPart object that is to become part - * of this SOAPMessage object + * an {@code AttachmentPart} object that is to become part + * of this {@code SOAPMessage} object * @exception IllegalArgumentException */ public abstract void addAttachmentPart(AttachmentPart AttachmentPart); /** - * Creates a new empty AttachmentPart object. Note that the - * method addAttachmentPart must be called with this new - * AttachmentPart object as the parameter in order for it to - * become an attachment to this SOAPMessage object. + * Creates a new empty {@code AttachmentPart} object. Note that the + * method {@code addAttachmentPart} must be called with this new + * {@code AttachmentPart} object as the parameter in order for it to + * become an attachment to this {@code SOAPMessage} object. * - * @return a new AttachmentPart object that can be populated - * and added to this SOAPMessage object + * @return a new {@code AttachmentPart} object that can be populated + * and added to this {@code SOAPMessage} object */ public abstract AttachmentPart createAttachmentPart(); /** - * Creates an AttachmentPart object and populates it using - * the given DataHandler object. + * Creates an {@code AttachmentPart} object and populates it using + * the given {@code DataHandler} object. * * @param dataHandler - * the javax.activation.DataHandler object that - * will generate the content for this SOAPMessage + * the {@code javax.activation.DataHandler} object that + * will generate the content for this {@code SOAPMessage} * object - * @return a new AttachmentPart object that contains data - * generated by the given DataHandler object + * @return a new {@code AttachmentPart} object that contains data + * generated by the given {@code DataHandler} object * @exception IllegalArgumentException - * if there was a problem with the specified DataHandler + * if there was a problem with the specified {@code DataHandler} * object * @see javax.activation.DataHandler * @see javax.activation.DataContentHandler @@ -310,32 +308,32 @@ public abstract class SOAPMessage { } /** - * Returns all the transport-specific MIME headers for this SOAPMessage + * Returns all the transport-specific MIME headers for this {@code SOAPMessage} * object in a transport-independent fashion. * - * @return a MimeHeaders object containing the MimeHeader + * @return a {@code MimeHeaders} object containing the {@code MimeHeader} * objects */ public abstract MimeHeaders getMimeHeaders(); /** - * Creates an AttachmentPart object and populates it with + * Creates an {@code AttachmentPart} object and populates it with * the specified data of the specified content type. The type of the - * Object should correspond to the value given for the - * Content-Type. + * {@code Object} should correspond to the value given for the + * {@code Content-Type}. * * @param content - * an Object containing the content for the - * AttachmentPart object to be created + * an {@code Object} containing the content for the + * {@code AttachmentPart} object to be created * @param contentType - * a String object giving the type of content; + * a {@code String} object giving the type of content; * examples are "text/xml", "text/plain", and "image/jpeg" - * @return a new AttachmentPart object that contains the + * @return a new {@code AttachmentPart} object that contains the * given data * @exception IllegalArgumentException * may be thrown if the contentType does not match the type * of the content object, or if there was no - * DataContentHandler object for the given + * {@code DataContentHandler} object for the given * content object * @see javax.activation.DataHandler * @see javax.activation.DataContentHandler @@ -349,50 +347,49 @@ public abstract class SOAPMessage { } /** - * Updates this SOAPMessage object with all the changes that + * Updates this {@code SOAPMessage} object with all the changes that * have been made to it. This method is called automatically when * {@link SOAPMessage#writeTo(OutputStream)} is called. However, if * changes are made to a message that was received or to one that has - * already been sent, the method saveChanges needs to be - * called explicitly in order to save the changes. The method saveChanges + * already been sent, the method {@code saveChanges} needs to be + * called explicitly in order to save the changes. The method {@code saveChanges} * also generates any changes that can be read back (for example, a * MessageId in profiles that support a message id). All MIME headers in a * message that is created for sending purposes are guaranteed to have - * valid values only after saveChanges has been called. + * valid values only after {@code saveChanges} has been called. *

                                * In addition, this method marks the point at which the data from all - * constituent AttachmentPart objects are pulled into the + * constituent {@code AttachmentPart} objects are pulled into the * message. - *

                                * - * @exception SOAPException if there was a problem saving - * changes to this message. + * @exception SOAPException if there was a problem saving + * changes to this message. */ public abstract void saveChanges() throws SOAPException; /** - * Indicates whether this SOAPMessage object needs to have - * the method saveChanges called on it. + * Indicates whether this {@code SOAPMessage} object needs to have + * the method {@code saveChanges} called on it. * - * @return true if saveChanges needs to be - * called; false otherwise. + * @return {@code true} if {@code saveChanges} needs to be + * called; {@code false} otherwise. */ public abstract boolean saveRequired(); /** - * Writes this SOAPMessage object to the given output + * Writes this {@code SOAPMessage} object to the given output * stream. The externalization format is as defined by the SOAP 1.1 with * Attachments specification. *

                                * If there are no attachments, just an XML stream is written out. For - * those messages that have attachments, writeTo writes a + * those messages that have attachments, {@code writeTo} writes a * MIME-encoded byte stream. *

                                * Note that this method does not write the transport-specific MIME Headers * of the Message * * @param out - * the OutputStream object to which this SOAPMessage + * the {@code OutputStream} object to which this {@code SOAPMessage} * object will be written * @exception IOException * if an I/O error occurs @@ -414,13 +411,13 @@ public abstract class SOAPMessage { * implementation specific properties. These properties must be prefixed * with package names that are unique to the vendor. *

                                - * Setting the property WRITE_XML_DECLARATION to "true" + * Setting the property {@code WRITE_XML_DECLARATION} to {@code "true"} * will cause an XML Declaration to be written out at the start of the SOAP * message. The default value of "false" suppresses this declaration. *

                                - * The property CHARACTER_SET_ENCODING defaults to the value - * "utf-8" which causes the SOAP message to be encoded using - * UTF-8. Setting CHARACTER_SET_ENCODING to "utf-16" + * The property {@code CHARACTER_SET_ENCODING} defaults to the value + * {@code "utf-8"} which causes the SOAP message to be encoded using + * UTF-8. Setting {@code CHARACTER_SET_ENCODING} to {@code "utf-16"} * causes the SOAP message to be encoded using UTF-16. *

                                * Some implementations may allow encodings in addition to UTF-8 and @@ -445,7 +442,7 @@ public abstract class SOAPMessage { * * @param property * the name of the property to retrieve - * @return the value associated with the named property or null + * @return the value associated with the named property or {@code null} * if no such property exists. * @exception SOAPException * if the property name is not recognized. diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPPart.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPPart.java index dc280fab60e..0a109422cf1 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPPart.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/soap/SOAPPart.java @@ -30,52 +30,51 @@ import java.util.Iterator; import javax.xml.transform.Source; /** - * The container for the SOAP-specific portion of a SOAPMessage + * The container for the SOAP-specific portion of a {@code SOAPMessage} * object. All messages are required to have a SOAP part, so when a - * SOAPMessage object is created, it will automatically - * have a SOAPPart object. - *

                                - * A SOAPPart object is a MIME part and has the MIME headers + * {@code SOAPMessage} object is created, it will automatically + * have a {@code SOAPPart} object. + *

                                + * A {@code SOAPPart} object is a MIME part and has the MIME headers * Content-Id, Content-Location, and Content-Type. Because the value of - * Content-Type must be "text/xml", a SOAPPart object automatically + * Content-Type must be "text/xml", a {@code SOAPPart} object automatically * has a MIME header of Content-Type with its value set to "text/xml". * The value must be "text/xml" because content in the SOAP part of a * message must be in XML format. Content that is not of type "text/xml" - * must be in an AttachmentPart object rather than in the - * SOAPPart object. + * must be in an {@code AttachmentPart} object rather than in the + * {@code SOAPPart} object. *

                                * When a message is sent, its SOAP part must have the MIME header Content-Type * set to "text/xml". Or, from the other perspective, the SOAP part of any * message that is received must have the MIME header Content-Type with a * value of "text/xml". *

                                - * A client can access the SOAPPart object of a - * SOAPMessage object by - * calling the method SOAPMessage.getSOAPPart. The - * following line of code, in which message is a - * SOAPMessage object, retrieves the SOAP part of a message. + * A client can access the {@code SOAPPart} object of a + * {@code SOAPMessage} object by + * calling the method {@code SOAPMessage.getSOAPPart}. The + * following line of code, in which {@code message} is a + * {@code SOAPMessage} object, retrieves the SOAP part of a message. *

                                  *   SOAPPart soapPart = message.getSOAPPart();
                                  * 
                                *

                                - * A SOAPPart object contains a SOAPEnvelope object, - * which in turn contains a SOAPBody object and a - * SOAPHeader object. - * The SOAPPart method getEnvelope can be used - * to retrieve the SOAPEnvelope object. - *

                                + * A {@code SOAPPart} object contains a {@code SOAPEnvelope} object, + * which in turn contains a {@code SOAPBody} object and a + * {@code SOAPHeader} object. + * The {@code SOAPPart} method {@code getEnvelope} can be used + * to retrieve the {@code SOAPEnvelope} object. * * @since 1.6 */ public abstract class SOAPPart implements org.w3c.dom.Document, Node { /** - * Gets the SOAPEnvelope object associated with this - * SOAPPart object. Once the SOAP envelope is obtained, it + * Gets the {@code SOAPEnvelope} object associated with this + * {@code SOAPPart} object. Once the SOAP envelope is obtained, it * can be used to get its contents. * - * @return the SOAPEnvelope object for this - * SOAPPart object + * @return the {@code SOAPEnvelope} object for this + * {@code SOAPPart} object * @exception SOAPException if there is a SOAP error */ public abstract SOAPEnvelope getEnvelope() throws SOAPException; @@ -83,7 +82,7 @@ public abstract class SOAPPart implements org.w3c.dom.Document, Node { /** * Retrieves the value of the MIME header whose name is "Content-Id". * - * @return a String giving the value of the MIME header + * @return a {@code String} giving the value of the MIME header * named "Content-Id" * @see #setContentId */ @@ -97,7 +96,7 @@ public abstract class SOAPPart implements org.w3c.dom.Document, Node { /** * Retrieves the value of the MIME header whose name is "Content-Location". * - * @return a String giving the value of the MIME header whose + * @return a {@code String} giving the value of the MIME header whose * name is "Content-Location" * @see #setContentLocation */ @@ -110,9 +109,9 @@ public abstract class SOAPPart implements org.w3c.dom.Document, Node { /** * Sets the value of the MIME header named "Content-Id" - * to the given String. + * to the given {@code String}. * - * @param contentId a String giving the value of the MIME + * @param contentId a {@code String} giving the value of the MIME * header "Content-Id" * * @exception IllegalArgumentException if there is a problem in @@ -125,9 +124,9 @@ public abstract class SOAPPart implements org.w3c.dom.Document, Node { } /** * Sets the value of the MIME header "Content-Location" - * to the given String. + * to the given {@code String}. * - * @param contentLocation a String giving the value + * @param contentLocation a {@code String} giving the value * of the MIME * header "Content-Location" * @exception IllegalArgumentException if there is a problem in @@ -141,24 +140,24 @@ public abstract class SOAPPart implements org.w3c.dom.Document, Node { /** * Removes all MIME headers that match the given name. * - * @param header a String giving the name of the MIME header(s) to + * @param header a {@code String} giving the name of the MIME header(s) to * be removed */ public abstract void removeMimeHeader(String header); /** - * Removes all the MimeHeader objects for this - * SOAPEnvelope object. + * Removes all the {@code MimeHeader} objects for this + * {@code SOAPEnvelope} object. */ public abstract void removeAllMimeHeaders(); /** - * Gets all the values of the MimeHeader object - * in this SOAPPart object that - * is identified by the given String. + * Gets all the values of the {@code MimeHeader} object + * in this {@code SOAPPart} object that + * is identified by the given {@code String}. * * @param name the name of the header; example: "Content-Type" - * @return a String array giving all the values for the + * @return a {@code String} array giving all the values for the * specified header * @see #setMimeHeader */ @@ -176,13 +175,13 @@ public abstract class SOAPPart implements org.w3c.dom.Document, Node { *

                                * Note that RFC822 headers can contain only US-ASCII characters. * - * @param name a String giving the header name + * @param name a {@code String} giving the header name * for which to search - * @param value a String giving the value to be set. + * @param value a {@code String} giving the value to be set. * This value will be substituted for the current value(s) * of the first header that is a match if there is one. * If there is no match, this value will be the value for - * a new MimeHeader object. + * a new {@code MimeHeader} object. * * @exception IllegalArgumentException if there was a problem with * the specified mime header name or value @@ -191,16 +190,16 @@ public abstract class SOAPPart implements org.w3c.dom.Document, Node { public abstract void setMimeHeader(String name, String value); /** - * Creates a MimeHeader object with the specified - * name and value and adds it to this SOAPPart object. - * If a MimeHeader with the specified name already + * Creates a {@code MimeHeader} object with the specified + * name and value and adds it to this {@code SOAPPart} object. + * If a {@code MimeHeader} with the specified name already * exists, this method adds the specified value to the already * existing value(s). *

                                * Note that RFC822 headers can contain only US-ASCII characters. * - * @param name a String giving the header name - * @param value a String giving the value to be set + * @param name a {@code String} giving the header name + * @param value a {@code String} giving the value to be set * or added * @exception IllegalArgumentException if there was a problem with * the specified mime header name or value @@ -208,44 +207,44 @@ public abstract class SOAPPart implements org.w3c.dom.Document, Node { public abstract void addMimeHeader(String name, String value); /** - * Retrieves all the headers for this SOAPPart object - * as an iterator over the MimeHeader objects. + * Retrieves all the headers for this {@code SOAPPart} object + * as an iterator over the {@code MimeHeader} objects. * - * @return an Iterator object with all of the Mime - * headers for this SOAPPart object + * @return an {@code Iterator} object with all of the Mime + * headers for this {@code SOAPPart} object */ public abstract Iterator getAllMimeHeaders(); /** - * Retrieves all MimeHeader objects that match a name in + * Retrieves all {@code MimeHeader} objects that match a name in * the given array. * - * @param names a String array with the name(s) of the + * @param names a {@code String} array with the name(s) of the * MIME headers to be returned * @return all of the MIME headers that match one of the names in the - * given array, returned as an Iterator object + * given array, returned as an {@code Iterator} object */ public abstract Iterator getMatchingMimeHeaders(String[] names); /** - * Retrieves all MimeHeader objects whose name does + * Retrieves all {@code MimeHeader} objects whose name does * not match a name in the given array. * - * @param names a String array with the name(s) of the + * @param names a {@code String} array with the name(s) of the * MIME headers not to be returned - * @return all of the MIME headers in this SOAPPart object + * @return all of the MIME headers in this {@code SOAPPart} object * except those that match one of the names in the * given array. The nonmatching MIME headers are returned as an - * Iterator object. + * {@code Iterator} object. */ public abstract Iterator getNonMatchingMimeHeaders(String[] names); /** - * Sets the content of the SOAPEnvelope object with the data - * from the given Source object. This Source + * Sets the content of the {@code SOAPEnvelope} object with the data + * from the given {@code Source} object. This {@code Source} * must contain a valid SOAP document. * - * @param source the javax.xml.transform.Source object with the + * @param source the {@code javax.xml.transform.Source} object with the * data to be set * * @exception SOAPException if there is a problem in setting the source @@ -254,13 +253,13 @@ public abstract class SOAPPart implements org.w3c.dom.Document, Node { public abstract void setContent(Source source) throws SOAPException; /** - * Returns the content of the SOAPEnvelope as a JAXP Source + * Returns the content of the SOAPEnvelope as a JAXP {@code Source} * object. * - * @return the content as a javax.xml.transform.Source object + * @return the content as a {@code javax.xml.transform.Source} object * * @exception SOAPException if the implementation cannot convert - * the specified Source object + * the specified {@code Source} object * @see #setContent */ public abstract Source getContent() throws SOAPException; diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/Action.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/Action.java index f42190b295e..445f651c893 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/Action.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/Action.java @@ -32,89 +32,90 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * The Action annotation allows explicit association of a - * WS-Addressing Action message addressing property with - * input, output, and - * fault messages of the mapped WSDL operation. + * The {@code Action} annotation allows explicit association of a + * WS-Addressing {@code Action} message addressing property with + * {@code input}, {@code output}, and + * {@code fault} messages of the mapped WSDL operation. *

                                * This annotation can be specified on each method of a service endpoint interface. * For such a method, the mapped operation in the generated WSDL's - * wsam:Action attribute on the WSDL input, - * output and fault messages of the WSDL operation - * is based upon which attributes of the Action annotation have been specified. - * For the exact computation of wsam:Action values for the messages, refer + * {@code wsam:Action} attribute on the WSDL {@code input}, + * {@code output} and {@code fault} messages of the WSDL {@code operation} + * is based upon which attributes of the {@code Action} annotation have been specified. + * For the exact computation of {@code wsam:Action} values for the messages, refer * to the algorithm in the JAX-WS specification. *

                                - * Example 1: Specify explicit values for Action message addressing property - * for input and output messages. + * Example 1: Specify explicit values for {@code Action} message addressing property + * for {@code input} and {@code output} messages. * *

                                - * @WebService(targetNamespace="http://example.com/numbers")
                                - * public class AddNumbersImpl {
                                - *     @Action(
                                - *         input="http://example.com/inputAction",
                                - *         output="http://example.com/outputAction")
                                - *     public int addNumbers(int number1, int number2) {
                                - *         return number1 + number2;
                                - *     }
                                - * }
                                + * {@literal @}WebService(targetNamespace="http://example.com/numbers")
                                + *  public class AddNumbersImpl {
                                + *     {@literal @}Action(
                                + *          input="http://example.com/inputAction",
                                + *          output="http://example.com/outputAction")
                                + *      public int addNumbers(int number1, int number2) {
                                + *          return number1 + number2;
                                + *      }
                                + *  }
                                  * 
                                * * The generated WSDL looks like: - *
                                - *   <definitions targetNamespace="http://example.com/numbers" ...>
                                + * 
                                 {@code
                                + *   
                                  *     ...
                                - *     <portType name="AddNumbersPortType">
                                - *       <operation name="AddNumbers">
                                - *         <input message="tns:AddNumbersInput" name="foo"
                                + *     
                                + *       
                                + *         wsam:Action="http://example.com/inputAction"/>
                                - *         <output message="tns:AddNumbersOutput" name="bar"
                                + *         wsam:Action="http://example.com/outputAction"/>
                                - *       </operation>
                                - *     </portType>
                                + *       
                                + *     
                                  *     ...
                                - *   </definitions>
                                + *   
                                + * }
                                  * 
                                * *

                                - * Example 2: Specify explicit value for Action message addressing property - * for only the input message. The wsam:Action values for the - * WSDL output message are computed using the algorithm in the JAX-WS specification. + * Example 2: Specify explicit value for {@code Action} message addressing property + * for only the {@code input} message. The {@code wsam:Action} values for the + * WSDL {@code output} message are computed using the algorithm in the JAX-WS specification. * *

                                - * @WebService(targetNamespace="http://example.com/numbers")
                                - * public class AddNumbersImpl {
                                - *     @Action(input="http://example.com/inputAction")
                                - *     public int addNumbers(int number1, int number2) {
                                - *         return number1 + number2;
                                - *     }
                                - * }
                                + * {@literal @}WebService(targetNamespace="http://example.com/numbers")
                                + *  public class AddNumbersImpl {
                                + *     {@literal @}Action(input="http://example.com/inputAction")
                                + *      public int addNumbers(int number1, int number2) {
                                + *          return number1 + number2;
                                + *      }
                                + *  }
                                  * 
                                * * The generated WSDL looks like: - *
                                - *   <definitions targetNamespace="http://example.com/numbers" ...>
                                + * 
                                 {@code
                                + *   
                                  *     ...
                                - *     <portType name="AddNumbersPortType">
                                - *       <operation name="AddNumbers">
                                - *         <input message="tns:AddNumbersInput" name="foo"
                                - *           wsam:Action="http://example.com/inputAction" />
                                - *         <output message="tns:AddNumbersOutput" name="bar"
                                + *     
                                + *       
                                + *         wsam:Action="http://example.com/inputAction"/>
                                + *         wsam:Action="http://example.com/numbers/AddNumbersPortType/AddNumbersResponse"/>
                                - *       </operation>
                                - *     </portType>
                                + *       
                                + *     
                                  *     ...
                                - *   </definitions>
                                - * 
                                + * + * }
                                * - * It is legitimate to specify an explicit value for Action message addressing property for - * output message only. In this case, wsam:Action value for the - * WSDL input message is computed using the algorithm in the JAX-WS specification. + * It is legitimate to specify an explicit value for {@code Action} message addressing property for + * {@code output} message only. In this case, {@code wsam:Action} value for the + * WSDL {@code input} message is computed using the algorithm in the JAX-WS specification. * *

                                * Example 3: See {@link FaultAction} annotation for an example of - * how to specify an explicit value for Action message addressing property for the - * fault message. + * how to specify an explicit value for {@code Action} message addressing property for the + * {@code fault} message. * * @see FaultAction * @@ -126,21 +127,21 @@ import java.lang.annotation.Target; @Target(ElementType.METHOD) public @interface Action { /** - * Explicit value of the WS-Addressing Action message addressing property for the input + * Explicit value of the WS-Addressing {@code Action} message addressing property for the {@code input} * message of the operation. */ String input() default ""; /** - * Explicit value of the WS-Addressing Action message addressing property for the output + * Explicit value of the WS-Addressing {@code Action} message addressing property for the {@code output} * message of the operation. */ String output() default ""; /** - * Explicit value of the WS-Addressing Action message addressing property for the fault + * Explicit value of the WS-Addressing {@code Action} message addressing property for the {@code fault} * message(s) of the operation. Each exception that is mapped to a fault and requires an explicit WS-Addressing - * Action message addressing property, needs to be specified as a value in this property + * {@code Action} message addressing property, needs to be specified as a value in this property * using {@link FaultAction} annotation. */ FaultAction[] fault() default { }; diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/Binding.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/Binding.java index 24be0222c67..f4f8c01d3bb 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/Binding.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/Binding.java @@ -26,7 +26,7 @@ package javax.xml.ws; -/** The Binding interface is the base interface +/** The {@code Binding} interface is the base interface * for JAX-WS protocol bindings. * * @since 1.6, JAX-WS 2.0 @@ -35,10 +35,10 @@ public interface Binding { /** * Gets a copy of the handler chain for a protocol binding instance. - * If the returned chain is modified a call to setHandlerChain + * If the returned chain is modified a call to {@code setHandlerChain} * is required to configure the binding instance with the new chain. * - * @return java.util.List<Handler> Handler chain + * @return {@code java.util.List} Handler chain */ public java.util.List getHandlerChain(); @@ -59,7 +59,7 @@ public interface Binding { * Get the URI for this binding instance. * * @return String The binding identifier for the port. - * Never returns null + * Never returns {@code null} * * @since 1.6, JAX-WS 2.1 */ diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/Dispatch.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/Dispatch.java index 7c96bab57d8..8bef4ee4cf5 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/Dispatch.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/Dispatch.java @@ -27,10 +27,10 @@ package javax.xml.ws; import java.util.concurrent.Future; -/** The Dispatch interface provides support +/** The {@code Dispatch} interface provides support * for the dynamic invocation of a service endpoint operations. The - * javax.xml.ws.Service - * class acts as a factory for the creation of Dispatch + * {@code javax.xml.ws.Service} + * class acts as a factory for the creation of {@code Dispatch} * instances. * * @since 1.6, JAX-WS 2.0 @@ -39,7 +39,7 @@ public interface Dispatch extends BindingProvider { /** Invoke a service operation synchronously. * - * The client is responsible for ensuring that the msg object + * The client is responsible for ensuring that the {@code msg} object * when marshalled is formed according to the requirements of the protocol * binding in use. * @@ -50,16 +50,16 @@ public interface Dispatch extends BindingProvider { * @throws WebServiceException If a fault occurs during communication with * the service * @throws WebServiceException If there is any error in the configuration of - * the Dispatch instance + * the {@code Dispatch} instance **/ public T invoke(T msg); /** Invoke a service operation asynchronously. The * method returns without waiting for the response to the operation * invocation, the results of the operation are obtained by polling the - * returned Response. + * returned {@code Response}. *

                                - * The client is responsible for ensuring that the msg object + * The client is responsible for ensuring that the {@code msg} object * when marshalled is formed according to the requirements of the protocol * binding in use. * @@ -68,16 +68,16 @@ public interface Dispatch extends BindingProvider { * @return The response message or message payload to the * operation invocation. * @throws WebServiceException If there is any error in the configuration of - * the Dispatch instance + * the {@code Dispatch} instance **/ public Response invokeAsync(T msg); /** Invoke a service operation asynchronously. The * method returns without waiting for the response to the operation * invocation, the results of the operation are communicated to the client - * via the passed in handler. + * via the passed in {@code handler}. *

                                - * The client is responsible for ensuring that the msg object + * The client is responsible for ensuring that the {@code msg} object * when marshalled is formed according to the requirements of the protocol * binding in use. * @@ -85,13 +85,13 @@ public interface Dispatch extends BindingProvider { * the message used to invoke the operation. * @param handler The handler object that will receive the * response to the operation invocation. - * @return A Future object that may be used to check the status + * @return A {@code Future} object that may be used to check the status * of the operation invocation. This object MUST NOT be used to try to * obtain the results of the operation - the object returned from - * Future<?>.get() is implementation dependent + * {@code Future.get()} is implementation dependent * and any use of it will result in non-portable behaviour. * @throws WebServiceException If there is any error in the configuration of - * the Dispatch instance + * the {@code Dispatch} instance **/ public Future invokeAsync(T msg, AsyncHandler handler); @@ -102,14 +102,14 @@ public interface Dispatch extends BindingProvider { * the protocol in use is SOAP/HTTP, this method MUST block until * an HTTP response code has been received or an error occurs. *

                                - * The client is responsible for ensuring that the msg object + * The client is responsible for ensuring that the {@code msg} object * when marshalled is formed according to the requirements of the protocol * binding in use. * * @param msg An object that will form the message or payload of * the message used to invoke the operation. * @throws WebServiceException If there is any error in the configuration of - * the Dispatch instance or if an error occurs during the + * the {@code Dispatch} instance or if an error occurs during the * invocation. **/ public void invokeOneWay(T msg); diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/FaultAction.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/FaultAction.java index 43e37f608ea..7fd4eff7f7e 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/FaultAction.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/FaultAction.java @@ -32,28 +32,28 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * The FaultAction annotation is used inside an {@link Action} + * The {@code FaultAction} annotation is used inside an {@link Action} * annotation to allow an explicit association of a WS-Addressing - * Action message addressing property with the fault + * {@code Action} message addressing property with the {@code fault} * messages of the WSDL operation mapped from the exception class. *

                                - * The wsam:Action attribute value in the fault - * message in the generated WSDL operation mapped for className - * class is equal to the corresponding value in the FaultAction. - * For the exact computation of wsam:Action values for the + * The {@code wsam:Action} attribute value in the {@code fault} + * message in the generated WSDL operation mapped for {@code className} + * class is equal to the corresponding value in the {@code FaultAction}. + * For the exact computation of {@code wsam:Action} values for the * fault messages, refer to the algorithm in the JAX-WS specification. * *

                                - * Example 1: Specify explicit values for Action message addressing - * property for the input, output and fault message + * Example 1: Specify explicit values for {@code Action} message addressing + * property for the {@code input}, {@code output} and {@code fault} message * if the Java method throws only one service specific exception. * *

                                - * @WebService(targetNamespace="http://example.com/numbers")
                                - * public class AddNumbersImpl {
                                - *     @Action(
                                + * {@literal @}WebService(targetNamespace="http://example.com/numbers")
                                + *  public class AddNumbersImpl {
                                + *    {@literal @}Action(
                                  *         fault = {
                                - *             @FaultAction(className=AddNumbersException.class, value="http://example.com/faultAction")
                                + *             {@literal @}FaultAction(className=AddNumbersException.class, value="http://example.com/faultAction")
                                  *         })
                                  *     public int addNumbers(int number1, int number2)
                                  *         throws AddNumbersException {
                                @@ -64,86 +64,86 @@ import java.lang.annotation.Target;
                                  *
                                  * The generated WSDL looks like:
                                  *
                                - * 
                                - *   <definitions targetNamespace="http://example.com/numbers" ...>
                                + * 
                                 {@code
                                + *   
                                  *     ...
                                - *     <portType name="AddNumbersPortType">
                                - *       <operation name="AddNumbers">
                                + *     
                                + *       
                                  *         ...
                                - *         <fault message="tns:AddNumbersException" name="AddNumbersException"
                                - *           wsam:Action="http://example.com/faultAction"/>
                                - *       </operation>
                                - *     </portType>
                                + *         wsam:Action="http://example.com/faultAction"{@code />
                                + *       
                                + *     
                                  *     ...
                                - *   </definitions>
                                + *    }
                                  * 
                                * *

                                - * Example 2: Here is an example that shows if the explicit value for Action + * Example 2: Here is an example that shows if the explicit value for {@code Action} * message addressing property for the service specific exception is not present. * *

                                - * @WebService(targetNamespace="http://example.com/numbers")
                                - * public class AddNumbersImpl {
                                + * {@literal @}WebService(targetNamespace="http://example.com/numbers")
                                + *  public class AddNumbersImpl {
                                  *     public int addNumbers(int number1, int number2)
                                  *         throws AddNumbersException {
                                  *         return number1 + number2;
                                  *     }
                                - * }
                                + *  }
                                  * 
                                * * The generated WSDL looks like: * - *
                                - *   <definitions targetNamespace="http://example.com/numbers" ...>
                                + * 
                                {@code
                                + *   
                                  *     ...
                                - *     <portType name="AddNumbersPortType">
                                - *       <operation name="AddNumbers">
                                + *     
                                + *       
                                  *         ...
                                - *         <fault message="tns:addNumbersFault" name="InvalidNumbers"
                                - *           wsam:Action="http://example.com/numbers/AddNumbersPortType/AddNumbers/Fault/AddNumbersException"/>
                                - *       </operation>
                                - *     </portType>
                                + *         wsam:Action="http://example.com/numbers/AddNumbersPortType/AddNumbers/Fault/AddNumbersException"{@code />
                                + *       
                                + *     
                                  *     ...
                                - *   </definitions>
                                - * 
                                + * + * }
                                * *

                                - * Example 3: Here is an example that shows how to specify explicit values for Action + * Example 3: Here is an example that shows how to specify explicit values for {@code Action} * message addressing property if the Java method throws more than one service specific exception. * *

                                - * @WebService(targetNamespace="http://example.com/numbers")
                                - * public class AddNumbersImpl {
                                - *     @Action(
                                + * {@literal @}WebService(targetNamespace="http://example.com/numbers")
                                + *  public class AddNumbersImpl {
                                + *    {@literal @}Action(
                                  *         fault = {
                                - *             @FaultAction(className=AddNumbersException.class, value="http://example.com/addFaultAction"),
                                - *             @FaultAction(className=TooBigNumbersException.class, value="http://example.com/toobigFaultAction")
                                + *             {@literal @}FaultAction(className=AddNumbersException.class, value="http://example.com/addFaultAction"),
                                + *             {@literal @}FaultAction(className=TooBigNumbersException.class, value="http://example.com/toobigFaultAction")
                                  *         })
                                  *     public int addNumbers(int number1, int number2)
                                  *         throws AddNumbersException, TooBigNumbersException {
                                  *         return number1 + number2;
                                  *     }
                                - * }
                                + *  }
                                  * 
                                * * The generated WSDL looks like: * - *
                                - *   <definitions targetNamespace="http://example.com/numbers" ...>
                                + * 
                                 {@code
                                + *   
                                  *     ...
                                - *     <portType name="AddNumbersPortType">
                                - *       <operation name="AddNumbers">
                                + *     
                                + *       
                                  *         ...
                                - *         <fault message="tns:addNumbersFault" name="AddNumbersException"
                                - *           wsam:Action="http://example.com/addFaultAction"/>
                                - *         <fault message="tns:tooBigNumbersFault" name="TooBigNumbersException"
                                - *           wsam:Action="http://example.com/toobigFaultAction"/>
                                - *       </operation>
                                - *     </portType>
                                + *         wsam:Action="http://example.com/addFaultAction"{@code />
                                + *         wsam:Action="http://example.com/toobigFaultAction"{@code />
                                + *       
                                + *     
                                  *     ...
                                - *   </definitions>
                                - * 
                                + * + * }
                                * * @since 1.6, JAX-WS 2.1 */ @@ -158,7 +158,7 @@ public @interface FaultAction { Class className(); /** - * Value of WS-Addressing Action message addressing property for the exception + * Value of WS-Addressing {@code Action} message addressing property for the exception */ String value() default ""; } diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/WebServicePermission.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/WebServicePermission.java index 743243f22f6..08751c4ea5a 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/WebServicePermission.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/WebServicePermission.java @@ -35,16 +35,14 @@ import java.security.BasicPermission; * with them. *

                                * The following permission target name is defined: - *

                                *

                                *
                                publishEndpoint *
                                + * The {@code publishEndpoint} permission allows publishing a + * web service endpoint using the {@code publish} methods + * defined by the {@code javax.xml.ws.Endpoint} class. *

                                - * The publishEndpoint permission allows publishing a - * web service endpoint using the publish methods - * defined by the javax.xml.ws.Endpoint class. - *

                                - * Granting publishEndpoint allows the application to be + * Granting {@code publishEndpoint} allows the application to be * exposed as a network service. Depending on the security of the runtime and * the security of the application, this may introduce a security hole that * is remotely exploitable. @@ -64,7 +62,7 @@ public final class WebServicePermission extends BasicPermission { /** * Creates a new permission with the specified name. * - * @param name the name of the WebServicePermission + * @param name the name of the {@code WebServicePermission} */ public WebServicePermission(String name) { super(name); @@ -73,11 +71,11 @@ public final class WebServicePermission extends BasicPermission { /** * Creates a new permission with the specified name and actions. * - * The actions parameter is currently unused and - * it should be null. + * The {@code actions} parameter is currently unused and + * it should be {@code null}. * - * @param name the name of the WebServicePermission - * @param actions should be null + * @param name the name of the {@code WebServicePermission} + * @param actions should be {@code null} */ public WebServicePermission(String name, String actions) { super(name, actions); diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/handler/HandlerResolver.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/handler/HandlerResolver.java index c0f2f97361b..7f1358c0e71 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/handler/HandlerResolver.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/handler/HandlerResolver.java @@ -26,15 +26,15 @@ package javax.xml.ws.handler; /** - * HandlerResolver is an interface implemented + * {@code HandlerResolver} is an interface implemented * by an application to get control over the handler chain * set on proxy/dispatch objects at the time of their creation. *

                                - * A HandlerResolver may be set on a Service - * using the setHandlerResolver method. - *

                                - * When the runtime invokes a HandlerResolver, it will - * pass it a PortInfo object containing information + * A {@code HandlerResolver} may be set on a {@code Service} + * using the {@code setHandlerResolver} method. + *

                                + * When the runtime invokes a {@code HandlerResolver}, it will + * pass it a {@code PortInfo} object containing information * about the port that the proxy/dispatch object will be accessing. * * @see javax.xml.ws.Service#setHandlerResolver @@ -47,7 +47,7 @@ public interface HandlerResolver { * Gets the handler chain for the specified port. * * @param portInfo Contains information about the port being accessed. - * @return java.util.List<Handler> chain + * @return {@code java.util.List} chain **/ public java.util.List getHandlerChain(PortInfo portInfo); } diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/handler/MessageContext.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/handler/MessageContext.java index 35525fc0440..aab8550dead 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/handler/MessageContext.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/handler/MessageContext.java @@ -27,12 +27,12 @@ package javax.xml.ws.handler; import java.util.Map; /** - * The interface MessageContext abstracts the message - * context that is processed by a handler in the handle + * The interface {@code MessageContext} abstracts the message + * context that is processed by a handler in the {@code handle} * method. * - *

                                The MessageContext interface provides methods to - * manage a property set. MessageContext properties + *

                                The {@code MessageContext} interface provides methods to + * manage a property set. {@code MessageContext} properties * enable handlers in a handler chain to share processing related * state. * @@ -41,8 +41,8 @@ import java.util.Map; public interface MessageContext extends Map { /** - * Standard property: message direction, true for - * outbound messages, false for inbound. + * Standard property: message direction, {@code true} for + * outbound messages, {@code false} for inbound. *

                                Type: boolean */ public static final String MESSAGE_OUTBOUND_PROPERTY = @@ -51,7 +51,7 @@ public interface MessageContext extends Map { /** * Standard property: Map of attachments to a message for the inbound * message, key is the MIME Content-ID, value is a DataHandler. - *

                                Type: java.util.Map<String,DataHandler> + *

                                Type: {@code java.util.Map} */ public static final String INBOUND_MESSAGE_ATTACHMENTS = "javax.xml.ws.binding.attachments.inbound"; @@ -59,7 +59,7 @@ public interface MessageContext extends Map { /** * Standard property: Map of attachments to a message for the outbound * message, key is the MIME Content-ID, value is a DataHandler. - *

                                Type: java.util.Map<String,DataHandler> + *

                                Type: {@code java.util.Map} */ public static final String OUTBOUND_MESSAGE_ATTACHMENTS = "javax.xml.ws.binding.attachments.outbound"; @@ -108,14 +108,14 @@ public interface MessageContext extends Map { /** * Standard property: HTTP request headers. - *

                                Type: java.util.Map<java.lang.String, java.util.List<java.lang.String>> + *

                                Type: {@code java.util.Map>} */ public static final String HTTP_REQUEST_HEADERS = "javax.xml.ws.http.request.headers"; /** * Standard property: HTTP response headers. - *

                                Type: java.util.Map<java.lang.String, java.util.List<java.lang.String>> + *

                                Type: {@code java.util.Map>} */ public static final String HTTP_RESPONSE_HEADERS = "javax.xml.ws.http.response.headers"; @@ -166,7 +166,7 @@ public interface MessageContext extends Map { * Standard property: WS Addressing Reference Parameters. * The list MUST include all SOAP headers marked with the * wsa:IsReferenceParameter="true" attribute. - *

                                Type: List<Element> + *

                                Type: {@code List} * * @since 1.6, JAX-WS 2.1 */ @@ -174,10 +174,10 @@ public interface MessageContext extends Map { "javax.xml.ws.reference.parameters"; /** - * Property scope. Properties scoped as APPLICATION are + * Property scope. Properties scoped as {@code APPLICATION} are * visible to handlers, * client applications and service endpoints; properties scoped as - * HANDLER + * {@code HANDLER} * are only normally visible to handlers. */ public enum Scope {APPLICATION, HANDLER}; @@ -186,7 +186,7 @@ public interface MessageContext extends Map { * Sets the scope of a property. * * @param name Name of the property associated with the - * MessageContext + * {@code MessageContext} * @param scope Desired scope of the property * @throws java.lang.IllegalArgumentException if an illegal * property name is specified diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/AddressingFeature.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/AddressingFeature.java index 8f9d730d797..2da2aaf14dc 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/AddressingFeature.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/AddressingFeature.java @@ -52,10 +52,10 @@ import javax.xml.ws.Service; * receiver. * *

                                - * If the feature is enabled, the required property determines + * If the feature is enabled, the {@code required} property determines * whether the endpoint requires WS-Addressing. If it is set true, * WS-Addressing headers MUST be present on incoming and outgoing messages. - * By default the required property is false. + * By default the {@code required} property is {@code false}. * *

                                * If the web service developer has not explicitly enabled this feature, @@ -75,31 +75,31 @@ import javax.xml.ws.Service; * *

                                * Example 1: Possible Policy Assertion in the generated WSDL for - * @Addressing - *

                                - *   <wsam:Addressing wsp:Optional="true">
                                - *     <wsp:Policy/>
                                - *   </wsam:Addressing>
                                + * {@code @Addressing}
                                + * 
                                 {@code
                                + *   
                                + *     
                                + *    }
                                  * 
                                * *

                                * Example 2: Possible Policy Assertion in the generated WSDL for - * @Addressing(required=true) - *

                                - *   <wsam:Addressing>
                                - *     <wsp:Policy/>
                                - *   </wsam:Addressing>
                                + * {@code @Addressing(required=true)}
                                + * 
                                 {@code
                                + *   
                                + *     
                                + *    }
                                  * 
                                * *

                                * Example 3: Possible Policy Assertion in the generated WSDL for - * @Addressing(required=true, responses=Responses.ANONYMOUS) - *

                                - *   <wsam:Addressing>
                                - *      <wsp:Policy>
                                - *        <wsam:AnonymousResponses/>
                                - *      </wsp:Policy>
                                - *   </wsam:Addressing>
                                + * {@code @Addressing(required=true, responses=Responses.ANONYMOUS)}
                                + * 
                                 {@code
                                + *   
                                + *      
                                + *        
                                + *      
                                + *    }
                                  * 
                                * *

                                @@ -181,7 +181,7 @@ public final class AddressingFeature extends WebServiceFeature { private final Responses responses; /** - * Creates and configures an AddressingFeature with the + * Creates and configures an {@code AddressingFeature} with the * use of addressing requirements. The created feature enables * ws-addressing i.e. supports ws-addressing but doesn't require * its use. It is also configured to accept all the response types. @@ -191,8 +191,8 @@ public final class AddressingFeature extends WebServiceFeature { } /** - * Creates and configures an AddressingFeature with the - * use of addressing requirements. If enabled is true, + * Creates and configures an {@code AddressingFeature} with the + * use of addressing requirements. If {@code enabled} is true, * it enables ws-addressing i.e. supports ws-addressing but doesn't * require its use. It also configures to accept all the response types. * @@ -204,9 +204,9 @@ public final class AddressingFeature extends WebServiceFeature { } /** - * Creates and configures an AddressingFeature with the - * use of addressing requirements. If enabled and - * required are true, it enables ws-addressing and + * Creates and configures an {@code AddressingFeature} with the + * use of addressing requirements. If {@code enabled} and + * {@code required} are true, it enables ws-addressing and * requires its use. It also configures to accept all the response types. * * @param enabled true enables ws-addressing i.e.ws-addressing @@ -218,11 +218,11 @@ public final class AddressingFeature extends WebServiceFeature { } /** - * Creates and configures an AddressingFeature with the - * use of addressing requirements. If enabled and - * required are true, it enables ws-addressing and + * Creates and configures an {@code AddressingFeature} with the + * use of addressing requirements. If {@code enabled} and + * {@code required} are true, it enables ws-addressing and * requires its use. Also, the response types can be configured using - * responses parameter. + * {@code responses} parameter. * * @param enabled true enables ws-addressing i.e.ws-addressing * is supported but doesn't require its use @@ -260,7 +260,6 @@ public final class AddressingFeature extends WebServiceFeature { * requires the use of anonymous responses, or non-anonymous responses, * or all responses. * - *

                                * @return {@link Responses#ALL} when endpoint supports all types of * responses, * {@link Responses#ANONYMOUS} when endpoint requires the use of diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/MTOM.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/MTOM.java index da6714e9a7e..cd59f0ffcbb 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/MTOM.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/MTOM.java @@ -40,14 +40,14 @@ import javax.xml.ws.WebServiceProvider; * web service. *

                                * This annotation MUST only be used in conjunction the - * javax.jws.WebService, {@link WebServiceProvider}, + * {@code javax.jws.WebService}, {@link WebServiceProvider}, * {@link WebServiceRef} annotations. - * When used with the javax.jws.WebService annotation this + * When used with the {@code javax.jws.WebService} annotation this * annotation MUST only be used on the service endpoint implementation * class. - * When used with a WebServiceRef annotation, this annotation + * When used with a {@code WebServiceRef} annotation, this annotation * MUST only be used when a proxy instance is created. The injected SEI - * proxy, and endpoint MUST honor the values of the MTOM + * proxy, and endpoint MUST honor the values of the {@code MTOM} * annotation. *

                                * @@ -69,7 +69,7 @@ public @interface MTOM { /** * Property for MTOM threshold value. When MTOM is enabled, binary data above this * size in bytes will be XOP encoded or sent as attachment. The value of this property - * MUST always be >= 0. Default value is 0. + * MUST always be {@literal >=} 0. Default value is 0. */ int threshold() default 0; } diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/MTOMFeature.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/MTOMFeature.java index 232f98f91c2..4ffb051a641 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/MTOMFeature.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/MTOMFeature.java @@ -67,14 +67,14 @@ public final class MTOMFeature extends WebServiceFeature { * Property for MTOM threshold value. This property serves as a hint when * MTOM is enabled, binary data above this size in bytes SHOULD be sent * as attachment. - * The value of this property MUST always be >= 0. Default value is 0. + * The value of this property MUST always be {@literal >=} 0. Default value is 0. */ // should be changed to private final, keeping original modifier to keep backwards compatibility protected int threshold; /** - * Create an MTOMFeature. + * Create an {@code MTOMFeature}. * The instance created will be enabled. */ public MTOMFeature() { @@ -83,7 +83,7 @@ public final class MTOMFeature extends WebServiceFeature { } /** - * Creates an MTOMFeature. + * Creates a {@code MTOMFeature}. * * @param enabled specifies if this feature should be enabled or not */ @@ -94,13 +94,13 @@ public final class MTOMFeature extends WebServiceFeature { /** - * Creates an MTOMFeature. + * Creates a {@code MTOMFeature}. * The instance created will be enabled. * * @param threshold the size in bytes that binary data SHOULD be before * being sent as an attachment. * - * @throws WebServiceException if threshold is < 0 + * @throws WebServiceException if threshold is {@literal <} 0 */ public MTOMFeature(int threshold) { if (threshold < 0) @@ -110,13 +110,13 @@ public final class MTOMFeature extends WebServiceFeature { } /** - * Creates an MTOMFeature. + * Creates a {@code MTOMFeature}. * * @param enabled specifies if this feature should be enabled or not * @param threshold the size in bytes that binary data SHOULD be before * being sent as an attachment. * - * @throws WebServiceException if threshold is < 0 + * @throws WebServiceException if threshold is {@literal <} 0 */ public MTOMFeature(boolean enabled, int threshold) { if (threshold < 0) diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/SOAPBinding.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/SOAPBinding.java index 4b9d88887f4..885328b14e1 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/SOAPBinding.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/soap/SOAPBinding.java @@ -31,7 +31,7 @@ import javax.xml.ws.Binding; import javax.xml.soap.SOAPFactory; import javax.xml.soap.MessageFactory; -/** The SOAPBinding interface is an abstraction for +/** The {@code SOAPBinding} interface is an abstraction for * the SOAP binding. * * @since 1.6, JAX-WS 2.0 @@ -63,7 +63,7 @@ public interface SOAPBinding extends Binding { /** Gets the roles played by the SOAP binding instance. * - * @return Set<String> The set of roles played by the binding instance. + * @return {@code Set} The set of roles played by the binding instance. **/ public Set getRoles(); @@ -76,9 +76,9 @@ public interface SOAPBinding extends Binding { public void setRoles(Set roles); /** - * Returns true if the use of MTOM is enabled. + * Returns {@code true} if the use of MTOM is enabled. * - * @return true if and only if the use of MTOM is enabled. + * @return {@code true} if and only if the use of MTOM is enabled. **/ public boolean isMTOMEnabled(); @@ -86,7 +86,7 @@ public interface SOAPBinding extends Binding { /** * Enables or disables use of MTOM. * - * @param flag A boolean specifying whether the use of MTOM should + * @param flag A {@code boolean} specifying whether the use of MTOM should * be enabled or disabled. * @throws WebServiceException If the specified setting is not supported * by this binding instance. @@ -95,14 +95,14 @@ public interface SOAPBinding extends Binding { public void setMTOMEnabled(boolean flag); /** - * Gets the SAAJ SOAPFactory instance used by this SOAP binding. + * Gets the SAAJ {@code SOAPFactory} instance used by this SOAP binding. * * @return SOAPFactory instance used by this SOAP binding. **/ public SOAPFactory getSOAPFactory(); /** - * Gets the SAAJ MessageFactory instance used by this SOAP binding. + * Gets the SAAJ {@code MessageFactory} instance used by this SOAP binding. * * @return MessageFactory instance used by this SOAP binding. **/ diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/spi/Provider.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/spi/Provider.java index 8c8b802130f..785a58a2c6f 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/spi/Provider.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/spi/Provider.java @@ -37,9 +37,8 @@ import javax.xml.ws.wsaddressing.W3CEndpointReference; import org.w3c.dom.Element; /** - * Service provider for ServiceDelegate and - * Endpoint objects. - *

                                + * Service provider for {@code ServiceDelegate} and + * {@code Endpoint} objects. * * @since 1.6, JAX-WS 2.0 */ @@ -47,14 +46,14 @@ public abstract class Provider { /** * A constant representing the property used to lookup the - * name of a Provider implementation + * name of a {@code Provider} implementation * class. */ static public final String JAXWSPROVIDER_PROPERTY = "javax.xml.ws.spi.Provider"; /** * A constant representing the name of the default - * Provider implementation class. + * {@code Provider} implementation class. **/ // Using two strings so that package renaming doesn't change it static final String DEFAULT_JAXWSPROVIDER @@ -72,22 +71,21 @@ public abstract class Provider { *

                                * The algorithm used to locate the provider subclass to use consists * of the following steps: - *

                                *

                                  *
                                • * If a resource with the name of - * META-INF/services/javax.xml.ws.spi.Provider + * {@code META-INF/services/javax.xml.ws.spi.Provider} * exists, then its first line, if present, is used as the UTF-8 encoded * name of the implementation class. *
                                • *
                                • * If the $java.home/lib/jaxws.properties file exists and it is readable by - * the java.util.Properties.load(InputStream) method and it contains - * an entry whose key is javax.xml.ws.spi.Provider, then the value of + * the {@code java.util.Properties.load(InputStream)} method and it contains + * an entry whose key is {@code javax.xml.ws.spi.Provider}, then the value of * that entry is used as the name of the implementation class. *
                                • *
                                • - * If a system property with the name javax.xml.ws.spi.Provider + * If a system property with the name {@code javax.xml.ws.spi.Provider} * is defined, then its value is used as the name of the implementation class. *
                                • *
                                • @@ -136,12 +134,12 @@ public abstract class Provider { /** * Creates a service delegate object. - *

                                  + * * @param wsdlDocumentLocation A URL pointing to the WSDL document - * for the service, or null if there isn't one. + * for the service, or {@code null} if there isn't one. * @param serviceName The qualified name of the service. * @param serviceClass The service class, which MUST be either - * javax.xml.ws.Service or a subclass thereof. + * {@code javax.xml.ws.Service} or a subclass thereof. * @return The newly created service delegate. */ public abstract ServiceDelegate createServiceDelegate( @@ -150,12 +148,12 @@ public abstract class Provider { /** * Creates a service delegate object. - *

                                  + * * @param wsdlDocumentLocation A URL pointing to the WSDL document - * for the service, or null if there isn't one. + * for the service, or {@code null} if there isn't one. * @param serviceName The qualified name of the service. * @param serviceClass The service class, which MUST be either - * javax.xml.ws.Service or a subclass thereof. + * {@code javax.xml.ws.Service} or a subclass thereof. * @param features Web Service features that must be configured on * the service. If the provider doesn't understand a feature, * it must throw a WebServiceException. @@ -205,18 +203,18 @@ public abstract class Provider { /** * read an EndpointReference from the infoset contained in - * eprInfoset. + * {@code eprInfoset}. * * @param eprInfoset infoset for EndpointReference * - * @return the EndpointReference unmarshalled from - * eprInfoset. This method never returns null. + * @return the {@code EndpointReference} unmarshalled from + * {@code eprInfoset}. This method never returns {@code null}. * * @throws WebServiceException If there is an error creating the - * EndpointReference from the specified eprInfoset. + * {@code EndpointReference} from the specified {@code eprInfoset}. * - * @throws NullPointerException If the null - * eprInfoset value is given. + * @throws NullPointerException If the {@code null} + * {@code eprInfoset} value is given. * * @since 1.6, JAX-WS 2.1 **/ @@ -226,31 +224,31 @@ public abstract class Provider { /** * The getPort method returns a proxy. If there * are any reference parameters in the - * endpointReference, then those reference + * {@code endpointReference}, then those reference * parameters MUST appear as SOAP headers, indicating them to be * reference parameters, on all messages sent to the endpoint. - * The parameter serviceEndpointInterface specifies + * The parameter {@code serviceEndpointInterface} specifies * the service endpoint interface that is supported by the * returned proxy. - * The parameter endpointReference specifies the + * The parameter {@code endpointReference} specifies the * endpoint that will be invoked by the returned proxy. * In the implementation of this method, the JAX-WS * runtime system takes the responsibility of selecting a protocol * binding (and a port) and configuring the proxy accordingly from * the WSDL metadata of the - * serviceEndpointInterface and the EndpointReference. + * {@code serviceEndpointInterface} and the {@code EndpointReference}. * For this method * to successfully return a proxy, WSDL metadata MUST be available and the - * endpointReference MUST contain an implementation understood - * serviceName metadata. + * {@code endpointReference} MUST contain an implementation understood + * {@code serviceName} metadata. * * * @param endpointReference the EndpointReference that will * be invoked by the returned proxy. * @param serviceEndpointInterface Service endpoint interface * @param features A list of WebServiceFeatures to configure on the - * proxy. Supported features not in the features - * parameter will have their default values. + * proxy. Supported features not in the {@code features + * } parameter will have their default values. * @return Object Proxy instance that supports the * specified service endpoint interface * @throws WebServiceException @@ -260,10 +258,10 @@ public abstract class Provider { *

                                • If there is any missing WSDL metadata * as required by this method} *
                                • If this - * endpointReference + * {@code endpointReference} * is illegal *
                                • If an illegal - * serviceEndpointInterface + * {@code serviceEndpointInterface} * is specified *
                                • If a feature is enabled that is not compatible with * this port or is unsupported. @@ -278,60 +276,60 @@ public abstract class Provider { WebServiceFeature... features); /** - * Factory method to create a W3CEndpointReference. + * Factory method to create a {@code W3CEndpointReference}. * *

                                  - * This method can be used to create a W3CEndpointReference - * for any endpoint by specifying the address property along + * This method can be used to create a {@code W3CEndpointReference} + * for any endpoint by specifying the {@code address} property along * with any other desired properties. This method - * can also be used to create a W3CEndpointReference for + * can also be used to create a {@code W3CEndpointReference} for * an endpoint that is published by the same Java EE application. - * To do so the address property can be provided or this - * method can automatically determine the address of + * To do so the {@code address} property can be provided or this + * method can automatically determine the {@code address} of * an endpoint that is published by the same Java EE application and is - * identified by the serviceName and - * portName propeties. If the address is - * null and the serviceName and - * portName do not identify an endpoint published by the + * identified by the {@code serviceName} and + * {@code portName} propeties. If the {@code address} is + * {@code null} and the {@code serviceName} and + * {@code portName} do not identify an endpoint published by the * same Java EE application, a - * javax.lang.IllegalStateException MUST be thrown. + * {@code javax.lang.IllegalStateException} MUST be thrown. * * @param address Specifies the address of the target endpoint * @param serviceName Qualified name of the service in the WSDL. * @param portName Qualified name of the endpoint in the WSDL. * @param metadata A list of elements that should be added to the - * W3CEndpointReference instances wsa:metadata + * {@code W3CEndpointReference} instances {@code wsa:metadata} * element. * @param wsdlDocumentLocation URL for the WSDL document location for * the service. * @param referenceParameters Reference parameters to be associated - * with the returned EndpointReference instance. + * with the returned {@code EndpointReference} instance. * - * @return the W3CEndpointReference created from - * serviceName, portName, - * metadata, wsdlDocumentLocation - * and referenceParameters. This method - * never returns null. + * @return the {@code W3CEndpointReference} created from + * {@code serviceName}, {@code portName}, + * {@code metadata}, {@code wsdlDocumentLocation} + * and {@code referenceParameters}. This method + * never returns {@code null}. * * @throws java.lang.IllegalStateException *

                                    - *
                                  • If the address, serviceName and - * portName are all null. - *
                                  • If the serviceName service is null and the - * portName is NOT null. - *
                                  • If the address property is null and - * the serviceName and portName do not + *
                                  • If the {@code address}, {@code serviceName} and + * {@code portName} are all {@code null}. + *
                                  • If the {@code serviceName} service is {@code null} and the + * {@code portName} is NOT {@code null}. + *
                                  • If the {@code address} property is {@code null} and + * the {@code serviceName} and {@code portName} do not * specify a valid endpoint published by the same Java EE * application. - *
                                  • If the serviceNameis NOT null + *
                                  • If the {@code serviceName}is NOT {@code null} * and is not present in the specified WSDL. - *
                                  • If the portName port is not null and it - * is not present in serviceName service in the WSDL. - *
                                  • If the wsdlDocumentLocation is NOT null + *
                                  • If the {@code portName} port is not {@code null} and it + * is not present in {@code serviceName} service in the WSDL. + *
                                  • If the {@code wsdlDocumentLocation} is NOT {@code null} * and does not represent a valid WSDL. *
                                  * @throws WebServiceException If an error occurs while creating the - * W3CEndpointReference. + * {@code W3CEndpointReference}. * * @since 1.6, JAX-WS 2.1 */ @@ -340,73 +338,73 @@ public abstract class Provider { /** - * Factory method to create a W3CEndpointReference. - * Using this method, a W3CEndpointReference instance + * Factory method to create a {@code W3CEndpointReference}. + * Using this method, a {@code W3CEndpointReference} instance * can be created with extension elements, and attributes. - * Provider implementations must override the default + * {@code Provider} implementations must override the default * implementation. * *

                                  - * This method can be used to create a W3CEndpointReference - * for any endpoint by specifying the address property along + * This method can be used to create a {@code W3CEndpointReference} + * for any endpoint by specifying the {@code address} property along * with any other desired properties. This method - * can also be used to create a W3CEndpointReference for + * can also be used to create a {@code W3CEndpointReference} for * an endpoint that is published by the same Java EE application. - * To do so the address property can be provided or this - * method can automatically determine the address of + * To do so the {@code address} property can be provided or this + * method can automatically determine the {@code address} of * an endpoint that is published by the same Java EE application and is - * identified by the serviceName and - * portName propeties. If the address is - * null and the serviceName and - * portName do not identify an endpoint published by the + * identified by the {@code serviceName} and + * {@code portName} propeties. If the {@code address} is + * {@code null} and the {@code serviceName} and + * {@code portName} do not identify an endpoint published by the * same Java EE application, a - * javax.lang.IllegalStateException MUST be thrown. + * {@code javax.lang.IllegalStateException} MUST be thrown. * * @param address Specifies the address of the target endpoint - * @param interfaceName the wsam:InterfaceName element in the - * wsa:Metadata element. + * @param interfaceName the {@code wsam:InterfaceName} element in the + * {@code wsa:Metadata} element. * @param serviceName Qualified name of the service in the WSDL. * @param portName Qualified name of the endpoint in the WSDL. * @param metadata A list of elements that should be added to the - * W3CEndpointReference instances wsa:metadata + * {@code W3CEndpointReference} instances {@code wsa:metadata} * element. * @param wsdlDocumentLocation URL for the WSDL document location for * the service. * @param referenceParameters Reference parameters to be associated - * with the returned EndpointReference instance. + * with the returned {@code EndpointReference} instance. * @param elements extension elements to be associated - * with the returned EndpointReference instance. + * with the returned {@code EndpointReference} instance. * @param attributes extension attributes to be associated - * with the returned EndpointReference instance. + * with the returned {@code EndpointReference} instance. * - * @return the W3CEndpointReference created from - * serviceName, portName, - * metadata, wsdlDocumentLocation - * and referenceParameters. This method - * never returns null. + * @return the {@code W3CEndpointReference} created from + * {@code serviceName}, {@code portName}, + * {@code metadata}, {@code wsdlDocumentLocation} + * and {@code referenceParameters}. This method + * never returns {@code null}. * * @throws java.lang.IllegalStateException *

                                    - *
                                  • If the address, serviceName and - * portName are all null. - *
                                  • If the serviceName service is null and the - * portName is NOT null. - *
                                  • If the address property is null and - * the serviceName and portName do not + *
                                  • If the {@code address}, {@code serviceName} and + * {@code portName} are all {@code null}. + *
                                  • If the {@code serviceName} service is {@code null} and the + * {@code portName} is NOT {@code null}. + *
                                  • If the {@code address} property is {@code null} and + * the {@code serviceName} and {@code portName} do not * specify a valid endpoint published by the same Java EE * application. - *
                                  • If the serviceNameis NOT null + *
                                  • If the {@code serviceName}is NOT {@code null} * and is not present in the specified WSDL. - *
                                  • If the portName port is not null and it - * is not present in serviceName service in the WSDL. - *
                                  • If the wsdlDocumentLocation is NOT null + *
                                  • If the {@code portName} port is not {@code null} and it + * is not present in {@code serviceName} service in the WSDL. + *
                                  • If the {@code wsdlDocumentLocation} is NOT {@code null} * and does not represent a valid WSDL. - *
                                  • If the wsdlDocumentLocation is NOT null but + *
                                  • If the {@code wsdlDocumentLocation} is NOT {@code null} but * wsdli:wsdlLocation's namespace name cannot be got from the available * metadata. *
                                  * @throws WebServiceException If an error occurs while creating the - * W3CEndpointReference. + * {@code W3CEndpointReference}. * @since 1.7, JAX-WS 2.2 */ public W3CEndpointReference createW3CEndpointReference(String address, @@ -419,7 +417,7 @@ public abstract class Provider { /** * Creates and publishes an endpoint object with the specified * address, implementation object and web service features. - * Provider implementations must override the + * {@code Provider} implementations must override the * default implementation. * * @param address A URI specifying the address and transport/protocol @@ -431,8 +429,8 @@ public abstract class Provider { * class MUST be annotated with all the necessary Web service * annotations. * @param features A list of WebServiceFeatures to configure on the - * endpoint. Supported features not in the features - * parameter will have their default values. + * endpoint. Supported features not in the {@code features} + * parameter will have their default values. * @return The newly created endpoint. * @since 1.7, JAX-WS 2.2 */ @@ -443,7 +441,7 @@ public abstract class Provider { /** * Creates an endpoint object with the provided binding, implementation - * object and web service features. Provider implementations + * object and web service features. {@code Provider} implementations * must override the default implementation. * * @param bindingId A URI specifying the desired binding (e.g. SOAP/HTTP) @@ -452,8 +450,8 @@ public abstract class Provider { * class MUST be annotated with all the necessary Web service * annotations. * @param features A list of WebServiceFeatures to configure on the - * endpoint. Supported features not in the features - * parameter will have their default values. + * endpoint. Supported features not in the {@code features} + * parameter will have their default values. * @return The newly created endpoint. * @since 1.7, JAX-WS 2.2 */ @@ -465,7 +463,7 @@ public abstract class Provider { /** * Creates an endpoint object with the provided binding, implementation * class, invoker and web service features. Containers typically use - * this to create Endpoint objects. Provider + * this to create Endpoint objects. {@code Provider} * implementations must override the default implementation. * * @param bindingId A URI specifying the desired binding (e.g. SOAP/HTTP). @@ -475,8 +473,8 @@ public abstract class Provider { * annotations. * @param invoker that does the actual invocation on the service instance. * @param features A list of WebServiceFeatures to configure on the - * endpoint. Supported features not in the features - * parameter will have their default values. + * endpoint. Supported features not in the {@code features + * } parameter will have their default values. * @return The newly created endpoint. * @since 1.7, JAX-WS 2.2 */ diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/spi/WebServiceFeatureAnnotation.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/spi/WebServiceFeatureAnnotation.java index 39c0f25e3c4..74423670e4e 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/spi/WebServiceFeatureAnnotation.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/spi/WebServiceFeatureAnnotation.java @@ -39,27 +39,26 @@ import javax.xml.ws.soap.MTOM; /** * Annotation used to identify other annotations - * as a WebServiceFeature. + * as a {@code WebServiceFeature}. *

                                  - * Each WebServiceFeature annotation annotated with + * Each {@code WebServiceFeature} annotation annotated with * this annotation MUST contain an - * enabled property of type - * boolean with a default value of true. + * {@code enabled} property of type + * {@code boolean} with a default value of {@code true}. *

                                  * JAX-WS defines the following - * WebServiceFeature annotations (Addressing, - * MTOM, RespectBinding), however, an implementation + * {@code WebServiceFeature} annotations ({@code Addressing}, + * {@code MTOM}, {@code RespectBinding}), however, an implementation * may define vendors specific annotations for other features. *

                                  - * Annotations annotated with WebServiceFeatureAnnotation MUST + * Annotations annotated with {@code WebServiceFeatureAnnotation} MUST * have the same @Target of {@link WebServiceRef} annotation, so that the resulting * feature annotation can be used in conjunction with the {@link WebServiceRef} * annotation if necessary. *

                                  * If a JAX-WS implementation encounters an annotation annotated - * with the WebServiceFeatureAnnotation that it does not + * with the {@code WebServiceFeatureAnnotation} that it does not * recognize/support an error MUST be given. - *

                                  * * @see Addressing * @see MTOM @@ -79,8 +78,8 @@ public @interface WebServiceFeatureAnnotation { String id(); /** - * The WebServiceFeature bean that is associated - * with the WebServiceFeature annotation + * The {@code WebServiceFeature} bean that is associated + * with the {@code WebServiceFeature} annotation */ Class bean(); } diff --git a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/spi/http/package-info.java b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/spi/http/package-info.java index d105948e7f4..eed7e5d4a53 100644 --- a/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/spi/http/package-info.java +++ b/jaxws/src/java.xml.ws/share/classes/javax/xml/ws/spi/http/package-info.java @@ -47,7 +47,7 @@ object encapsulates a HTTP request and a response. -

                                  +  
                                  {@literal
                                     Container                               JAX-WS runtime
                                     ---------                               --------------
                                     1. Creates Invoker1, ... InvokerN
                                  @@ -64,10 +64,10 @@
                                    10. EndpointN.publish(HttpContextN)  --> 11. creates HttpHandlerN
                                                                            HttpContextN.setHandler(HttpHandlerN)
                                   
                                  -  
                                  + }
                                  The request processing is done as below(for every request): -
                                  +  
                                  {@literal
                                     Container                               JAX-WS runtime
                                     ---------                               --------------
                                     1. Creates a HttpExchange
                                  @@ -76,14 +76,14 @@
                                                                         <-- 5. Calls Invoker
                                     6. Invokes the actual instance
                                                                             7. Writes the response to HttpExchange
                                  -  
                                  + }

                                  The portable undeployment is done as below:

                                     Container
                                     ---------
                                  -  1. @preDestroy on instances
                                  +  1. {@literal @}preDestroy on instances
                                     2. Endpoint1.stop()
                                     ...
                                     3. EndpointN.stop()
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle.properties
                                  index 427db1f466e..19f062ab0b0 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -30,10 +30,10 @@ BASEDIR_DOESNT_EXIST = \
                                       Non-existent directory: {0}
                                   
                                   VERSION = \
                                  -        schemagen 2.2.12-b150126.1924
                                  +        schemagen 2.2.12-b150331.1824
                                   
                                   FULLVERSION = \
                                  -        schemagen full version "2.2.12-b150126.1924"
                                  +        schemagen full version "2.2.12-b150331.1824"
                                   
                                   USAGE = \
                                   Usage: schemagen [-options ...]  \n\
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_de.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_de.properties
                                  index 435ed7150a6..1de04cc98b7 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_de.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_de.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -27,8 +27,8 @@ UNEXPECTED_NGCC_TOKEN = Nicht erkanntes {0} in Zeile {1} Spalte {2}
                                   
                                   BASEDIR_DOESNT_EXIST = Nicht vorhandenes Verzeichnis: {0}
                                   
                                  -VERSION = schemagen 2.2.12-b150126.1924
                                  +VERSION = schemagen 2.2.12-b150331.1824
                                   
                                  -FULLVERSION = schemagen vollst\u00E4ndige Version "2.2.12-b150126.1924"
                                  +FULLVERSION = schemagen vollst\u00E4ndige Version "2.2.12-b150331.1824"
                                   
                                   USAGE = Verwendung: schemagen [-options ...]  \nOptionen: \n\\ \\ \\ \\ -d              : Gibt an, wo die von Prozessor und javac generierten Klassendateien gespeichert werden sollen\n\\ \\ \\ \\ -cp             : Gibt an, wo die vom Benutzer angegebenen Dateien gespeichert sind\n\\ \\ \\ \\ -classpath      : Gibt an, wo die vom Benutzer angegebenen Dateien gespeichert sind\n\\ \\ \\ \\ -encoding   : Gibt die Codierung f\u00FCr die Annotationsverarbeitung/den javac-Aufruf an \n\\ \\ \\ \\ -episode        : Generiert Episodendatei f\u00FCr separate Kompilierung\n\\ \\ \\ \\ -version              : Zeigt Versionsinformation an\n\\ \\ \\ \\ -fullversion          : Zeigt vollst\u00E4ndige Versionsinformationen an\n\\ \\ \\ \\ -help                 : Zeigt diese Verwendungsmeldung an
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_es.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_es.properties
                                  index c6d5aad27fa..015e45a1be0 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_es.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_es.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -27,8 +27,8 @@ UNEXPECTED_NGCC_TOKEN = Aparece un {0} inesperado en la l\u00EDnea {1} y la colu
                                   
                                   BASEDIR_DOESNT_EXIST = Directorio no existente: {0}
                                   
                                  -VERSION = schemagen 2.2.12-b150126.1924
                                  +VERSION = schemagen 2.2.12-b150331.1824
                                   
                                  -FULLVERSION = versi\u00F3n completa de schemagen "2.2.12-b150126.1924"
                                  +FULLVERSION = versi\u00F3n completa de schemagen "2.2.12-b150331.1824"
                                   
                                   USAGE = Sintaxis: schemagen [-options ...]  \nOpciones: \n\\ \\ \\ \\ -d              : especifique d\u00F3nde se colocan los archivos de clase generados por javac y el procesador\n\\ \\ \\ \\ -cp             : especifique d\u00F3nde se encuentran los archivos especificados por el usuario\n\\ \\ \\ \\ -encoding   : especifique la codificaci\u00F3n que se va a utilizar para el procesamiento de anotaciones/llamada de javac\n\\ \\ \\ \\ -episode        : genera un archivo de episodio para una compilaci\u00F3n diferente\n\\ \\ \\ \\ -version              : muestra la informaci\u00F3n de la versi\u00F3n\n\\ \\ \\ \\ -fullversion          : muestra la informaci\u00F3n completa de la versi\u00F3n\n\\ \\ \\ \\ -help                 : muestra este mensaje de sintaxis
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_fr.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_fr.properties
                                  index 756a94788fa..a006426db90 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_fr.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_fr.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -27,8 +27,8 @@ UNEXPECTED_NGCC_TOKEN = Un \u00E9l\u00E9ment {0} inattendu appara\u00EEt \u00E0
                                   
                                   BASEDIR_DOESNT_EXIST = R\u00E9pertoire {0} inexistant
                                   
                                  -VERSION = schemagen 2.2.12-b150126.1924
                                  +VERSION = schemagen 2.2.12-b150331.1824
                                   
                                  -FULLVERSION = version compl\u00E8te de schemagen "2.2.12-b150126.1924"
                                  +FULLVERSION = version compl\u00E8te de schemagen "2.2.12-b150331.1824"
                                   
                                   USAGE = Syntaxe : schemagen [-options ...]  \nOptions : \n\ \ \ \ -d  : indiquez o\u00F9 placer les fichiers de classe g\u00E9n\u00E9r\u00E9s par le processeur et le compilateur javac\n\ \ \ \ -cp  : indiquez o\u00F9 trouver les fichiers sp\u00E9cifi\u00E9s par l'utilisateur\n\ \ \ \ -classpath  : indiquez o\u00F9 trouver les fichiers sp\u00E9cifi\u00E9s par l'utilisateur\n\ \ \ \ -encoding  : indiquez l'encodage \u00E0 utiliser pour l'appel de javac/traitement de l'annotation \n\ \ \ \ -episode  : g\u00E9n\u00E9rez un fichier d'\u00E9pisode pour la compilation s\u00E9par\u00E9e\n\ \ \ \ -version : affichez les informations de version\n\ \ \ \ -fullversion : affichez les informations compl\u00E8tes de version\n\ \ \ \ -help : affichez ce message de syntaxe
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_it.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_it.properties
                                  index 992b68e2c77..ca32febc263 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_it.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_it.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -27,8 +27,8 @@ UNEXPECTED_NGCC_TOKEN = {0} imprevisto visualizzato sulla riga {1} colonna {2}
                                   
                                   BASEDIR_DOESNT_EXIST = Directory non esistente: {0}
                                   
                                  -VERSION = schemagen 2.2.12-b150126.1924
                                  +VERSION = schemagen 2.2.12-b150331.1824
                                   
                                  -FULLVERSION = versione completa schemagen "2.2.12-b150126.1924"
                                  +FULLVERSION = versione completa schemagen "2.2.12-b150331.1824"
                                   
                                   USAGE = Uso: schemagen [-options ...]  \nOpzioni: \n\ \ \ \ -d              : specifica dove posizionare il processore e i file della classe generata javac\n\ \ \ \ -cp             : specifica dove trovare i file specificati dall'utente\n\ \ \ \ -classpath      : specifica dove trovare i file specificati dall'utente\n\ \ \ \ -encoding   : specifica la codifica da usare per l'elaborazione dell'annotazione/richiamo javac \n\ \ \ \ -episode        : genera il file di episodio per la compilazione separata\n\ \ \ \ -version              : visualizza le informazioni sulla versione\n\ \ \ \ -fullversion          : visualizza le informazioni sulla versione completa\n\ \ \ \ -help                 : visualizza questo messaggio sull'uso
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_ja.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_ja.properties
                                  index bf3e933ce1c..28f152ffcbd 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_ja.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_ja.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -27,8 +27,8 @@ UNEXPECTED_NGCC_TOKEN = \u4E88\u671F\u3057\u306A\u3044{0}\u304C\u884C{1}\u3001\u
                                   
                                   BASEDIR_DOESNT_EXIST = \u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u304C\u5B58\u5728\u3057\u307E\u305B\u3093: {0}
                                   
                                  -VERSION = schemagen 2.2.12-b150126.1924
                                  +VERSION = schemagen 2.2.12-b150331.1824
                                   
                                  -FULLVERSION = schemagen\u30D5\u30EB\u30FB\u30D0\u30FC\u30B8\u30E7\u30F3"2.2.12-b150126.1924"
                                  +FULLVERSION = schemagen\u30D5\u30EB\u30FB\u30D0\u30FC\u30B8\u30E7\u30F3"2.2.12-b150331.1824"
                                   
                                   USAGE = \u4F7F\u7528\u65B9\u6CD5: schemagen [-options ...]  \n\u30AA\u30D7\u30B7\u30E7\u30F3: \n\ \ \ \ -d              : \u30D7\u30ED\u30BB\u30C3\u30B5\u304A\u3088\u3073javac\u304C\u751F\u6210\u3057\u305F\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u7F6E\u304F\u4F4D\u7F6E\u3092\u6307\u5B9A\u3057\u307E\u3059\n\ \ \ \ -cp             : \u30E6\u30FC\u30B6\u30FC\u304C\u6307\u5B9A\u3057\u305F\u30D5\u30A1\u30A4\u30EB\u3092\u691C\u7D22\u3059\u308B\u4F4D\u7F6E\u3092\u6307\u5B9A\u3057\u307E\u3059\n\ \ \ \ -classpath      : \u30E6\u30FC\u30B6\u30FC\u304C\u6307\u5B9A\u3057\u305F\u30D5\u30A1\u30A4\u30EB\u3092\u691C\u7D22\u3059\u308B\u4F4D\u7F6E\u3092\u6307\u5B9A\u3057\u307E\u3059\n\ \ \ \ -encoding   : \u6CE8\u91C8\u51E6\u7406/javac\u547C\u51FA\u3057\u306B\u4F7F\u7528\u3059\u308B\u30A8\u30F3\u30B3\u30FC\u30C7\u30A3\u30F3\u30B0\u3092\u6307\u5B9A\u3057\u307E\u3059\n\ \ \ \ -episode        : \u30B3\u30F3\u30D1\u30A4\u30EB\u3054\u3068\u306B\u30A8\u30D4\u30BD\u30FC\u30C9\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u751F\u6210\u3057\u307E\u3059\n\ \ \ \ -version              : \u30D0\u30FC\u30B8\u30E7\u30F3\u60C5\u5831\u3092\u8868\u793A\u3057\u307E\u3059\n\ \ \ \ -fullversion          : \u30D5\u30EB\u30FB\u30D0\u30FC\u30B8\u30E7\u30F3\u60C5\u5831\u3092\u8868\u793A\u3057\u307E\u3059\n\ \ \ \ -help                 : \u3053\u306E\u4F7F\u7528\u4F8B\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u8868\u793A\u3057\u307E\u3059
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_ko.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_ko.properties
                                  index 31ba0ab9637..1f7cd2ef605 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_ko.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_ko.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -27,8 +27,8 @@ UNEXPECTED_NGCC_TOKEN = \uC608\uC0C1\uCE58 \uC54A\uC740 {0}\uC774(\uAC00) {1}\uD
                                   
                                   BASEDIR_DOESNT_EXIST = \uC874\uC7AC\uD558\uC9C0 \uC54A\uB294 \uB514\uB809\uD1A0\uB9AC: {0}
                                   
                                  -VERSION = schemagen 2.2.12-b150126.1924
                                  +VERSION = schemagen 2.2.12-b150331.1824
                                   
                                  -FULLVERSION = schemagen \uC815\uC2DD \uBC84\uC804 "2.2.12-b150126.1924"
                                  +FULLVERSION = schemagen \uC815\uC2DD \uBC84\uC804 "2.2.12-b150331.1824"
                                   
                                   USAGE = \uC0AC\uC6A9\uBC95: schemagen [-options ...]  \n\uC635\uC158: \n\ \ \ \ -d              : \uD504\uB85C\uC138\uC11C \uBC0F javac\uC5D0\uC11C \uC0DD\uC131\uD55C \uD074\uB798\uC2A4 \uD30C\uC77C\uC744 \uBC30\uCE58\uD560 \uC704\uCE58\uB97C \uC9C0\uC815\uD569\uB2C8\uB2E4.\n\ \ \ \ -cp             : \uC0AC\uC6A9\uC790\uAC00 \uC9C0\uC815\uD55C \uD30C\uC77C\uC744 \uCC3E\uC744 \uC704\uCE58\uB97C \uC9C0\uC815\uD569\uB2C8\uB2E4.\n\ \ \ \ -classpath      : \uC0AC\uC6A9\uC790\uAC00 \uC9C0\uC815\uD55C \uD30C\uC77C\uC744 \uCC3E\uC744 \uC704\uCE58\uB97C \uC9C0\uC815\uD569\uB2C8\uB2E4.\n\ \ \ \ -encoding   : \uC8FC\uC11D \uCC98\uB9AC/javac \uD638\uCD9C\uC5D0 \uC0AC\uC6A9\uD560 \uC778\uCF54\uB529\uC744 \uC9C0\uC815\uD569\uB2C8\uB2E4. \n\ \ \ \ -episode        : \uBCC4\uB3C4 \uCEF4\uD30C\uC77C\uC744 \uC704\uD574 episode \uD30C\uC77C\uC744 \uC0DD\uC131\uD569\uB2C8\uB2E4.\n\ \ \ \ -version              : \uBC84\uC804 \uC815\uBCF4\uB97C \uD45C\uC2DC\uD569\uB2C8\uB2E4.\n\ \ \ \ -fullversion          : \uC815\uC2DD \uBC84\uC804 \uC815\uBCF4\uB97C \uD45C\uC2DC\uD569\uB2C8\uB2E4.\n\ \ \ \ -help                 : \uC774 \uC0AC\uC6A9\uBC95 \uBA54\uC2DC\uC9C0\uB97C \uD45C\uC2DC\uD569\uB2C8\uB2E4.
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_pt_BR.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_pt_BR.properties
                                  index c2f4155d874..0596527faad 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_pt_BR.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_pt_BR.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -27,8 +27,8 @@ UNEXPECTED_NGCC_TOKEN = {0} inesperado aparece na linha {1} coluna {2}
                                   
                                   BASEDIR_DOESNT_EXIST = Diret\u00F3rio n\u00E3o existente: {0}
                                   
                                  -VERSION = gera\u00E7\u00E3o do esquema 2.2.12-b150126.1924
                                  +VERSION = gera\u00E7\u00E3o do esquema 2.2.12-b150331.1824
                                   
                                  -FULLVERSION = vers\u00E3o completa da gera\u00E7\u00E3o do esquema "2.2.12-b150126.1924"
                                  +FULLVERSION = vers\u00E3o completa da gera\u00E7\u00E3o do esquema "2.2.12-b150331.1824"
                                   
                                   USAGE = Uso: gera\u00E7\u00E3o do esquema [-options ...]  \nOp\u00E7\u00F5es: \n\\ \\ \\ \\ -d              : especificar onde colocar o processador e os arquivos da classe gerados por javac\n\\ \\ \\ \\ -cp             : especificar onde localizar arquivos especificados pelo usu\u00E1rio\n\\ \\ \\ \\ -classpath      : especificar onde localizar os arquivos especificados pelo usu\u00E1rio\n\\ \\ \\ \\ -encoding   : especificar codifica\u00E7\u00E3o a ser usada para processamento de anota\u00E7\u00E3o/chamada javac \n\\ \\ \\ \\ -episode        : gerar arquivo do epis\u00F3dio para compila\u00E7\u00E3o separada\n\\ \\ \\ \\ -version              : exibir informa\u00E7\u00F5es da vers\u00E3o\n\\ \\ \\ \\ -fullversion          : exibir informa\u00E7\u00F5es da vers\u00E3o completa\n\\ \\ \\ \\ -help                 : exibir esta mensagem de uso
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_zh_CN.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_zh_CN.properties
                                  index cec06517656..3d780676808 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_zh_CN.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_zh_CN.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -27,8 +27,8 @@ UNEXPECTED_NGCC_TOKEN = \u5728\u7B2C {1} \u884C, \u7B2C {2} \u5217\u51FA\u73B0\u
                                   
                                   BASEDIR_DOESNT_EXIST = \u4E0D\u5B58\u5728\u7684\u76EE\u5F55: {0}
                                   
                                  -VERSION = schemagen 2.2.12-b150126.1924
                                  +VERSION = schemagen 2.2.12-b150331.1824
                                   
                                  -FULLVERSION = schemagen \u5B8C\u6574\u7248\u672C "2.2.12-b150126.1924"
                                  +FULLVERSION = schemagen \u5B8C\u6574\u7248\u672C "2.2.12-b150331.1824"
                                   
                                   USAGE = \u7528\u6CD5: schemagen [-options ...]  \n\u9009\u9879: \n\ \ \ \ -d              : \u6307\u5B9A\u653E\u7F6E\u5904\u7406\u7A0B\u5E8F\u548C javac \u751F\u6210\u7684\u7C7B\u6587\u4EF6\u7684\u4F4D\u7F6E\n\ \ \ \ -cp             : \u6307\u5B9A\u67E5\u627E\u7528\u6237\u6307\u5B9A\u6587\u4EF6\u7684\u4F4D\u7F6E\n\ \ \ \ -classpath      : \u6307\u5B9A\u67E5\u627E\u7528\u6237\u6307\u5B9A\u6587\u4EF6\u7684\u4F4D\u7F6E\n\ \ \ \ -encoding   : \u6307\u5B9A\u7528\u4E8E\u6CE8\u91CA\u5904\u7406/javac \u8C03\u7528\u7684\u7F16\u7801\n\ \ \ \ -episode        : \u751F\u6210\u7247\u6BB5\u6587\u4EF6\u4EE5\u4F9B\u5355\u72EC\u7F16\u8BD1\n\ \ \ \ -version              : \u663E\u793A\u7248\u672C\u4FE1\u606F\n\ \ \ \ -fullversion          : \u663E\u793A\u5B8C\u6574\u7684\u7248\u672C\u4FE1\u606F\n\ \ \ \ -help                 : \u663E\u793A\u6B64\u7528\u6CD5\u6D88\u606F
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_zh_TW.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_zh_TW.properties
                                  index 938aef76528..1ded7446a25 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_zh_TW.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/MessageBundle_zh_TW.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -27,8 +27,8 @@ UNEXPECTED_NGCC_TOKEN = \u672A\u9810\u671F\u7684 {0} \u986F\u793A\u65BC\u884C {1
                                   
                                   BASEDIR_DOESNT_EXIST = \u4E0D\u5B58\u5728\u7684\u76EE\u9304: {0}
                                   
                                  -VERSION = schemagen 2.2.12-b150126.1924
                                  +VERSION = schemagen 2.2.12-b150331.1824
                                   
                                  -FULLVERSION = schemagen \u5B8C\u6574\u7248\u672C "2.2.12-b150126.1924"
                                  +FULLVERSION = schemagen \u5B8C\u6574\u7248\u672C "2.2.12-b150331.1824"
                                   
                                   USAGE = \u7528\u6CD5: schemagen [-options ...]  \n\u9078\u9805: \n\\ \\ \\ \\ -d              : \u6307\u5B9A\u8655\u7406\u5668\u4EE5\u53CA javac \u7522\u751F\u7684\u985E\u5225\u6A94\u6848\u653E\u7F6E\u4F4D\u7F6E\n\\ \\ \\ \\ -cp             : \u6307\u5B9A\u8981\u5C0B\u627E\u4F7F\u7528\u8005\u6307\u5B9A\u6A94\u6848\u7684\u4F4D\u7F6E\n\\ \\ \\ \\ -classpath      : \u6307\u5B9A\u8981\u5C0B\u627E\u4F7F\u7528\u8005\u6307\u5B9A\u6A94\u6848\u7684\u4F4D\u7F6E\n\\ \\ \\ \\ -encoding   : \u6307\u5B9A\u8981\u7528\u65BC\u8A3B\u89E3\u8655\u7406/javac \u547C\u53EB\u7684\u7DE8\u78BC \n\\ \\ \\ \\ -episode        : \u7522\u751F\u7368\u7ACB\u7DE8\u8B6F\u7684\u4E8B\u4EF6 (episode) \u6A94\u6848\n\\ \\ \\ \\ -version              : \u986F\u793A\u7248\u672C\u8CC7\u8A0A\n\\ \\ \\ \\ -fullversion          : \u986F\u793A\u5B8C\u6574\u7248\u672C\u8CC7\u8A0A\n\\ \\ \\ \\ -help                 : \u986F\u793A\u6B64\u7528\u6CD5\u8A0A\u606F
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/SchemaGenerator.java b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/SchemaGenerator.java
                                  index 47d62d8e713..6a3eec71d50 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/SchemaGenerator.java
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/SchemaGenerator.java
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                    *
                                    * This code is free software; you can redistribute it and/or modify it
                                  @@ -158,7 +158,12 @@ public class SchemaGenerator {
                                           while (cl != null) {
                                               if (cl instanceof URLClassLoader) {
                                                   for (URL url : ((URLClassLoader) cl).getURLs()) {
                                  -                    appendPath(cp, url.getPath());
                                  +                    try {
                                  +                        appendPath(cp,new File(url.toURI()).getPath());
                                  +                    } catch(URISyntaxException ex) {
                                  +                        /*If the URL is not properly formated - skip it*/
                                  +                        LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                                  +                    }
                                                   }
                                               }
                                               cl = cl.getParent();
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/ap/SchemaGenerator.java b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/ap/SchemaGenerator.java
                                  index a15b1453e9f..2a8b59894fe 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/ap/SchemaGenerator.java
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/ap/SchemaGenerator.java
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * 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,8 +23,6 @@
                                    * questions.
                                    */
                                   
                                  -
                                  -
                                   package com.sun.tools.internal.jxc.ap;
                                   
                                   import com.sun.tools.internal.jxc.api.JXC;
                                  @@ -89,12 +87,12 @@ public class SchemaGenerator extends AbstractProcessor {
                                       public boolean process(Set annotations, RoundEnvironment roundEnv) {
                                           final ErrorReceiverImpl errorListener = new ErrorReceiverImpl(processingEnv);
                                   
                                  -        List classes = new ArrayList();
                                  +        List classesToBeBound = new ArrayList();
                                           // simply ignore all the interface definitions,
                                           // so that users won't have to manually exclude interfaces, which is silly.
                                  -        filterClass(classes, roundEnv.getRootElements());
                                  +        filterClass(classesToBeBound, roundEnv.getRootElements());
                                   
                                  -        J2SJAXBModel model = JXC.createJavaCompiler().bind(classes, Collections.emptyMap(), null, processingEnv);
                                  +        J2SJAXBModel model = JXC.createJavaCompiler().bind(classesToBeBound, Collections.emptyMap(), null, processingEnv);
                                           if (model == null)
                                               return false; // error
                                   
                                  @@ -133,11 +131,17 @@ public class SchemaGenerator extends AbstractProcessor {
                                           return false;
                                       }
                                   
                                  -    private void filterClass(List classes, Collection elements) {
                                  +    /**
                                  +     * Filter classes (note that enum is kind of class) from elements tree
                                  +     * @param result list of found classes
                                  +     * @param elements tree to be filtered
                                  +     */
                                  +    private void filterClass(List result, Collection elements) {
                                           for (Element element : elements) {
                                  -            if (element.getKind().equals(ElementKind.CLASS) || element.getKind().equals(ElementKind.ENUM)) {
                                  -                classes.add(new Reference((TypeElement) element, processingEnv));
                                  -                filterClass(classes, ElementFilter.typesIn(element.getEnclosedElements()));
                                  +            final ElementKind kind = element.getKind();
                                  +            if (ElementKind.CLASS.equals(kind) || ElementKind.ENUM.equals(kind)) {
                                  +                result.add(new Reference((TypeElement) element, processingEnv));
                                  +                filterClass(result, ElementFilter.typesIn(element.getEnclosedElements()));
                                               }
                                           }
                                       }
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/model/nav/ApNavigator.java b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/model/nav/ApNavigator.java
                                  index 803d32973a9..359bfc4cec0 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/model/nav/ApNavigator.java
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/jxc/model/nav/ApNavigator.java
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                    *
                                    * This code is free software; you can redistribute it and/or modify it
                                  @@ -30,7 +30,12 @@ import com.sun.source.util.TreePath;
                                   import com.sun.source.util.Trees;
                                   import com.sun.xml.internal.bind.v2.model.nav.Navigator;
                                   import com.sun.xml.internal.bind.v2.runtime.Location;
                                  -
                                  +import java.lang.annotation.Annotation;
                                  +import java.util.ArrayList;
                                  +import java.util.Collection;
                                  +import java.util.HashMap;
                                  +import java.util.List;
                                  +import java.util.Map;
                                   import javax.annotation.processing.ProcessingEnvironment;
                                   import javax.lang.model.element.AnnotationMirror;
                                   import javax.lang.model.element.Element;
                                  @@ -52,12 +57,6 @@ import javax.lang.model.util.ElementFilter;
                                   import javax.lang.model.util.Elements;
                                   import javax.lang.model.util.SimpleTypeVisitor6;
                                   import javax.lang.model.util.Types;
                                  -import java.lang.annotation.Annotation;
                                  -import java.util.Collection;
                                  -import java.util.HashMap;
                                  -import java.util.HashSet;
                                  -import java.util.List;
                                  -import java.util.Map;
                                   
                                   /**
                                    * {@link Navigator} implementation for annotation processing.
                                  @@ -241,7 +240,7 @@ public final class ApNavigator implements Navigator elements = env.getElementUtils().getAllMembers(clazz);
                                  -        Collection constants = new HashSet();
                                  +        Collection constants = new ArrayList();
                                           for (Element element : elements) {
                                               if (element.getKind().equals(ElementKind.ENUM_CONSTANT)) {
                                                   constants.add((VariableElement) element);
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle.properties
                                  index fd88f7f2d7f..de2930362f8 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -171,20 +171,20 @@ Driver.CompilingSchema = \
                                   Driver.FailedToGenerateCode = \
                                           Failed to produce code.
                                   
                                  -# DO NOT localize the 2.2.12-b150126.1924 string - it is a token for an mvn 
                                  +# DO NOT localize the 2.2.12-b150331.1824 string - it is a token for an mvn 
                                   Driver.FilePrologComment = \
                                  -        This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.12-b150126.1924 \n\
                                  +        This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.12-b150331.1824 \n\
                                           See http://java.sun.com/xml/jaxb \n\
                                           Any modifications to this file will be lost upon recompilation of the source schema. \n\
                                           Generated on: {0} \n
                                   
                                   Driver.Version = \
                                  -        xjc 2.2.12-b150126.1924
                                  +        xjc 2.2.12-b150331.1824
                                   
                                   Driver.FullVersion = \
                                  -        xjc full version "2.2.12-b150126.1924"
                                  +        xjc full version "2.2.12-b150331.1824"
                                   
                                  -Driver.BuildID = 2.2.12-b150126.1924
                                  +Driver.BuildID = 2.2.12-b150331.1824
                                   
                                   # for JDK integration - include version in source zip
                                   jaxb.jdk.version=@@JAXB_JDK_VERSION@@
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_de.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_de.properties
                                  index 97271e9de79..6c30fbf39cc 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_de.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_de.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -96,14 +96,14 @@ Driver.CompilingSchema = Ein Schema wird kompiliert ...
                                   
                                   Driver.FailedToGenerateCode = Code konnte nicht erzeugt werden.
                                   
                                  -# DO NOT localize the 2.2.12-b150126.1924 string - it is a token for an mvn 
                                  -Driver.FilePrologComment = Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.12-b150126.1924 generiert \nSiehe http://java.sun.com/xml/jaxb \n\u00c4nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. \nGeneriert: {0} \n
                                  +# DO NOT localize the 2.2.12-b150331.1824 string - it is a token for an mvn 
                                  +Driver.FilePrologComment = Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.12-b150331.1824 generiert \nSiehe http://java.sun.com/xml/jaxb \n\u00c4nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. \nGeneriert: {0} \n
                                   
                                  -Driver.Version = xjc 2.2.12-b150126.1924
                                  +Driver.Version = xjc 2.2.12-b150331.1824
                                   
                                  -Driver.FullVersion = xjc vollst\u00E4ndige Version "2.2.12-b150126.1924"
                                  +Driver.FullVersion = xjc vollst\u00E4ndige Version "2.2.12-b150331.1824"
                                   
                                  -Driver.BuildID = 2.2.12-b150126.1924
                                  +Driver.BuildID = 2.2.12-b150331.1824
                                   
                                   # for JDK integration - include version in source zip
                                   jaxb.jdk.version=@@JAXB_JDK_VERSION@@
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_es.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_es.properties
                                  index eadb52fac88..0ad71a458d2 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_es.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_es.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -96,14 +96,14 @@ Driver.CompilingSchema = Compilando un esquema...
                                   
                                   Driver.FailedToGenerateCode = Fallo al producir c\u00f3digo.
                                   
                                  -# DO NOT localize the 2.2.12-b150126.1924 string - it is a token for an mvn 
                                  -Driver.FilePrologComment = Este archivo ha sido generado por la arquitectura JavaTM para la implantaci\u00f3n de la referencia de enlace (JAXB) XML v2.2.12-b150126.1924 \nVisite http://java.sun.com/xml/jaxb \nTodas las modificaciones realizadas en este archivo se perder\u00e1n si se vuelve a compilar el esquema de origen. \nGenerado el: {0} \n
                                  +# DO NOT localize the 2.2.12-b150331.1824 string - it is a token for an mvn 
                                  +Driver.FilePrologComment = Este archivo ha sido generado por la arquitectura JavaTM para la implantaci\u00f3n de la referencia de enlace (JAXB) XML v2.2.12-b150331.1824 \nVisite http://java.sun.com/xml/jaxb \nTodas las modificaciones realizadas en este archivo se perder\u00e1n si se vuelve a compilar el esquema de origen. \nGenerado el: {0} \n
                                   
                                  -Driver.Version = xjc 2.2.12-b150126.1924
                                  +Driver.Version = xjc 2.2.12-b150331.1824
                                   
                                  -Driver.FullVersion = versi\u00F3n completa de xjc "2.2.12-b150126.1924"
                                  +Driver.FullVersion = versi\u00F3n completa de xjc "2.2.12-b150331.1824"
                                   
                                  -Driver.BuildID = 2.2.12-b150126.1924
                                  +Driver.BuildID = 2.2.12-b150331.1824
                                   
                                   # for JDK integration - include version in source zip
                                   jaxb.jdk.version=@@JAXB_JDK_VERSION@@
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_fr.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_fr.properties
                                  index dd19a1687df..dab13109b69 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_fr.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_fr.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -96,14 +96,14 @@ Driver.CompilingSchema = compilation d'un sch\u00e9ma...
                                   
                                   Driver.FailedToGenerateCode = Echec de la production du code.
                                   
                                  -# DO NOT localize the 2.2.12-b150126.1924 string - it is a token for an mvn 
                                  -Driver.FilePrologComment = Ce fichier a \u00e9t\u00e9 g\u00e9n\u00e9r\u00e9 par l''impl\u00e9mentation de r\u00e9f\u00e9rence JavaTM Architecture for XML Binding (JAXB), v2.2.12-b150126.1924 \nVoir http://java.sun.com/xml/jaxb \nToute modification apport\u00e9e \u00e0 ce fichier sera perdue lors de la recompilation du sch\u00e9ma source. \nG\u00e9n\u00e9r\u00e9 le : {0} \n
                                  +# DO NOT localize the 2.2.12-b150331.1824 string - it is a token for an mvn 
                                  +Driver.FilePrologComment = Ce fichier a \u00e9t\u00e9 g\u00e9n\u00e9r\u00e9 par l''impl\u00e9mentation de r\u00e9f\u00e9rence JavaTM Architecture for XML Binding (JAXB), v2.2.12-b150331.1824 \nVoir http://java.sun.com/xml/jaxb \nToute modification apport\u00e9e \u00e0 ce fichier sera perdue lors de la recompilation du sch\u00e9ma source. \nG\u00e9n\u00e9r\u00e9 le : {0} \n
                                   
                                  -Driver.Version = xjc 2.2.12-b150126.1924
                                  +Driver.Version = xjc 2.2.12-b150331.1824
                                   
                                  -Driver.FullVersion = version compl\u00E8te xjc "2.2.12-b150126.1924"
                                  +Driver.FullVersion = version compl\u00E8te xjc "2.2.12-b150331.1824"
                                   
                                  -Driver.BuildID = 2.2.12-b150126.1924
                                  +Driver.BuildID = 2.2.12-b150331.1824
                                   
                                   # for JDK integration - include version in source zip
                                   jaxb.jdk.version=@@JAXB_JDK_VERSION@@
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_it.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_it.properties
                                  index f259cb3d291..32b7221ef35 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_it.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_it.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -96,14 +96,14 @@ Driver.CompilingSchema = compilazione di uno schema in corso...
                                   
                                   Driver.FailedToGenerateCode = Produzione del codice non riuscita.
                                   
                                  -# DO NOT localize the 2.2.12-b150126.1924 string - it is a token for an mvn 
                                  -Driver.FilePrologComment = Questo file \u00e8 stato generato dall''architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.12-b150126.1924 \nVedere http://java.sun.com/xml/jaxb \nQualsiasi modifica a questo file andr\u00e0 persa durante la ricompilazione dello schema di origine. \nGenerato il: {0} \n
                                  +# DO NOT localize the 2.2.12-b150331.1824 string - it is a token for an mvn 
                                  +Driver.FilePrologComment = Questo file \u00e8 stato generato dall''architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.12-b150331.1824 \nVedere http://java.sun.com/xml/jaxb \nQualsiasi modifica a questo file andr\u00e0 persa durante la ricompilazione dello schema di origine. \nGenerato il: {0} \n
                                   
                                  -Driver.Version = xjc 2.2.12-b150126.1924
                                  +Driver.Version = xjc 2.2.12-b150331.1824
                                   
                                  -Driver.FullVersion = versione completa xjc "2.2.12-b150126.1924"
                                  +Driver.FullVersion = versione completa xjc "2.2.12-b150331.1824"
                                   
                                  -Driver.BuildID = 2.2.12-b150126.1924
                                  +Driver.BuildID = 2.2.12-b150331.1824
                                   
                                   # for JDK integration - include version in source zip
                                   jaxb.jdk.version=@@JAXB_JDK_VERSION@@
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_ja.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_ja.properties
                                  index 9674081427e..366edb4becc 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_ja.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_ja.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -96,14 +96,14 @@ Driver.CompilingSchema = \u30b9\u30ad\u30fc\u30de\u306e\u30b3\u30f3\u30d1\u30a4\
                                   
                                   Driver.FailedToGenerateCode = \u30b3\u30fc\u30c9\u306e\u751f\u6210\u306b\u5931\u6557\u3057\u307e\u3057\u305f\u3002
                                   
                                  -# DO NOT localize the 2.2.12-b150126.1924 string - it is a token for an mvn 
                                  -Driver.FilePrologComment = \u3053\u306e\u30d5\u30a1\u30a4\u30eb\u306f\u3001JavaTM Architecture for XML Binding(JAXB) Reference Implementation\u3001v2.2.12-b150126.1924\u306b\u3088\u3063\u3066\u751f\u6210\u3055\u308c\u307e\u3057\u305f \nhttp://java.sun.com/xml/jaxb\u3092\u53c2\u7167\u3057\u3066\u304f\u3060\u3055\u3044 \n\u30bd\u30fc\u30b9\u30fb\u30b9\u30ad\u30fc\u30de\u306e\u518d\u30b3\u30f3\u30d1\u30a4\u30eb\u6642\u306b\u3053\u306e\u30d5\u30a1\u30a4\u30eb\u306e\u5909\u66f4\u306f\u5931\u308f\u308c\u307e\u3059\u3002 \n\u751f\u6210\u65e5: {0} \n
                                  +# DO NOT localize the 2.2.12-b150331.1824 string - it is a token for an mvn 
                                  +Driver.FilePrologComment = \u3053\u306e\u30d5\u30a1\u30a4\u30eb\u306f\u3001JavaTM Architecture for XML Binding(JAXB) Reference Implementation\u3001v2.2.12-b150331.1824\u306b\u3088\u3063\u3066\u751f\u6210\u3055\u308c\u307e\u3057\u305f \nhttp://java.sun.com/xml/jaxb\u3092\u53c2\u7167\u3057\u3066\u304f\u3060\u3055\u3044 \n\u30bd\u30fc\u30b9\u30fb\u30b9\u30ad\u30fc\u30de\u306e\u518d\u30b3\u30f3\u30d1\u30a4\u30eb\u6642\u306b\u3053\u306e\u30d5\u30a1\u30a4\u30eb\u306e\u5909\u66f4\u306f\u5931\u308f\u308c\u307e\u3059\u3002 \n\u751f\u6210\u65e5: {0} \n
                                   
                                  -Driver.Version = xjc 2.2.12-b150126.1924
                                  +Driver.Version = xjc 2.2.12-b150331.1824
                                   
                                  -Driver.FullVersion = xjc\u30D5\u30EB\u30FB\u30D0\u30FC\u30B8\u30E7\u30F3"2.2.12-b150126.1924"
                                  +Driver.FullVersion = xjc\u30D5\u30EB\u30FB\u30D0\u30FC\u30B8\u30E7\u30F3"2.2.12-b150331.1824"
                                   
                                  -Driver.BuildID = 2.2.12-b150126.1924
                                  +Driver.BuildID = 2.2.12-b150331.1824
                                   
                                   # for JDK integration - include version in source zip
                                   jaxb.jdk.version=@@JAXB_JDK_VERSION@@
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_ko.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_ko.properties
                                  index 3715185d805..ffb08b6952e 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_ko.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_ko.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -96,14 +96,14 @@ Driver.CompilingSchema = \uc2a4\ud0a4\ub9c8\ub97c \ucef4\ud30c\uc77c\ud558\ub294
                                   
                                   Driver.FailedToGenerateCode = \ucf54\ub4dc \uc0dd\uc131\uc744 \uc2e4\ud328\ud588\uc2b5\ub2c8\ub2e4.
                                   
                                  -# DO NOT localize the 2.2.12-b150126.1924 string - it is a token for an mvn 
                                  -Driver.FilePrologComment = \uc774 \ud30c\uc77c\uc740 JAXB(JavaTM Architecture for XML Binding) \ucc38\uc870 \uad6c\ud604 2.2.12-b150126.1924 \ubc84\uc804\uc744 \ud1b5\ud574 \uc0dd\uc131\ub418\uc5c8\uc2b5\ub2c8\ub2e4. \nhttp://java.sun.com/xml/jaxb\ub97c \ucc38\uc870\ud558\uc2ed\uc2dc\uc624. \n\uc774 \ud30c\uc77c\uc744 \uc218\uc815\ud558\uba74 \uc18c\uc2a4 \uc2a4\ud0a4\ub9c8\ub97c \uc7ac\ucef4\ud30c\uc77c\ud560 \ub54c \uc218\uc815 \uc0ac\ud56d\uc774 \uc190\uc2e4\ub429\ub2c8\ub2e4. \n\uc0dd\uc131 \ub0a0\uc9dc: {0} \n
                                  +# DO NOT localize the 2.2.12-b150331.1824 string - it is a token for an mvn 
                                  +Driver.FilePrologComment = \uc774 \ud30c\uc77c\uc740 JAXB(JavaTM Architecture for XML Binding) \ucc38\uc870 \uad6c\ud604 2.2.12-b150331.1824 \ubc84\uc804\uc744 \ud1b5\ud574 \uc0dd\uc131\ub418\uc5c8\uc2b5\ub2c8\ub2e4. \nhttp://java.sun.com/xml/jaxb\ub97c \ucc38\uc870\ud558\uc2ed\uc2dc\uc624. \n\uc774 \ud30c\uc77c\uc744 \uc218\uc815\ud558\uba74 \uc18c\uc2a4 \uc2a4\ud0a4\ub9c8\ub97c \uc7ac\ucef4\ud30c\uc77c\ud560 \ub54c \uc218\uc815 \uc0ac\ud56d\uc774 \uc190\uc2e4\ub429\ub2c8\ub2e4. \n\uc0dd\uc131 \ub0a0\uc9dc: {0} \n
                                   
                                  -Driver.Version = XJC 2.2.12-b150126.1924
                                  +Driver.Version = XJC 2.2.12-b150331.1824
                                   
                                  -Driver.FullVersion = XJC \uC815\uC2DD \uBC84\uC804 "2.2.12-b150126.1924"
                                  +Driver.FullVersion = XJC \uC815\uC2DD \uBC84\uC804 "2.2.12-b150331.1824"
                                   
                                  -Driver.BuildID = 2.2.12-b150126.1924
                                  +Driver.BuildID = 2.2.12-b150331.1824
                                   
                                   # for JDK integration - include version in source zip
                                   jaxb.jdk.version=@@JAXB_JDK_VERSION@@
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_pt_BR.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_pt_BR.properties
                                  index 9f44278b4eb..5712ddafe10 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_pt_BR.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_pt_BR.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -96,14 +96,14 @@ Driver.CompilingSchema = compilando um esquema...
                                   
                                   Driver.FailedToGenerateCode = Falha ao produzir o c\u00f3digo.
                                   
                                  -# DO NOT localize the 2.2.12-b150126.1924 string - it is a token for an mvn 
                                  -Driver.FilePrologComment = Este arquivo foi gerado pela Arquitetura JavaTM para Implementa\u00e7\u00e3o de Refer\u00eancia (JAXB) de Bind XML, v2.2.12-b150126.1924 \nConsulte http://java.sun.com/xml/jaxb \nTodas as modifica\u00e7\u00f5es neste arquivo ser\u00e3o perdidas ap\u00f3s a recompila\u00e7\u00e3o do esquema de origem. \nGerado em: {0} \n
                                  +# DO NOT localize the 2.2.12-b150331.1824 string - it is a token for an mvn 
                                  +Driver.FilePrologComment = Este arquivo foi gerado pela Arquitetura JavaTM para Implementa\u00e7\u00e3o de Refer\u00eancia (JAXB) de Bind XML, v2.2.12-b150331.1824 \nConsulte http://java.sun.com/xml/jaxb \nTodas as modifica\u00e7\u00f5es neste arquivo ser\u00e3o perdidas ap\u00f3s a recompila\u00e7\u00e3o do esquema de origem. \nGerado em: {0} \n
                                   
                                  -Driver.Version = xjc 2.2.12-b150126.1924
                                  +Driver.Version = xjc 2.2.12-b150331.1824
                                   
                                  -Driver.FullVersion = vers\u00E3o completa de xjc "2.2.12-b150126.1924"
                                  +Driver.FullVersion = vers\u00E3o completa de xjc "2.2.12-b150331.1824"
                                   
                                  -Driver.BuildID = 2.2.12-b150126.1924
                                  +Driver.BuildID = 2.2.12-b150331.1824
                                   
                                   # for JDK integration - include version in source zip
                                   jaxb.jdk.version=@@JAXB_JDK_VERSION@@
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_zh_CN.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_zh_CN.properties
                                  index 11276a8352a..b5f2d8a505a 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_zh_CN.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_zh_CN.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -96,14 +96,14 @@ Driver.CompilingSchema = \u6b63\u5728\u7f16\u8bd1\u6a21\u5f0f...
                                   
                                   Driver.FailedToGenerateCode = \u65e0\u6cd5\u751f\u6210\u4ee3\u7801\u3002
                                   
                                  -# DO NOT localize the 2.2.12-b150126.1924 string - it is a token for an mvn 
                                  -Driver.FilePrologComment = \u6b64\u6587\u4ef6\u662f\u7531 JavaTM Architecture for XML Binding (JAXB) \u5f15\u7528\u5b9e\u73b0 v2.2.12-b150126.1924 \u751f\u6210\u7684\n\u8bf7\u8bbf\u95ee http://java.sun.com/xml/jaxb \n\u5728\u91cd\u65b0\u7f16\u8bd1\u6e90\u6a21\u5f0f\u65f6, \u5bf9\u6b64\u6587\u4ef6\u7684\u6240\u6709\u4fee\u6539\u90fd\u5c06\u4e22\u5931\u3002\n\u751f\u6210\u65f6\u95f4: {0} \n
                                  +# DO NOT localize the 2.2.12-b150331.1824 string - it is a token for an mvn 
                                  +Driver.FilePrologComment = \u6b64\u6587\u4ef6\u662f\u7531 JavaTM Architecture for XML Binding (JAXB) \u5f15\u7528\u5b9e\u73b0 v2.2.12-b150331.1824 \u751f\u6210\u7684\n\u8bf7\u8bbf\u95ee http://java.sun.com/xml/jaxb \n\u5728\u91cd\u65b0\u7f16\u8bd1\u6e90\u6a21\u5f0f\u65f6, \u5bf9\u6b64\u6587\u4ef6\u7684\u6240\u6709\u4fee\u6539\u90fd\u5c06\u4e22\u5931\u3002\n\u751f\u6210\u65f6\u95f4: {0} \n
                                   
                                  -Driver.Version = xjc 2.2.12-b150126.1924
                                  +Driver.Version = xjc 2.2.12-b150331.1824
                                   
                                  -Driver.FullVersion = xjc \u5B8C\u6574\u7248\u672C "2.2.12-b150126.1924"
                                  +Driver.FullVersion = xjc \u5B8C\u6574\u7248\u672C "2.2.12-b150331.1824"
                                   
                                  -Driver.BuildID = 2.2.12-b150126.1924
                                  +Driver.BuildID = 2.2.12-b150331.1824
                                   
                                   # for JDK integration - include version in source zip
                                   jaxb.jdk.version=@@JAXB_JDK_VERSION@@
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_zh_TW.properties b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_zh_TW.properties
                                  index 27227f5b5c5..d722fc105cc 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_zh_TW.properties
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/MessageBundle_zh_TW.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -96,14 +96,14 @@ Driver.CompilingSchema = \u6b63\u5728\u7de8\u8b6f\u7db1\u8981...
                                   
                                   Driver.FailedToGenerateCode = \u7121\u6cd5\u7522\u751f\u7a0b\u5f0f\u78bc.
                                   
                                  -# DO NOT localize the 2.2.12-b150126.1924 string - it is a token for an mvn 
                                  -Driver.FilePrologComment = \u6b64\u6a94\u6848\u662f\u7531 JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.12-b150126.1924 \u6240\u7522\u751f \n\u8acb\u53c3\u95b1 http://java.sun.com/xml/jaxb \n\u4e00\u65e6\u91cd\u65b0\u7de8\u8b6f\u4f86\u6e90\u7db1\u8981, \u5c0d\u6b64\u6a94\u6848\u6240\u505a\u7684\u4efb\u4f55\u4fee\u6539\u90fd\u5c07\u6703\u907a\u5931. \n\u7522\u751f\u6642\u9593: {0} \n
                                  +# DO NOT localize the 2.2.12-b150331.1824 string - it is a token for an mvn 
                                  +Driver.FilePrologComment = \u6b64\u6a94\u6848\u662f\u7531 JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.12-b150331.1824 \u6240\u7522\u751f \n\u8acb\u53c3\u95b1 http://java.sun.com/xml/jaxb \n\u4e00\u65e6\u91cd\u65b0\u7de8\u8b6f\u4f86\u6e90\u7db1\u8981, \u5c0d\u6b64\u6a94\u6848\u6240\u505a\u7684\u4efb\u4f55\u4fee\u6539\u90fd\u5c07\u6703\u907a\u5931. \n\u7522\u751f\u6642\u9593: {0} \n
                                   
                                  -Driver.Version = xjc 2.2.12-b150126.1924
                                  +Driver.Version = xjc 2.2.12-b150331.1824
                                   
                                  -Driver.FullVersion = xjc \u5B8C\u6574\u7248\u672C "2.2.12-b150126.1924"
                                  +Driver.FullVersion = xjc \u5B8C\u6574\u7248\u672C "2.2.12-b150331.1824"
                                   
                                  -Driver.BuildID = 2.2.12-b150126.1924
                                  +Driver.BuildID = 2.2.12-b150331.1824
                                   
                                   # for JDK integration - include version in source zip
                                   jaxb.jdk.version=@@JAXB_JDK_VERSION@@
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/addon/code_injector/PluginImpl.java b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/addon/code_injector/PluginImpl.java
                                  index 626e97232f5..2d82bab915f 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/addon/code_injector/PluginImpl.java
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/addon/code_injector/PluginImpl.java
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * 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,13 +25,15 @@
                                   
                                   package com.sun.tools.internal.xjc.addon.code_injector;
                                   
                                  +import java.util.Collection;
                                   import java.util.Collections;
                                   import java.util.List;
                                   
                                  +import com.sun.istack.internal.NotNull;
                                   import com.sun.tools.internal.xjc.Options;
                                   import com.sun.tools.internal.xjc.Plugin;
                                   import com.sun.tools.internal.xjc.model.CPluginCustomization;
                                  -import com.sun.tools.internal.xjc.outline.ClassOutline;
                                  +import com.sun.tools.internal.xjc.outline.CustomizableOutline;
                                   import com.sun.tools.internal.xjc.outline.Outline;
                                   import com.sun.tools.internal.xjc.util.DOMUtils;
                                   
                                  @@ -54,7 +56,7 @@ public class PluginImpl extends Plugin {
                                       }
                                   
                                       public boolean isCustomizationTagName(String nsUri, String localName) {
                                  -        return nsUri.equals(Const.NS) && localName.equals("code");
                                  +        return Const.NS.equals(nsUri) && "code".equals(localName);
                                       }
                                   
                                       public String getUsage() {
                                  @@ -62,9 +64,15 @@ public class PluginImpl extends Plugin {
                                       }
                                   
                                       // meat of the processing
                                  -    public boolean run(Outline model, Options opt, ErrorHandler errorHandler) {
                                  -        for( ClassOutline co : model.getClasses() ) {
                                  -            CPluginCustomization c = co.target.getCustomizations().find(Const.NS,"code");
                                  +    public boolean run(@NotNull Outline model, Options opt, ErrorHandler errorHandler) {
                                  +        checkAndInject(model.getClasses());
                                  +        checkAndInject(model.getEnums());
                                  +        return true;
                                  +    }
                                  +
                                  +    private static void checkAndInject(Collection outlines) {
                                  +        for (CustomizableOutline co : outlines) {
                                  +            CPluginCustomization c = co.getTarget().getCustomizations().find(Const.NS, "code");
                                               if(c==null)
                                                   continue;   // no customization --- nothing to inject here
                                   
                                  @@ -74,9 +82,7 @@ public class PluginImpl extends Plugin {
                                               String codeFragment = DOMUtils.getElementText(c.element);
                                   
                                               // inject the specified code fragment into the implementation class.
                                  -            co.implClass.direct(codeFragment);
                                  +            co.getImplClass().direct(codeFragment);
                                           }
                                  -
                                  -        return true;
                                       }
                                   }
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/ClassOutline.java b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/ClassOutline.java
                                  index 1b6e1b664d9..dde38ae363c 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/ClassOutline.java
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/ClassOutline.java
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                    *
                                    * This code is free software; you can redistribute it and/or modify it
                                  @@ -33,6 +33,7 @@ import java.util.List;
                                   import com.sun.codemodel.internal.JClass;
                                   import com.sun.codemodel.internal.JDefinedClass;
                                   import com.sun.tools.internal.xjc.model.CClassInfo;
                                  +import com.sun.tools.internal.xjc.model.CCustomizable;
                                   import com.sun.tools.internal.xjc.model.CPropertyInfo;
                                   import com.sun.istack.internal.NotNull;
                                   
                                  @@ -44,7 +45,7 @@ import com.sun.istack.internal.NotNull;
                                    *
                                    * @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
                                    */
                                  -public abstract class ClassOutline {
                                  +public abstract class ClassOutline implements CustomizableOutline {
                                   
                                       /**
                                        * A {@link Outline} that encloses all the class outlines.
                                  @@ -122,4 +123,14 @@ public abstract class ClassOutline {
                                           if(s==null)     return null;
                                           return parent().getClazz(s);
                                       }
                                  +
                                  +    @Override
                                  +    public JDefinedClass getImplClass() {
                                  +        return implClass;
                                  +    }
                                  +
                                  +    @Override
                                  +    public CCustomizable getTarget() {
                                  +        return target;
                                  +    }
                                   }
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/CustomizableOutline.java b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/CustomizableOutline.java
                                  new file mode 100644
                                  index 00000000000..79c223d5c57
                                  --- /dev/null
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/CustomizableOutline.java
                                  @@ -0,0 +1,53 @@
                                  +/*
                                  + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
                                  + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                  + *
                                  + * This code is free software; you can redistribute it and/or modify it
                                  + * under the terms of the GNU General Public License version 2 only, as
                                  + * published by the Free Software Foundation.  Oracle designates this
                                  + * particular file as subject to the "Classpath" exception as provided
                                  + * by Oracle in the LICENSE file that accompanied this code.
                                  + *
                                  + * This code is distributed in the hope that it will be useful, but WITHOUT
                                  + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
                                  + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
                                  + * version 2 for more details (a copy is included in the LICENSE file that
                                  + * accompanied this code).
                                  + *
                                  + * You should have received a copy of the GNU General Public License version
                                  + * 2 along with this work; if not, write to the Free Software Foundation,
                                  + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
                                  + *
                                  + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
                                  + * or visit www.oracle.com if you need additional information or have any
                                  + * questions.
                                  + */
                                  +
                                  +package com.sun.tools.internal.xjc.outline;
                                  +
                                  +import com.sun.codemodel.internal.JDefinedClass;
                                  +import com.sun.istack.internal.NotNull;
                                  +import com.sun.tools.internal.xjc.model.CCustomizable;
                                  +
                                  +/**
                                  + * This interface describes that outline class could be customized.
                                  + * It provides the bound info from {@link CCustomizable} target. And
                                  + * customization output - implementation class.
                                  + *
                                  + * @author yaroska
                                  + * @since 2.2.12
                                  + */
                                  +public interface CustomizableOutline {
                                  +
                                  +    /**
                                  +     * Provides bound information about customizable target.
                                  +     * @return customizable target
                                  +     */
                                  +    @NotNull CCustomizable getTarget();
                                  +
                                  +    /**
                                  +     * Provides customization output.
                                  +     * @return Implementation class
                                  +     */
                                  +    @NotNull JDefinedClass getImplClass();
                                  +}
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/ElementOutline.java b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/ElementOutline.java
                                  index 34609aa8fec..72d768719ba 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/ElementOutline.java
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/ElementOutline.java
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                    *
                                    * This code is free software; you can redistribute it and/or modify it
                                  @@ -26,6 +26,7 @@
                                   package com.sun.tools.internal.xjc.outline;
                                   
                                   import com.sun.codemodel.internal.JDefinedClass;
                                  +import com.sun.tools.internal.xjc.model.CCustomizable;
                                   import com.sun.tools.internal.xjc.model.CElementInfo;
                                   
                                   /**
                                  @@ -39,7 +40,7 @@ import com.sun.tools.internal.xjc.model.CElementInfo;
                                    *
                                    * @author Kohsuke Kawaguchi
                                    */
                                  -public abstract class ElementOutline {
                                  +public abstract class ElementOutline implements CustomizableOutline {
                                   
                                       /**
                                        * A {@link Outline} that encloses all the class outlines.
                                  @@ -69,4 +70,14 @@ public abstract class ElementOutline {
                                           this.target = target;
                                           this.implClass = implClass;
                                       }
                                  +
                                  +    @Override
                                  +    public CCustomizable getTarget() {
                                  +        return target;
                                  +    }
                                  +
                                  +    @Override
                                  +    public JDefinedClass getImplClass() {
                                  +        return implClass;
                                  +    }
                                   }
                                  diff --git a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/EnumOutline.java b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/EnumOutline.java
                                  index 9ac6b7a97d3..ae48a7212e2 100644
                                  --- a/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/EnumOutline.java
                                  +++ b/jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/outline/EnumOutline.java
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * 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,6 +29,7 @@ import java.util.ArrayList;
                                   import java.util.List;
                                   
                                   import com.sun.codemodel.internal.JDefinedClass;
                                  +import com.sun.tools.internal.xjc.model.CCustomizable;
                                   import com.sun.tools.internal.xjc.model.CEnumLeafInfo;
                                   import com.sun.istack.internal.NotNull;
                                   
                                  @@ -40,7 +41,7 @@ import com.sun.istack.internal.NotNull;
                                    *
                                    * @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
                                    */
                                  -public abstract class EnumOutline {
                                  +public abstract class EnumOutline implements CustomizableOutline {
                                   
                                       /**
                                        * This {@link EnumOutline} holds information about this {@link CEnumLeafInfo}.
                                  @@ -74,4 +75,14 @@ public abstract class EnumOutline {
                                           this.target = target;
                                           this.clazz = clazz;
                                       }
                                  +
                                  +    @Override
                                  +    public JDefinedClass getImplClass() {
                                  +        return clazz;
                                  +    }
                                  +
                                  +    @Override
                                  +    public CCustomizable getTarget() {
                                  +        return target;
                                  +    }
                                   }
                                  diff --git a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/version.properties b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/version.properties
                                  index b18bbc710b0..8cc250fb181 100644
                                  --- a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/version.properties
                                  +++ b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/version.properties
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -23,7 +23,7 @@
                                   # questions.
                                   #
                                   
                                  -build-id=2.2.11-b150127.1410
                                  -build-version=JAX-WS RI 2.2.11-b150127.1410
                                  +build-id=2.2.11-b150402.1412
                                  +build-version=JAX-WS RI 2.2.11-b150402.1412
                                   major-version=2.2.11
                                  -svn-revision=28121d09ed8ac02b76788709ccb4cdb66e03bbfa
                                  +svn-revision=f923291dedcf386c5f408263984a99d7cedf0012
                                  diff --git a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wsdl/document/soap/SOAPConstants.java b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wsdl/document/soap/SOAPConstants.java
                                  index aabf2579a43..7c6a640bee8 100644
                                  --- a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wsdl/document/soap/SOAPConstants.java
                                  +++ b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wsdl/document/soap/SOAPConstants.java
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                    *
                                    * This code is free software; you can redistribute it and/or modify it
                                  diff --git a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wsdl/parser/Internalizer.java b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wsdl/parser/Internalizer.java
                                  index c153cce7f68..d216e6f3608 100644
                                  --- a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wsdl/parser/Internalizer.java
                                  +++ b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wsdl/parser/Internalizer.java
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                    *
                                    * This code is free software; you can redistribute it and/or modify it
                                  @@ -78,7 +78,7 @@ public class Internalizer {
                                       private static final ContextClassloaderLocal xpf = new ContextClassloaderLocal() {
                                           @Override
                                           protected XPathFactory initialValue() throws Exception {
                                  -            return XPathFactory.newInstance();
                                  +            return XmlUtil.newXPathFactory(true);
                                           }
                                       };
                                       /**
                                  diff --git a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wsdl/parser/JAXWSBindingExtensionHandler.java b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wsdl/parser/JAXWSBindingExtensionHandler.java
                                  index 0f12222220c..6801dd9f474 100644
                                  --- a/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wsdl/parser/JAXWSBindingExtensionHandler.java
                                  +++ b/jaxws/src/jdk.xml.ws/share/classes/com/sun/tools/internal/ws/wsdl/parser/JAXWSBindingExtensionHandler.java
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * 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,10 +25,10 @@
                                   
                                   package com.sun.tools.internal.ws.wsdl.parser;
                                   
                                  +import com.sun.tools.internal.ws.util.xml.XmlUtil;
                                   import com.sun.tools.internal.ws.api.wsdl.TWSDLExtensible;
                                   import com.sun.tools.internal.ws.api.wsdl.TWSDLExtension;
                                   import com.sun.tools.internal.ws.api.wsdl.TWSDLParserContext;
                                  -import com.sun.tools.internal.ws.util.xml.XmlUtil;
                                   import com.sun.tools.internal.ws.wsdl.document.*;
                                   import com.sun.tools.internal.ws.wsdl.document.jaxws.CustomName;
                                   import com.sun.tools.internal.ws.wsdl.document.jaxws.JAXWSBinding;
                                  @@ -57,7 +57,7 @@ public class JAXWSBindingExtensionHandler extends AbstractExtensionHandler {
                                       private static final ContextClassloaderLocal xpf = new ContextClassloaderLocal() {
                                           @Override
                                           protected XPathFactory initialValue() throws Exception {
                                  -            return XPathFactory.newInstance();
                                  +            return XmlUtil.newXPathFactory(false);
                                           }
                                       };
                                   
                                  diff --git a/jdk/.hgtags b/jdk/.hgtags
                                  index 4e2ce2b244e..07c91542bbc 100644
                                  --- a/jdk/.hgtags
                                  +++ b/jdk/.hgtags
                                  @@ -298,3 +298,10 @@ a0dad230aeb3b0d5cfd5b0715029e48d50573f8c jdk9-b51
                                   6cb5f5c34009630749a40cefe116d143f0b2583e jdk9-b53
                                   568a62ab7d764d7c74ac1d87387dbe500662b551 jdk9-b54
                                   d49e247dade61f29f771f09b2105857492241156 jdk9-b55
                                  +7969f7b6465e47ce4afa77670ca600b04c1d746c jdk9-b56
                                  +c76339e86ea7da5d9ac7856f3fae9ef73eef04a2 jdk9-b57
                                  +36fc65e80d811ee43aedfc69284224b86a403662 jdk9-b58
                                  +48ee960f29df93a9b2a895621321358a86909086 jdk9-b59
                                  +84c5527f742bc64562e47d3149c16197fe1c4c1a jdk9-b60
                                  +da84dcac1b0b12c5b836b05ac75ecbfadee0cd32 jdk9-b61
                                  +49118e68fbd4cc0044e718c47db681946d5efd69 jdk9-b62
                                  diff --git a/jdk/make/CompileDemos.gmk b/jdk/make/CompileDemos.gmk
                                  index 2d10867948f..3328dbc6cf4 100644
                                  --- a/jdk/make/CompileDemos.gmk
                                  +++ b/jdk/make/CompileDemos.gmk
                                  @@ -45,7 +45,7 @@ DEMO_SHARE_SRC := $(JDK_TOPDIR)/src/demo/share
                                   DEMO_CLOSED_SHARE_SRC := $(JDK_TOPDIR)/src/closed/demo/share
                                   DEMO_SOLARIS_SRC := $(JDK_TOPDIR)/src/demo/solaris
                                   DEMO_OS_TYPE_SRC := $(JDK_TOPDIR)/src/demo/$(OPENJDK_TARGET_OS_TYPE)
                                  -VERSION_INFO_RESOURCE := $(JDK_TOPDIR)/src/java.base/windows/native/common/version.rc
                                  +GLOBAL_VERSION_INFO_RESOURCE := $(JDK_TOPDIR)/src/java.base/windows/native/common/version.rc
                                   
                                   ##################################################################################################
                                   
                                  @@ -230,11 +230,8 @@ define SetupJVMTIDemo
                                         $$(wildcard $$(patsubst %, $(DEMO_SHARE_SRC)/jvmti/%/README.txt, $2)) \
                                         $$(wildcard $$(patsubst %, $(DEMO_SHARE_SRC)/jvmti/%/sample.makefile.txt, $2))
                                     BUILD_DEMO_JVMTI_$1_EXTRA_INC := $$(addprefix -I, $$(BUILD_DEMO_JVMTI_$1_EXTRA_SRC))
                                  -  BUILD_DEMO_JVMTI_$1_LANG := C
                                  -  ifneq (, $4)
                                  -    BUILD_DEMO_JVMTI_$1_LANG := $4
                                  -  endif
                                     ifeq (C++, $4)
                                  +    BUILD_DEMO_JVMTI_$1_TOOLCHAIN := TOOLCHAIN_LINK_CXX
                                       $1_EXTRA_CXX := $(LDFLAGS_CXX_JDK) $(LIBCXX)
                                     endif
                                   
                                  @@ -254,7 +251,7 @@ define SetupJVMTIDemo
                                     # Remove the -incremental:no setting to get .ilk-files like in the old build.
                                     $$(eval $$(call SetupNativeCompilation,BUILD_DEMO_JVMTI_$1, \
                                         SRC := $(DEMO_SHARE_SRC)/jvmti/$1 $$(BUILD_DEMO_JVMTI_$1_EXTRA_SRC), \
                                  -      LANG := $$(BUILD_DEMO_JVMTI_$1_LANG), \
                                  +      TOOLCHAIN := $$(BUILD_DEMO_JVMTI_$1_TOOLCHAIN), \
                                         OPTIMIZATION := LOW, \
                                         CXXFLAGS := $$($1_CXXFLAGS), \
                                         DISABLED_WARNINGS_gcc := $(10), \
                                  @@ -267,7 +264,7 @@ define SetupJVMTIDemo
                                         LDFLAGS_SUFFIX_windows := $6, \
                                         LDFLAGS_SUFFIX_solaris := $7 -lc, \
                                         LDFLAGS_SUFFIX_linux := $8, \
                                  -      VERSIONINFO_RESOURCE := $(VERSION_INFO_RESOURCE), \
                                  +      VERSIONINFO_RESOURCE := $(GLOBAL_VERSION_INFO_RESOURCE), \
                                         RC_FLAGS := $$(RC_FLAGS) \
                                             -D "JDK_FNAME=$1.dll" \
                                             -D "JDK_INTERNAL_NAME=$1" \
                                  @@ -398,7 +395,6 @@ ifeq ($(OPENJDK_TARGET_OS), solaris)
                                   
                                     $(eval $(call SetupNativeCompilation,BUILD_LIBPOLLER, \
                                         SRC := $(DEMO_SOLARIS_SRC)/jni/Poller, \
                                  -      LANG := C, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKLIB) $(SHARED_LIBRARY_FLAGS) \
                                             -I$(SUPPORT_OUTPUTDIR)/demo/classes/jni/Poller, \
                                  diff --git a/jdk/make/Tools.gmk b/jdk/make/Tools.gmk
                                  index 07ac66339a0..0d56ccbb827 100644
                                  --- a/jdk/make/Tools.gmk
                                  +++ b/jdk/make/Tools.gmk
                                  @@ -163,9 +163,7 @@ $(eval $(call SetupCopyFiles,COPY_JIMAGE_SERVICE_PROVIDER, \
                                   ifeq ($(OPENJDK_TARGET_OS), solaris)
                                     $(eval $(call SetupNativeCompilation,ADD_GNU_DEBUGLINK, \
                                         SRC := $(JDK_TOPDIR)/make/src/native/add_gnu_debuglink, \
                                  -      LANG := C, \
                                  -      CC := $(BUILD_CC), \
                                  -      LDEXE := $(BUILD_LD), \
                                  +      TOOLCHAIN := TOOLCHAIN_BUILD, \
                                         LDFLAGS := -lelf, \
                                         OBJECT_DIR := $(BUILDTOOLS_OUTPUTDIR)/objs/add_gnu_debuglink, \
                                         OUTPUT_DIR := $(BUILDTOOLS_OUTPUTDIR)/bin, \
                                  @@ -173,9 +171,7 @@ ifeq ($(OPENJDK_TARGET_OS), solaris)
                                   
                                     $(eval $(call SetupNativeCompilation,FIX_EMPTY_SEC_HDR_FLAGS, \
                                         SRC := $(JDK_TOPDIR)/make/src/native/fix_empty_sec_hdr_flags, \
                                  -      LANG := C, \
                                  -      CC := $(BUILD_CC), \
                                  -      LDEXE := $(BUILD_LD), \
                                  +      TOOLCHAIN := TOOLCHAIN_BUILD, \
                                         LDFLAGS := -lelf, \
                                         OBJECT_DIR := $(BUILDTOOLS_OUTPUTDIR)/objs/fix_empty_sec_hdr_flags, \
                                         OUTPUT_DIR := $(BUILDTOOLS_OUTPUTDIR)/bin, \
                                  diff --git a/jdk/make/copy/Copy-java.base.gmk b/jdk/make/copy/Copy-java.base.gmk
                                  index 296442e0f13..46687333361 100644
                                  --- a/jdk/make/copy/Copy-java.base.gmk
                                  +++ b/jdk/make/copy/Copy-java.base.gmk
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -98,6 +98,8 @@ ifeq ($(OPENJDK_TARGET_OS), macosx)
                                     JVMCFG_SRC := $(JDK_TOPDIR)/src/java.base/macosx/conf/$(JVMCFG_ARCH)/jvm.cfg
                                   else
                                     JVMCFG_SRC := $(JDK_TOPDIR)/src/java.base/$(OPENJDK_TARGET_OS_TYPE)/conf/$(JVMCFG_ARCH)/jvm.cfg
                                  +  # Allow override by ALT_JVMCFG_SRC if it exists
                                  +  JVMCFG_SRC := $(if $(wildcard $(ALT_JVMCFG_SRC)),$(ALT_JVMCFG_SRC),$(JVMCFG_SRC)) 
                                   endif
                                   JVMCFG_DIR := $(LIB_DST_DIR)$(OPENJDK_TARGET_CPU_LIBDIR)
                                   JVMCFG := $(JVMCFG_DIR)/jvm.cfg
                                  @@ -168,9 +170,6 @@ POLICY_SRC_LIST :=
                                   
                                   ifeq ($(OPENJDK_TARGET_OS), windows)
                                     POLICY_SRC_LIST += $(JDK_TOPDIR)/src/java.base/$(OPENJDK_TARGET_OS)/conf/security/java.policy
                                  -  ifndef OPENJDK
                                  -    POLICY_SRC_LIST += $(JDK_TOPDIR)/src/closed/java.base/$(OPENJDK_TARGET_OS)/conf/security/java.policy
                                  -  endif
                                   endif
                                   
                                   POLICY_SRC_LIST += $(POLICY_SRC)
                                  diff --git a/jdk/make/Makefile b/jdk/make/copy/Copy-jdk.accessibility.gmk
                                  similarity index 54%
                                  rename from jdk/make/Makefile
                                  rename to jdk/make/copy/Copy-jdk.accessibility.gmk
                                  index ce3a3333405..4c089c16883 100644
                                  --- a/jdk/make/Makefile
                                  +++ b/jdk/make/copy/Copy-jdk.accessibility.gmk
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 2104, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # 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,25 @@
                                   # questions.
                                   #
                                   
                                  -# Locate this Makefile
                                  -ifeq ($(filter /%, $(lastword $(MAKEFILE_LIST))), )
                                  -  makefile_path := $(CURDIR)/$(lastword $(MAKEFILE_LIST))
                                  -else
                                  -  makefile_path := $(lastword $(MAKEFILE_LIST))
                                  -endif
                                  -repo_dir := $(patsubst %/make/Makefile, %, $(makefile_path))
                                  +include CopyCommon.gmk
                                   
                                  -# What is the name of this subsystem (langtools, corba, etc)?
                                  -subsystem_name := $(notdir $(repo_dir))
                                  +################################################################################
                                  +
                                  +ifeq ($(OPENJDK_TARGET_OS), windows)
                                  +  TARGETS += $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgeCallbacks.h \
                                  +      $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgeCalls.h \
                                  +      $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgePackages.h \
                                  +      $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgeCalls.c \
                                  +      $(CONF_DST_DIR)/accessibility.properties
                                  +
                                  +  $(INCLUDE_DST_OS_DIR)/bridge/%: \
                                  +      $(JDK_TOPDIR)/src/jdk.accessibility/windows/native/include/bridge/%
                                  +		$(install-file)
                                  +
                                  +  $(CONF_DST_DIR)/accessibility.properties: \
                                  +      $(JDK_TOPDIR)/src/jdk.accessibility/windows/conf/accessibility.properties
                                  +		$(install-file)
                                   
                                  -# Try to locate top-level makefile
                                  -top_level_makefile := $(repo_dir)/../Makefile
                                  -ifneq ($(wildcard $(top_level_makefile)), )
                                  -  $(info Will run $(subsystem_name) target on top-level Makefile)
                                  -  $(info WARNING: This is a non-recommended way of building!)
                                  -  $(info ===================================================)
                                  -else
                                  -  $(info Cannot locate top-level Makefile. Is this repo not checked out as part of a complete forest?)
                                  -  $(error Build from top-level Makefile instead)
                                   endif
                                   
                                  -all:
                                  -	@$(MAKE) -f $(top_level_makefile) $(subsystem_name)
                                  +################################################################################
                                  diff --git a/jdk/make/data/swingbeaninfo/SwingBeanInfo.template b/jdk/make/data/swingbeaninfo/SwingBeanInfo.template
                                  index 9c1a133f67f..e0c83c0e2cf 100644
                                  --- a/jdk/make/data/swingbeaninfo/SwingBeanInfo.template
                                  +++ b/jdk/make/data/swingbeaninfo/SwingBeanInfo.template
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                    *
                                    * This code is free software; you can redistribute it and/or modify it
                                  @@ -92,25 +92,38 @@ public class @(BeanClassName)BeanInfo extends javax.swing.SwingBeanInfoBase {
                                       /**
                                        * @return an icon of the specified kind for @(BeanClassName)
                                        */
                                  -    public Image getIcon(int kind) {
                                  +    public Image getIcon(final int kind) {
                                           Image i;
                                           switch (kind){
                                               case ICON_COLOR_32x32:
                                  -                i = loadImage("beaninfo/images/@(BeanClassName)Color32.gif");
                                  -                return ((i == null) ? loadImage("beaninfo/images/JComponentColor32.gif") : i);
                                  +                i = loadStandardImage("beaninfo/images/@(BeanClassName)Color32.gif");
                                  +                return ((i == null) ? loadStandardImage("beaninfo/images/JComponentColor32.gif") : i);
                                               case ICON_COLOR_16x16:
                                  -                i = loadImage("beaninfo/images/@(BeanClassName)Color16.gif");
                                  -                return ((i == null) ? loadImage("beaninfo/images/JComponentColor16.gif") : i);
                                  +                i = loadStandardImage("beaninfo/images/@(BeanClassName)Color16.gif");
                                  +                return ((i == null) ? loadStandardImage("beaninfo/images/JComponentColor16.gif") : i);
                                               case ICON_MONO_32x32:
                                  -                i = loadImage("beaninfo/images/@(BeanClassName)Mono32.gif");
                                  -                return ((i == null) ? loadImage("beaninfo/images/JComponentMono32.gif") : i);		  
                                  +                i = loadStandardImage("beaninfo/images/@(BeanClassName)Mono32.gif");
                                  +                return ((i == null) ? loadStandardImage("beaninfo/images/JComponentMono32.gif") : i);         
                                               case ICON_MONO_16x16:
                                  -                i = loadImage("beaninfo/images/@(BeanClassName)Mono16.gif");
                                  -                return ((i == null) ? loadImage("beaninfo/images/JComponentMono16.gif") : i);		  
                                  +                i = loadStandardImage("beaninfo/images/@(BeanClassName)Mono16.gif");
                                  +                return ((i == null) ? loadStandardImage("beaninfo/images/JComponentMono16.gif") : i);         
                                               default:
                                                   return super.getIcon(kind);
                                           }
                                       }
                                  +
                                  +    /**
                                  +     * This is a utility method to help in loading standard icon images.
                                  +     *
                                  +     * @param  resourceName A pathname relative to the directory holding the
                                  +     *         class file of the current class
                                  +     * @return an image object. May be null if the load failed.
                                  +     * @see java.beans.SimpleBeanInfo#loadImage(String)
                                  +     */
                                  +    private Image loadStandardImage(final String resourceName) {
                                  +        return java.security.AccessController.doPrivileged(
                                  +                (java.security.PrivilegedAction) () -> loadImage(resourceName));
                                  +    }
                                   }
                                   
                                   
                                  diff --git a/jdk/make/data/tzdata/VERSION b/jdk/make/data/tzdata/VERSION
                                  index 034114ae6ca..ebd4db73b0e 100644
                                  --- a/jdk/make/data/tzdata/VERSION
                                  +++ b/jdk/make/data/tzdata/VERSION
                                  @@ -21,4 +21,4 @@
                                   # or visit www.oracle.com if you need additional information or have any
                                   # questions.
                                   #
                                  -tzdata2015a
                                  +tzdata2015b
                                  diff --git a/jdk/make/data/tzdata/asia b/jdk/make/data/tzdata/asia
                                  index bff837c48d8..fa4f2461cbb 100644
                                  --- a/jdk/make/data/tzdata/asia
                                  +++ b/jdk/make/data/tzdata/asia
                                  @@ -1927,6 +1927,13 @@ Zone	Indian/Maldives	4:54:00 -	LMT	1880 # Male
                                   # was at the start of 2008-03-31 (the day of Steffen Thorsen's report);
                                   # this is almost surely wrong.
                                   
                                  +# From Ganbold Tsagaankhuu (2015-03-10):
                                  +# It seems like yesterday Mongolian Government meeting has concluded to use
                                  +# daylight saving time in Mongolia....  Starting at 2:00AM of last Saturday of
                                  +# March 2015, daylight saving time starts.  And 00:00AM of last Saturday of
                                  +# September daylight saving time ends.  Source:
                                  +# http://zasag.mn/news/view/8969
                                  +
                                   # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
                                   Rule	Mongol	1983	1984	-	Apr	1	0:00	1:00	S
                                   Rule	Mongol	1983	only	-	Oct	1	0:00	0	-
                                  @@ -1947,6 +1954,8 @@ Rule	Mongol	1984	1998	-	Sep	lastSun	0:00	0	-
                                   Rule	Mongol	2001	only	-	Apr	lastSat	2:00	1:00	S
                                   Rule	Mongol	2001	2006	-	Sep	lastSat	2:00	0	-
                                   Rule	Mongol	2002	2006	-	Mar	lastSat	2:00	1:00	S
                                  +Rule	Mongol	2015	max	-	Mar	lastSat	2:00	1:00	S
                                  +Rule	Mongol	2015	max	-	Sep	lastSat	0:00	0	-
                                   
                                   # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
                                   # Hovd, a.k.a. Chovd, Dund-Us, Dzhargalant, Khovd, Jirgalanta
                                  @@ -2365,13 +2374,19 @@ Zone	Asia/Karachi	4:28:12 -	LMT	1907
                                   # official source...:
                                   # http://www.palestinecabinet.gov.ps/ar/Views/ViewDetails.aspx?pid=1252
                                   
                                  -# From Paul Eggert (2013-09-24):
                                  -# For future dates, guess the last Thursday in March at 24:00 through
                                  -# the first Friday on or after September 21 at 00:00.  This is consistent with
                                  -# the predictions in today's editions of the following URLs,
                                  -# which are for Gaza and Hebron respectively:
                                  -# http://www.timeanddate.com/worldclock/timezone.html?n=702
                                  -# http://www.timeanddate.com/worldclock/timezone.html?n=2364
                                  +# From Steffen Thorsen (2015-03-03):
                                  +# Sources such as http://www.alquds.com/news/article/view/id/548257
                                  +# and http://www.raya.ps/ar/news/890705.html say Palestine areas will
                                  +# start DST on 2015-03-28 00:00 which is one day later than expected.
                                  +#
                                  +# From Paul Eggert (2015-03-03):
                                  +# http://www.timeanddate.com/time/change/west-bank/ramallah?year=2014
                                  +# says that the fall 2014 transition was Oct 23 at 24:00.
                                  +# For future dates, guess the last Friday in March at 24:00 through
                                  +# the first Friday on or after October 21 at 00:00.  This is consistent with
                                  +# the predictions in today's editions of the following URLs:
                                  +# http://www.timeanddate.com/time/change/gaza-strip/gaza
                                  +# http://www.timeanddate.com/time/change/west-bank/hebron
                                   
                                   # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
                                   Rule EgyptAsia	1957	only	-	May	10	0:00	1:00	S
                                  @@ -2397,9 +2412,11 @@ Rule Palestine	2011	only	-	Apr	 1	0:01	1:00	S
                                   Rule Palestine	2011	only	-	Aug	 1	0:00	0	-
                                   Rule Palestine	2011	only	-	Aug	30	0:00	1:00	S
                                   Rule Palestine	2011	only	-	Sep	30	0:00	0	-
                                  -Rule Palestine	2012	max	-	Mar	lastThu	24:00	1:00	S
                                  +Rule Palestine	2012	2014	-	Mar	lastThu	24:00	1:00	S
                                   Rule Palestine	2012	only	-	Sep	21	1:00	0	-
                                  -Rule Palestine	2013	max	-	Sep	Fri>=21	0:00	0	-
                                  +Rule Palestine	2013	only	-	Sep	Fri>=21	0:00	0	-
                                  +Rule Palestine	2014	max	-	Oct	Fri>=21	0:00	0	-
                                  +Rule Palestine	2015	max	-	Mar	lastFri	24:00	1:00	S
                                   
                                   # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
                                   Zone	Asia/Gaza	2:17:52	-	LMT	1900 Oct
                                  diff --git a/jdk/make/data/tzdata/australasia b/jdk/make/data/tzdata/australasia
                                  index f2a89e8ee37..ec9f392f88f 100644
                                  --- a/jdk/make/data/tzdata/australasia
                                  +++ b/jdk/make/data/tzdata/australasia
                                  @@ -396,6 +396,7 @@ Zone	Pacific/Guam	-14:21:00 -	LMT	1844 Dec 31
                                   			 9:39:00 -	LMT	1901        # Agana
                                   			10:00	-	GST	2000 Dec 23 # Guam
                                   			10:00	-	ChST	# Chamorro Standard Time
                                  +Link Pacific/Guam Pacific/Saipan # N Mariana Is
                                   
                                   # Kiribati
                                   # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
                                  @@ -411,12 +412,7 @@ Zone Pacific/Kiritimati	-10:29:20 -	LMT	1901
                                   			 14:00	-	LINT
                                   
                                   # N Mariana Is
                                  -# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
                                  -Zone Pacific/Saipan	-14:17:00 -	LMT	1844 Dec 31
                                  -			 9:43:00 -	LMT	1901
                                  -			 9:00	-	MPT	1969 Oct    # N Mariana Is Time
                                  -			10:00	-	MPT	2000 Dec 23
                                  -			10:00	-	ChST	# Chamorro Standard Time
                                  +# See Pacific/Guam.
                                   
                                   # Marshall Is
                                   # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
                                  @@ -586,6 +582,7 @@ Zone Pacific/Pago_Pago	 12:37:12 -	LMT	1879 Jul  5
                                   			-11:00	-	NST	1967 Apr    # N=Nome
                                   			-11:00	-	BST	1983 Nov 30 # B=Bering
                                   			-11:00	-	SST	            # S=Samoa
                                  +Link Pacific/Pago_Pago Pacific/Midway # in US minor outlying islands
                                   
                                   # Samoa (formerly and also known as Western Samoa)
                                   
                                  @@ -767,23 +764,7 @@ Zone Pacific/Funafuti	11:56:52 -	LMT	1901
                                   # uninhabited
                                   
                                   # Midway
                                  -#
                                  -# From Mark Brader (2005-01-23):
                                  -# [Fallacies and Fantasies of Air Transport History, by R.E.G. Davies,
                                  -# published 1994 by Paladwr Press, McLean, VA, USA; ISBN 0-9626483-5-3]
                                  -# reproduced a Pan American Airways timetable from 1936, for their weekly
                                  -# "Orient Express" flights between San Francisco and Manila, and connecting
                                  -# flights to Chicago and the US East Coast.  As it uses some time zone
                                  -# designations that I've never seen before:....
                                  -# Fri. 6:30A Lv. HONOLOLU (Pearl Harbor), H.I.   H.L.T. Ar. 5:30P Sun.
                                  -#  "   3:00P Ar. MIDWAY ISLAND . . . . . . . . . M.L.T. Lv. 6:00A  "
                                  -#
                                  -Zone Pacific/Midway	-11:49:28 -	LMT	1901
                                  -			-11:00	-	NST	1956 Jun  3
                                  -			-11:00	1:00	NDT	1956 Sep  2
                                  -			-11:00	-	NST	1967 Apr    # N=Nome
                                  -			-11:00	-	BST	1983 Nov 30 # B=Bering
                                  -			-11:00	-	SST	            # S=Samoa
                                  +# See Pacific/Pago_Pago.
                                   
                                   # Palmyra
                                   # uninhabited since World War II; was probably like Pacific/Kiritimati
                                  diff --git a/jdk/make/data/tzdata/europe b/jdk/make/data/tzdata/europe
                                  index 89790f06c17..008268ac763 100644
                                  --- a/jdk/make/data/tzdata/europe
                                  +++ b/jdk/make/data/tzdata/europe
                                  @@ -2423,7 +2423,7 @@ Zone Europe/Volgograd	 2:57:40 -	LMT	1920 Jan  3
                                   			 4:00	Russia	VOL%sT	1989 Mar 26  2:00s # Volgograd T
                                   			 3:00	Russia	VOL%sT	1991 Mar 31  2:00s
                                   			 4:00	-	VOLT	1992 Mar 29  2:00s
                                  -			 3:00	Russia	MSK	2011 Mar 27  2:00s
                                  +			 3:00	Russia	MSK/MSD	2011 Mar 27  2:00s
                                   			 4:00	-	MSK	2014 Oct 26  2:00s
                                   			 3:00	-	MSK
                                   
                                  diff --git a/jdk/make/data/tzdata/northamerica b/jdk/make/data/tzdata/northamerica
                                  index 5943cfeec4b..442a50eef0f 100644
                                  --- a/jdk/make/data/tzdata/northamerica
                                  +++ b/jdk/make/data/tzdata/northamerica
                                  @@ -2335,8 +2335,24 @@ Zone America/Dawson	-9:17:40 -	LMT	1900 Aug 20
                                   # "...the new time zone will come into effect at two o'clock on the first Sunday
                                   # of February, when we will have to advance the clock one hour from its current
                                   # time..."
                                  -#
                                   # Also, the new zone will not use DST.
                                  +#
                                  +# From Carlos Raúl Perasso (2015-02-02):
                                  +# The decree that modifies the Mexican Hour System Law has finally
                                  +# been published at the Diario Oficial de la Federación
                                  +# http://www.dof.gob.mx/nota_detalle.php?codigo=5380123&fecha=31/01/2015
                                  +# It establishes 5 zones for Mexico:
                                  +# 1- Zona Centro (Central Zone): Corresponds to longitude 90 W,
                                  +#    includes most of Mexico, excluding what's mentioned below.
                                  +# 2- Zona Pacífico (Pacific Zone): Longitude 105 W, includes the
                                  +#    states of Baja California Sur; Chihuahua; Nayarit (excluding Bahía
                                  +#    de Banderas which lies in Central Zone); Sinaloa and Sonora.
                                  +# 3- Zona Noroeste (Northwest Zone): Longitude 120 W, includes the
                                  +#    state of Baja California.
                                  +# 4- Zona Sureste (Southeast Zone): Longitude 75 W, includes the state
                                  +#    of Quintana Roo.
                                  +# 5- The islands, reefs and keys shall take their timezone from the
                                  +#    longitude they are located at.
                                   
                                   # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
                                   Rule	Mexico	1939	only	-	Feb	5	0:00	1:00	D
                                  @@ -2531,13 +2547,8 @@ Zone America/Santa_Isabel	-7:39:28 -	LMT	1922 Jan  1  0:20:32
                                   ###############################################################################
                                   
                                   # Anguilla
                                  -# See America/Port_of_Spain.
                                  -
                                   # Antigua and Barbuda
                                  -# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
                                  -Zone	America/Antigua	-4:07:12 -	LMT	1912 Mar 2
                                  -			-5:00	-	EST	1951
                                  -			-4:00	-	AST
                                  +# See America/Port_of_Spain.
                                   
                                   # Bahamas
                                   #
                                  @@ -2604,10 +2615,7 @@ Zone Atlantic/Bermuda	-4:19:18 -	LMT	1930 Jan  1  2:00 # Hamilton
                                   			-4:00	US	A%sT
                                   
                                   # Cayman Is
                                  -# Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
                                  -Zone	America/Cayman	-5:25:32 -	LMT	1890     # Georgetown
                                  -			-5:07:11 -	KMT	1912 Feb # Kingston Mean Time
                                  -			-5:00	-	EST
                                  +# See America/Panama.
                                   
                                   # Costa Rica
                                   
                                  @@ -3130,6 +3138,7 @@ Zone	America/Managua	-5:45:08 -	LMT	1890
                                   Zone	America/Panama	-5:18:08 -	LMT	1890
                                   			-5:19:36 -	CMT	1908 Apr 22 # Colón Mean Time
                                   			-5:00	-	EST
                                  +Link America/Panama America/Cayman
                                   
                                   # Puerto Rico
                                   # There are too many San Juans elsewhere, so we'll use 'Puerto_Rico'.
                                  diff --git a/jdk/make/data/tzdata/southamerica b/jdk/make/data/tzdata/southamerica
                                  index 02cf12113a0..238ae3dc569 100644
                                  --- a/jdk/make/data/tzdata/southamerica
                                  +++ b/jdk/make/data/tzdata/southamerica
                                  @@ -1229,10 +1229,13 @@ Zone America/Rio_Branco	-4:31:12 -	LMT	1914
                                   # DST Start: first Saturday of September 2014 (Sun 07 Sep 2014 04:00 UTC)
                                   # http://www.diariooficial.interior.gob.cl//media/2014/02/19/do-20140219.pdf
                                   
                                  -# From Juan Correa (2015-01-28):
                                  -# ... today the Ministry of Energy announced that Chile will drop DST, will keep
                                  -# "summer time" (UTC -3 / UTC -5) all year round....
                                  -# http://www.minenergia.cl/ministerio/noticias/generales/ministerio-de-energia-anuncia.html
                                  +# From Eduardo Romero Urra (2015-03-03):
                                  +# Today has been published officially that Chile will use the DST time
                                  +# permanently until March 25 of 2017
                                  +# http://www.diariooficial.interior.gob.cl/media/2015/03/03/1-large.jpg
                                  +#
                                  +# From Paul Eggert (2015-03-03):
                                  +# For now, assume that the extension will persist indefinitely.
                                   
                                   # NOTE: ChileAQ rules for Antarctic bases are stored separately in the
                                   # 'antarctica' file.
                                  @@ -1291,7 +1294,7 @@ Zone America/Santiago	-4:42:46 -	LMT	1890
                                   			-3:00	-	CLT
                                   Zone Pacific/Easter	-7:17:44 -	LMT	1890
                                   			-7:17:28 -	EMT	1932 Sep    # Easter Mean Time
                                  -			-7:00	Chile	EAS%sT	1982 Mar 13 3:00u # Easter Time
                                  +			-7:00	Chile	EAS%sT	1982 Mar 14 3:00u # Easter Time
                                   			-6:00	Chile	EAS%sT	2015 Apr 26 3:00u
                                   			-5:00	-	EAST
                                   #
                                  @@ -1626,6 +1629,7 @@ Zone America/Port_of_Spain -4:06:04 -	LMT	1912 Mar 2
                                   
                                   # These all agree with Trinidad and Tobago since 1970.
                                   Link America/Port_of_Spain America/Anguilla
                                  +Link America/Port_of_Spain America/Antigua
                                   Link America/Port_of_Spain America/Dominica
                                   Link America/Port_of_Spain America/Grenada
                                   Link America/Port_of_Spain America/Guadeloupe
                                  diff --git a/jdk/make/gensrc/GensrcMisc.gmk b/jdk/make/gensrc/GensrcMisc.gmk
                                  index c0489f3a97d..7762a284952 100644
                                  --- a/jdk/make/gensrc/GensrcMisc.gmk
                                  +++ b/jdk/make/gensrc/GensrcMisc.gmk
                                  @@ -63,9 +63,7 @@ SOR_COPYRIGHT_YEARS = $(shell $(CAT) $(GENSRC_SOR_SRC)/$(GENSRC_SOR_SRC_FILE) |
                                   $(eval $(call SetupNativeCompilation,BUILD_GENSRC_SOR_EXE, \
                                       SRC := $(GENSRC_SOR_SRC), \
                                       INCLUDE_FILES := $(GENSRC_SOR_SRC_FILE), \
                                  -    LANG := C, \
                                  -    CC := $(BUILD_CC), \
                                  -    LDEXE := $(BUILD_LD), \
                                  +    TOOLCHAIN := TOOLCHAIN_BUILD, \
                                       OBJECT_DIR := $(GENSRC_SOR_BIN), \
                                       OUTPUT_DIR := $(GENSRC_SOR_BIN), \
                                       PROGRAM := genSocketOptionRegistry))
                                  @@ -101,9 +99,7 @@ ifneq ($(OPENJDK_TARGET_OS), windows)
                                     $(eval $(call SetupNativeCompilation,BUILD_GENSRC_UC_EXE, \
                                         SRC := $(GENSRC_UC_SRC), \
                                         INCLUDE_FILES := $(GENSRC_UC_SRC_FILE), \
                                  -      LANG := C, \
                                  -      CC := $(BUILD_CC), \
                                  -      LDEXE := $(BUILD_CC), \
                                  +      TOOLCHAIN := TOOLCHAIN_BUILD, \
                                         CFLAGS := $(filter -D%, $(CFLAGS_JDKEXE)), \
                                         OBJECT_DIR := $(GENSRC_UC_BIN), \
                                         OUTPUT_DIR := $(GENSRC_UC_BIN), \
                                  @@ -142,9 +138,7 @@ ifeq ($(OPENJDK_TARGET_OS), solaris)
                                     $(eval $(call SetupNativeCompilation,BUILD_GENSRC_SOL_EXE, \
                                         SRC := $(GENSRC_SOL_SRC), \
                                         INCLUDE_FILES := $(GENSRC_SOL_SRC_FILE), \
                                  -      LANG := C, \
                                  -      CC := $(BUILD_CC), \
                                  -      LDEXE := $(BUILD_CC), \
                                  +      TOOLCHAIN := TOOLCHAIN_BUILD, \
                                         OBJECT_DIR := $(GENSRC_SOL_BIN), \
                                         OUTPUT_DIR := $(GENSRC_SOL_BIN), \
                                         PROGRAM := genSolarisConstants))
                                  diff --git a/jdk/make/launcher/Launcher-java.base.gmk b/jdk/make/launcher/Launcher-java.base.gmk
                                  index d117ad3b2ca..b0defc603f8 100644
                                  --- a/jdk/make/launcher/Launcher-java.base.gmk
                                  +++ b/jdk/make/launcher/Launcher-java.base.gmk
                                  @@ -103,7 +103,6 @@ ifneq ($(BUILD_JEXEC_SRC), )
                                     $(eval $(call SetupNativeCompilation,BUILD_JEXEC, \
                                         SRC := $(BUILD_JEXEC_SRC), \
                                         INCLUDE_FILES := jexec.c, \
                                  -      LANG := C, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKEXE) \
                                             $(BUILD_JEXEC_INC), \
                                  @@ -144,7 +143,6 @@ ifeq ($(BUILD_JSPAWNHELPER), 1)
                                     $(eval $(call SetupNativeCompilation,BUILD_JSPAWNHELPER, \
                                         SRC := $(BUILD_JSPAWNHELPER_SRC), \
                                         INCLUDE_FILES := jspawnhelper.c, \
                                  -      LANG := C, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKEXE) $(JSPAWNHELPER_CFLAGS), \
                                         LDFLAGS := $(LDFLAGS_JDKEXE) $(LINK_JSPAWNHELPER_FLAGS), \
                                  diff --git a/jdk/make/launcher/Launcher-jdk.accessibility.gmk b/jdk/make/launcher/Launcher-jdk.accessibility.gmk
                                  new file mode 100644
                                  index 00000000000..dc34a3fee7b
                                  --- /dev/null
                                  +++ b/jdk/make/launcher/Launcher-jdk.accessibility.gmk
                                  @@ -0,0 +1,61 @@
                                  +#
                                  +# Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
                                  +# 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 LauncherCommon.gmk
                                  +
                                  +################################################################################
                                  +# jabswitch
                                  +
                                  +ifeq ($(OPENJDK_TARGET_OS), windows)
                                  +
                                  +  JABSWITCH_SRC := $(JDK_TOPDIR)/src/jdk.accessibility/windows/native/jabswitch
                                  +  ACCESSBRIDGE_SRC := $(JDK_TOPDIR)/src/jdk.accessibility/windows/native/common
                                  +
                                  +  $(eval $(call SetupNativeCompilation,BUILD_JABSWITCH, \
                                  +      SRC := $(JABSWITCH_SRC), \
                                  +      INCLUDE_FILES := jabswitch.cpp, \
                                  +      CFLAGS := $(filter-out -Zc:wchar_t-, $(CFLAGS_JDKEXE)) -Zc:wchar_t \
                                  +          -analyze- -Od -Gd -D_WINDOWS \
                                  +          -D_UNICODE -DUNICODE -RTC1 -EHsc, \
                                  +      DISABLED_WARNINGS_microsoft := 4267, \
                                  +      LDFLAGS := $(LDFLAGS_JDKEXE) \
                                  +          Advapi32.lib Version.lib User32.lib, \
                                  +      OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/native/jdk.accessibility/jabswitch, \
                                  +      OUTPUT_DIR := $(SUPPORT_OUTPUTDIR)/modules_cmds/jdk.accessibility, \
                                  +      PROGRAM := jabswitch, \
                                  +      DEBUG_SYMBOLS := true, \
                                  +      VERSIONINFO_RESOURCE := $(ACCESSBRIDGE_SRC)/AccessBridgeStatusWindow.RC, \
                                  +      RC_FLAGS := $(RC_FLAGS) \
                                  +          -D "JDK_FNAME=jabswitch.exe" \
                                  +          -D "JDK_INTERNAL_NAME=jabswitch" \
                                  +          -D "JDK_FTYPE=0x01L", \
                                  +      MANIFEST := $(JABSWITCH_SRC)/jabswitch.manifest, \
                                  +      MANIFEST_VERSION := $(JDK_VERSION_FOR_MANIFEST), \
                                  +  ))
                                  +
                                  +  TARGETS += $(BUILD_JABSWITCH)
                                  +endif
                                  +
                                  +################################################################################
                                  diff --git a/jdk/make/launcher/Launcher-jdk.pack200.gmk b/jdk/make/launcher/Launcher-jdk.pack200.gmk
                                  index 6ee00f7ccd0..391272a76fb 100644
                                  --- a/jdk/make/launcher/Launcher-jdk.pack200.gmk
                                  +++ b/jdk/make/launcher/Launcher-jdk.pack200.gmk
                                  @@ -56,32 +56,34 @@ else
                                   
                                   endif
                                   
                                  -UNPACKEXE_LANG := C
                                   ifeq ($(OPENJDK_TARGET_OS), solaris)
                                  -  UNPACKEXE_LANG := C++
                                  +  UNPACKEXE_TOOLCHAIN := TOOLCHAIN_LINK_CXX
                                   endif
                                   
                                  +UNPACK_MAPFILE_DIR := $(JDK_TOPDIR)/make/mapfiles/libunpack
                                  +UNPACK_MAPFILE_PLATFORM_FILE := \
                                  +    $(UNPACK_MAPFILE_DIR)/mapfile-vers-unpack200-$(OPENJDK_TARGET_OS)-$(OPENJDK_TARGET_CPU_ARCH)
                                  +
                                   # The linker on older SuSE distros (e.g. on SLES 10) complains with:
                                   # "Invalid version tag `SUNWprivate_1.1'. Only anonymous version tag is allowed in executable."
                                   # if feeded with a version script which contains named tags.
                                   ifeq ($(USING_BROKEN_SUSE_LD), yes)
                                  -  UNPACK_MAPFILE = $(JDK_TOPDIR)/make/mapfiles/libunpack/mapfile-vers-unpack200.anonymous
                                  +  UNPACK_MAPFILE := $(UNPACK_MAPFILE_DIR)/mapfile-vers-unpack200.anonymous
                                  +else ifneq ($(wildcard $(UNPACK_MAPFILE_PLATFORM_FILE)), )
                                  +  UNPACK_MAPFILE := $(UNPACK_MAPFILE_PLATFORM_FILE)
                                   else
                                  -  UNPACK_MAPFILE = $(JDK_TOPDIR)/make/mapfiles/libunpack/mapfile-vers-unpack200
                                  +  UNPACK_MAPFILE := $(UNPACK_MAPFILE_DIR)/mapfile-vers-unpack200
                                   endif
                                   
                                   $(eval $(call SetupNativeCompilation,BUILD_UNPACKEXE, \
                                       SRC := $(UNPACKEXE_SRC), \
                                  -    LANG := $(UNPACKEXE_LANG), \
                                  +    TOOLCHAIN := $(UNPACKEXE_TOOLCHAIN), \
                                       OPTIMIZATION := LOW, \
                                       CFLAGS := $(UNPACKEXE_CFLAGS) $(CXXFLAGS_JDKEXE) -DFULL, \
                                       CFLAGS_release := -DPRODUCT, \
                                       CFLAGS_linux := -fPIC, \
                                       CFLAGS_solaris := -KPIC, \
                                       CFLAGS_macosx := -fPIC, \
                                  -    DISABLED_WARNINGS_gcc := sign-compare unused-result format-nonliteral \
                                  -        format-security parentheses, \
                                  -    DISABLED_WARNINGS_microsoft := 4267 4018, \
                                       MAPFILE := $(UNPACK_MAPFILE),\
                                       LDFLAGS := $(UNPACKEXE_ZIPOBJS) \
                                           $(LDFLAGS_JDKEXE) $(LDFLAGS_CXX_JDK) \
                                  @@ -99,7 +101,9 @@ $(eval $(call SetupNativeCompilation,BUILD_UNPACKEXE, \
                                           -D "JDK_INTERNAL_NAME=unpack200" \
                                           -D "JDK_FTYPE=0x1L", \
                                       DEBUG_SYMBOLS := true, \
                                  -    MANIFEST := $(JDK_TOPDIR)/src/jdk.pack200/windows/native/unpack200/unpack200_proto.exe.manifest))
                                  +    MANIFEST := $(JDK_TOPDIR)/src/jdk.pack200/windows/native/unpack200/unpack200_proto.exe.manifest, \
                                  +    MANIFEST_VERSION := $(JDK_VERSION_FOR_MANIFEST), \
                                  +))
                                   
                                   ifneq ($(USE_EXTERNAL_LIBZ), true)
                                   
                                  diff --git a/jdk/make/launcher/LauncherCommon.gmk b/jdk/make/launcher/LauncherCommon.gmk
                                  index 09ffcffdb34..1e504f5231a 100644
                                  --- a/jdk/make/launcher/LauncherCommon.gmk
                                  +++ b/jdk/make/launcher/LauncherCommon.gmk
                                  @@ -1,5 +1,5 @@
                                   #
                                  -# Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
                                  +# Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                   # This code is free software; you can redistribute it and/or modify it
                                  @@ -161,7 +161,6 @@ define SetupLauncher
                                     $(call SetupNativeCompilation,BUILD_LAUNCHER_$1, \
                                         SRC := $(LAUNCHER_SRC), \
                                         INCLUDE_FILES := main.c, \
                                  -      LANG := C, \
                                         OPTIMIZATION := $$($1_OPTIMIZATION_ARG), \
                                         CFLAGS := $$($1_CFLAGS) \
                                             $(LAUNCHER_CFLAGS) \
                                  @@ -199,7 +198,9 @@ define SetupLauncher
                                             -D "JDK_FTYPE=0x1L" \
                                             $7, \
                                         MANIFEST := $(JAVA_MANIFEST), \
                                  -      CODESIGN := $$($1_CODESIGN))
                                  +      MANIFEST_VERSION := $(JDK_VERSION_FOR_MANIFEST), \
                                  +      CODESIGN := $$($1_CODESIGN), \
                                  +  )
                                   
                                     TARGETS += $$(BUILD_LAUNCHER_$1)
                                   
                                  diff --git a/jdk/make/lib/Awt2dLibraries.gmk b/jdk/make/lib/Awt2dLibraries.gmk
                                  index 549068675fd..254f446a000 100644
                                  --- a/jdk/make/lib/Awt2dLibraries.gmk
                                  +++ b/jdk/make/lib/Awt2dLibraries.gmk
                                  @@ -51,7 +51,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBMLIB_IMAGE, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(BUILD_LIBMLIB_SRC), \
                                       EXCLUDE_FILES := mlib_c_ImageBlendTable.c, \
                                  -    LANG := C, \
                                       OPTIMIZATION := HIGHEST, \
                                       CFLAGS := $(CFLAGS_JDKLIB) \
                                           $(BUILD_LIBMLIB_CFLAGS), \
                                  @@ -124,7 +123,6 @@ ifeq ($(OPENJDK_TARGET_OS)-$(OPENJDK_TARGET_CPU_ARCH), solaris-sparc)
                                         LIBRARY := mlib_image_v, \
                                         OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                         SRC := $(LIBMLIB_IMAGE_V_SRC), \
                                  -      LANG := C, \
                                         EXCLUDE_FILES := $(BUILD_LIBMLIB_IMAGE_V_EXFILES), \
                                         OPTIMIZATION := HIGHEST, \
                                         CFLAGS := -xarch=sparcvis \
                                  @@ -204,8 +202,6 @@ ifneq ($(OPENJDK_TARGET_OS), solaris)
                                     LIBAWT_CFLAGS += -DMLIB_NO_LIBSUNMATH
                                   endif
                                   
                                  -LIBAWT_LANG := C
                                  -
                                   ifeq ($(OPENJDK_TARGET_OS), windows)
                                     LIBAWT_DIRS += $(JDK_TOPDIR)/src/java.desktop/share/native/common/font \
                                         $(JDK_TOPDIR)/src/java.desktop/share/native/common/java2d/opengl \
                                  @@ -222,7 +218,6 @@ ifeq ($(OPENJDK_TARGET_OS), windows)
                                         awt/image/cvutils/img_colors.c \
                                         #
                                   
                                  -  LIBAWT_LANG := C++
                                     LIBAWT_CFLAGS += -EHsc -DUNICODE -D_UNICODE
                                     ifeq ($(OPENJDK_TARGET_CPU_BITS), 64)
                                       LIBAWT_CFLAGS += -DMLIB_OS64BIT
                                  @@ -236,10 +231,6 @@ ifeq ($(OPENJDK_TARGET_OS), windows)
                                     LIBAWT_VERSIONINFO_RESOURCE := $(JDK_TOPDIR)/src/java.desktop/windows/native/libawt/windows/awt.rc
                                   endif
                                   
                                  -ifeq ($(MILESTONE), internal)
                                  -  LIBAWT_CFLAGS += -DINTERNAL_BUILD
                                  -endif
                                  -
                                   LIBAWT_MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libawt/mapfile-vers
                                   ifeq ($(OPENJDK_TARGET_OS), linux)
                                     LIBAWT_MAPFILE :=
                                  @@ -251,7 +242,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBAWT, \
                                       SRC := $(LIBAWT_DIRS), \
                                       EXCLUDES := $(LIBAWT_EXCLUDES), \
                                       EXCLUDE_FILES := $(LIBAWT_EXFILES), \
                                  -    LANG := $(LIBAWT_LANG), \
                                       OPTIMIZATION := LOW, \
                                       CFLAGS := $(CFLAGS_JDKLIB) $(LIBAWT_CFLAGS), \
                                       DISABLED_WARNINGS_gcc := sign-compare unused-result maybe-uninitialized \
                                  @@ -347,10 +337,6 @@ ifeq ($(findstring $(OPENJDK_TARGET_OS),windows macosx),)
                                         endif
                                       endif
                                   
                                  -    ifeq ($(MILESTONE), internal)
                                  -      LIBAWT_XAWT_CFLAGS += -DINTERNAL_BUILD
                                  -    endif
                                  -
                                       LIBAWT_XAWT_LDFLAGS_SUFFIX := $(LIBM) -lawt -lXext -lX11 -lXrender $(LIBDL) -lXtst -lXi -ljava -ljvm -lc
                                   
                                       ifeq ($(OPENJDK_TARGET_OS), linux)
                                  @@ -363,7 +349,6 @@ ifeq ($(findstring $(OPENJDK_TARGET_OS),windows macosx),)
                                           OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                           SRC := $(LIBAWT_XAWT_DIRS), \
                                           EXCLUDES := $(LIBAWT_XAWT_EXCLUDES), \
                                  -        LANG := C, \
                                           OPTIMIZATION := LOW, \
                                           CFLAGS := $(CFLAGS_JDKLIB) $(LIBAWT_XAWT_CFLAGS) \
                                               $(X_CFLAGS), \
                                  @@ -421,7 +406,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBLCMS, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(LIBLCMS_SRC), \
                                       INCLUDE_FILES := $(BUILD_LIBLCMS_INCLUDE_FILES), \
                                  -    LANG := C, \
                                       OPTIMIZATION := HIGHEST, \
                                       CFLAGS := $(filter-out -xc99=%none, $(CFLAGS_JDKLIB)) \
                                           $(SHARED_LIBRARY_FLAGS) $(LIBLCMS_CPPFLAGS) \
                                  @@ -504,7 +488,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJAVAJPEG, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(LIBJAVAJPEG_SRC), \
                                       INCLUDE_FILES := $(BUILD_LIBJAVAJPEG_INCLUDE_FILES), \
                                  -    LANG := C, \
                                       OPTIMIZATION := HIGHEST, \
                                       CFLAGS := $(CFLAGS_JDKLIB) $(addprefix -I, $(LIBJAVAJPEG_SRC)) \
                                           $(LIBJAVA_HEADER_FLAGS) \
                                  @@ -572,7 +555,6 @@ ifeq ($(BUILD_HEADLESS), true)
                                           OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                           SRC := $(LIBAWT_HEADLESS_DIRS), \
                                           EXCLUDES := $(LIBAWT_HEADLESS_EXCLUDES), \
                                  -        LANG := C, \
                                           OPTIMIZATION := LOW, \
                                           CFLAGS := $(CFLAGS_JDKLIB) \
                                               -DHEADLESS=true \
                                  @@ -659,7 +641,7 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBFONTMANAGER, \
                                       SRC := $(LIBFONTMANAGER_SRC), \
                                       EXCLUDE_FILES := $(LIBFONTMANAGER_EXCLUDE_FILES) \
                                           AccelGlyphCache.c, \
                                  -    LANG := C++, \
                                  +    TOOLCHAIN := TOOLCHAIN_LINK_CXX, \
                                       CFLAGS := $(CFLAGS_JDKLIB) $(LIBFONTMANAGER_CFLAGS), \
                                       CXXFLAGS := $(CXXFLAGS_JDKLIB) $(LIBFONTMANAGER_CFLAGS), \
                                       OPTIMIZATION := $(LIBFONTMANAGER_OPTIMIZATION), \
                                  @@ -720,7 +702,6 @@ ifeq ($(OPENJDK_TARGET_OS), windows)
                                         OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                         SRC := $(LIBJAWT_SRC), \
                                         INCLUDE_FILES := $(LIBJAWT_INCLUDE_FILES), \
                                  -      LANG := C++, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CXXFLAGS_JDKLIB) \
                                             -EHsc -DUNICODE -D_UNICODE \
                                  @@ -779,7 +760,6 @@ else # OPENJDK_TARGET_OS not windows
                                         OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                         SRC := $(LIBJAWT_SRC), \
                                         INCLUDE_FILES := $(JAWT_FILES), \
                                  -      LANG := C, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKLIB) \
                                             $(LIBJAWT_CFLAGS), \
                                  @@ -897,7 +877,6 @@ ifndef BUILD_HEADLESS_ONLY
                                         SRC := $(LIBSPLASHSCREEN_DIRS), \
                                         EXCLUDE_FILES := imageioJPEG.c jpegdecoder.c pngtest.c, \
                                         EXCLUDES := $(LIBSPLASHSCREEN_EXCLUDES), \
                                  -      LANG := C, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(LIBSPLASHSCREEN_CFLAGS) $(CFLAGS_JDKLIB) \
                                                   $(GIFLIB_CFLAGS) $(LIBJPEG_CFLAGS) $(PNG_CFLAGS), \
                                  @@ -966,7 +945,6 @@ ifeq ($(OPENJDK_TARGET_OS), macosx)
                                         LIBRARY := awt_lwawt, \
                                         OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                         SRC := $(LIBAWT_LWAWT_DIRS), \
                                  -      LANG := C, \
                                         INCLUDE_FILES := $(LIBAWT_LWAWT_FILES), \
                                         EXCLUDE_FILES := $(LIBAWT_LWAWT_EXFILES), \
                                         EXCLUDES := $(LIBAWT_LWAWT_EXCLUDES), \
                                  @@ -1016,7 +994,6 @@ ifeq ($(OPENJDK_TARGET_OS), macosx)
                                         LIBRARY := osxui, \
                                         OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                         SRC := $(JDK_TOPDIR)/src/java.desktop/macosx/native/libosxui, \
                                  -      LANG := C, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKLIB) \
                                             -I$(JDK_TOPDIR)/src/java.desktop/macosx/native/libosxui \
                                  diff --git a/jdk/make/lib/CoreLibraries.gmk b/jdk/make/lib/CoreLibraries.gmk
                                  index 678af20a830..ed6d75ce2be 100644
                                  --- a/jdk/make/lib/CoreLibraries.gmk
                                  +++ b/jdk/make/lib/CoreLibraries.gmk
                                  @@ -43,7 +43,6 @@ ifneq ($(OPENJDK_TARGET_OS), macosx)
                                         STATIC_LIBRARY := fdlibm, \
                                         OUTPUT_DIR := $(SUPPORT_OUTPUTDIR)/native/$(MODULE), \
                                         SRC := $(LIBFDLIBM_SRC), \
                                  -      LANG := C, \
                                         OPTIMIZATION := $(BUILD_LIBFDLIBM_OPTIMIZATION), \
                                         CFLAGS := $(CFLAGS_JDKLIB) $(LIBFDLIBM_CFLAGS), \
                                         CFLAGS_windows_debug := -DLOGGING, \
                                  @@ -62,7 +61,6 @@ else
                                         LIBRARY := fdlibm, \
                                         OUTPUT_DIR := $(SUPPORT_OUTPUTDIR)/native/$(MODULE)/libfdlibm, \
                                         SRC := $(LIBFDLIBM_SRC), \
                                  -      LANG := C, \
                                         CFLAGS := $(CFLAGS_JDKLIB) $(LIBFDLIBM_CFLAGS), \
                                         LDFLAGS := -nostdlib -r -arch x86_64, \
                                         OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/native/$(MODULE)/libfdlibm, \
                                  @@ -93,7 +91,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBVERIFY, \
                                       LIBRARY := verify, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(JDK_TOPDIR)/src/java.base/share/native/libverify, \
                                  -    LANG := C, \
                                       OPTIMIZATION := $(LIBVERIFY_OPTIMIZATION), \
                                       CFLAGS := $(CFLAGS_JDKLIB), \
                                       DISABLED_WARNINGS_microsoft := 4244 4267, \
                                  @@ -146,7 +143,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJAVA, \
                                       LIBRARY := java, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(LIBJAVA_SRC_DIRS), \
                                  -    LANG := C, \
                                       OPTIMIZATION := HIGH, \
                                       CFLAGS := $(CFLAGS_JDKLIB) \
                                           $(LIBJAVA_CFLAGS), \
                                  @@ -206,7 +202,6 @@ endif
                                   $(eval $(call SetupNativeCompilation,BUILD_LIBZIP, \
                                       LIBRARY := zip, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                  -    LANG := C, \
                                       OPTIMIZATION := LOW, \
                                       SRC := $(JDK_TOPDIR)/src/java.base/share/native/libzip, \
                                       EXCLUDES := $(LIBZIP_EXCLUDES), \
                                  @@ -269,7 +264,7 @@ endif
                                   LIBJLI_EXCLUDE_FILES += $(notdir $(LIBJLI_EXCLUDE_ERGO))
                                   
                                   ifeq ($(OPENJDK_TARGET_OS), macosx)
                                  -  LIBJLI_EXCLUDE_FILES += java_md_solinux.c ergo.c
                                  +  LIBJLI_EXCLUDE_FILES += java_md_solinux.c ergo.c ergo_i586.c
                                   
                                     BUILD_LIBJLI_java_md_macosx.c_CFLAGS := -x objective-c
                                     BUILD_LIBJLI_STATIC_java_md_macosx.c_CFLAGS := -x objective-c
                                  @@ -314,15 +309,9 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJLI, \
                                       SRC := $(LIBJLI_SRC_DIRS), \
                                       EXCLUDE_FILES := $(LIBJLI_EXCLUDE_FILES), \
                                       EXTRA_FILES := $(LIBJLI_EXTRA_FILES), \
                                  -    LANG := C, \
                                       OPTIMIZATION := HIGH, \
                                       CFLAGS := $(LIBJLI_CFLAGS), \
                                  -    DISABLED_WARNINGS_gcc := pointer-to-int-cast sign-compare format-nonliteral \
                                  -        parentheses, \
                                  -    DISABLED_WARNINGS_clang := implicit-function-declaration parentheses \
                                  -        int-conversion, \
                                  -    DISABLED_WARNINGS_solstudio := E_ASM_DISABLES_OPTIMIZATION E_NEWLINE_NOT_LAST, \
                                  -    DISABLED_WARNINGS_microsoft := 4244 4047 4267, \
                                  +    DISABLED_WARNINGS_solstudio := E_ASM_DISABLES_OPTIMIZATION, \
                                       MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libjli/mapfile-vers, \
                                       LDFLAGS := $(LDFLAGS_JDKLIB) \
                                           $(call SET_SHARED_LIBRARY_ORIGIN), \
                                  @@ -368,10 +357,8 @@ ifeq ($(OPENJDK_TARGET_OS), windows)
                                         SRC := $(LIBJLI_SRC_DIRS), \
                                         EXCLUDE_FILES := $(LIBJLI_EXCLUDE_FILES), \
                                         EXTRA_FILES := $(LIBJLI_EXTRA_FILES), \
                                  -      LANG := C, \
                                         OPTIMIZATION := HIGH, \
                                         CFLAGS := $(STATIC_LIBRARY_FLAGS) $(LIBJLI_CFLAGS), \
                                  -      DISABLED_WARNINGS_microsoft := 4244 4047 4267, \
                                         ARFLAGS := $(ARFLAGS), \
                                         OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/native/$(MODULE)/libjli_static, \
                                         DEBUG_SYMBOLS := $(DEBUG_ALL_BINARIES)))
                                  @@ -389,11 +376,8 @@ else ifeq ($(OPENJDK_TARGET_OS), macosx)
                                         SRC := $(LIBJLI_SRC_DIRS), \
                                         EXCLUDE_FILES := $(LIBJLI_EXCLUDE_FILES), \
                                         EXTRA_FILES := $(LIBJLI_EXTRA_FILES), \
                                  -      LANG := C, \
                                         OPTIMIZATION := HIGH, \
                                         CFLAGS := $(CFLAGS_JDKLIB) $(LIBJLI_CFLAGS), \
                                  -      DISABLED_WARNINGS_clang := implicit-function-declaration parentheses \
                                  -          int-conversion, \
                                         LDFLAGS := -nostdlib -r, \
                                         OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/native/$(MODULE)/libjli_static, \
                                         DEBUG_SYMBOLS := $(DEBUG_ALL_BINARIES)))
                                  @@ -411,7 +395,6 @@ else ifeq ($(OPENJDK_TARGET_OS), aix)
                                         SRC := $(LIBJLI_SRC_DIRS), \
                                         EXCLUDE_FILES := $(LIBJLI_EXCLUDE_FILES), \
                                         EXTRA_FILES := $(LIBJLI_EXTRA_FILES), \
                                  -      LANG := C, \
                                         OPTIMIZATION := HIGH, \
                                         CFLAGS := $(STATIC_LIBRARY_FLAGS) $(LIBJLI_CFLAGS), \
                                         ARFLAGS := $(ARFLAGS), \
                                  diff --git a/jdk/make/lib/Lib-java.instrument.gmk b/jdk/make/lib/Lib-java.instrument.gmk
                                  index 4aaec5ce5e2..5b668c87872 100644
                                  --- a/jdk/make/lib/Lib-java.instrument.gmk
                                  +++ b/jdk/make/lib/Lib-java.instrument.gmk
                                  @@ -57,7 +57,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBINSTRUMENT, \
                                       LIBRARY := instrument, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(LIBINSTRUMENT_SRC), \
                                  -    LANG := C, \
                                       OPTIMIZATION := LOW, \
                                       CFLAGS := $(LIBINSTRUMENT_CFLAGS) $(CFLAGS_WARNINGS_ARE_ERRORS), \
                                       CFLAGS_debug := -DJPLIS_LOGGING, \
                                  diff --git a/jdk/make/lib/Lib-java.management.gmk b/jdk/make/lib/Lib-java.management.gmk
                                  index 9f4435d7707..29d5c081665 100644
                                  --- a/jdk/make/lib/Lib-java.management.gmk
                                  +++ b/jdk/make/lib/Lib-java.management.gmk
                                  @@ -38,6 +38,11 @@ BUILD_LIBMANAGEMENT_CFLAGS := -I$(JDK_TOPDIR)/src/java.management/share/native/i
                                       $(LIBJAVA_HEADER_FLAGS) \
                                       #
                                   
                                  +# In (at least) VS2013 and later, -DPSAPI_VERSION=1 is needed to generate
                                  +# a binary that is compatible with windows versions older than 7/2008R2.
                                  +# See MSDN documentation for GetProcessMemoryInfo for more information.
                                  +BUILD_LIBMANAGEMENT_CFLAGS += -DPSAPI_VERSION=1
                                  +
                                   BUILD_LIBMANAGEMENT_EXCLUDES :=
                                   
                                   ifneq ($(OPENJDK_TARGET_OS), solaris)
                                  @@ -67,7 +72,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBMANAGEMENT, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(BUILD_LIBMANAGEMENT_SRC), \
                                       EXCLUDE_FILES := $(BUILD_LIBMANAGEMENT_EXCLUDES), \
                                  -    LANG := C, \
                                       OPTIMIZATION := $(LIBMANAGEMENT_OPTIMIZATION), \
                                       CFLAGS := $(CFLAGS_JDKLIB) $(CFLAGS_WARNINGS_ARE_ERRORS) $(BUILD_LIBMANAGEMENT_CFLAGS), \
                                       MAPFILE := $(LIBMANAGEMENT_MAPFILE), \
                                  diff --git a/jdk/make/lib/Lib-java.prefs.gmk b/jdk/make/lib/Lib-java.prefs.gmk
                                  index 1ed2b6b13a8..d12d7eff7dd 100644
                                  --- a/jdk/make/lib/Lib-java.prefs.gmk
                                  +++ b/jdk/make/lib/Lib-java.prefs.gmk
                                  @@ -37,7 +37,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBPREFS, \
                                       LIBRARY := prefs, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(LIBPREF_SRC_DIRS), \
                                  -    LANG := C, \
                                       OPTIMIZATION := HIGH, \
                                       CFLAGS := $(CFLAGS_JDKLIB) $(addprefix -I, $(LIBPREF_SRC_DIRS)) \
                                           $(LIBJAVA_HEADER_FLAGS), \
                                  diff --git a/jdk/make/lib/Lib-java.security.jgss.gmk b/jdk/make/lib/Lib-java.security.jgss.gmk
                                  index c2cee4e109b..401d0e7c0e9 100644
                                  --- a/jdk/make/lib/Lib-java.security.jgss.gmk
                                  +++ b/jdk/make/lib/Lib-java.security.jgss.gmk
                                  @@ -36,7 +36,6 @@ ifneq ($(OPENJDK_TARGET_OS), windows)
                                         LIBRARY := j2gss, \
                                         OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                         SRC := $(LIBJ2GSS_SRC), \
                                  -      LANG := C, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKLIB) $(addprefix -I, $(LIBJ2GSS_SRC)) \
                                             $(LIBJAVA_HEADER_FLAGS) \
                                  @@ -79,7 +78,6 @@ ifneq ($(BUILD_CRYPTO), no)
                                           LIBRARY := $(BUILD_LIBKRB5_NAME), \
                                           OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                           SRC := $(BUILD_LIBKRB5_SRC), \
                                  -        LANG := C, \
                                           OPTIMIZATION := LOW, \
                                           CFLAGS := $(CFLAGS_JDKLIB) \
                                               $(addprefix -I, $(BUILD_LIBKRB5_SRC)) \
                                  diff --git a/jdk/make/lib/Lib-java.smartcardio.gmk b/jdk/make/lib/Lib-java.smartcardio.gmk
                                  index b08fb077819..82dfbfd55c1 100644
                                  --- a/jdk/make/lib/Lib-java.smartcardio.gmk
                                  +++ b/jdk/make/lib/Lib-java.smartcardio.gmk
                                  @@ -37,7 +37,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJ2PCSC, \
                                       LIBRARY := j2pcsc, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(LIBJ2PCSC_SRC), \
                                  -    LANG := C, \
                                       CFLAGS_unix := -D__sun_jdk, \
                                       OPTIMIZATION := LOW, \
                                       CFLAGS := $(CFLAGS_JDKLIB) $(LIBJ2PCSC_CPPFLAGS), \
                                  diff --git a/jdk/make/lib/Lib-jdk.accessibility.gmk b/jdk/make/lib/Lib-jdk.accessibility.gmk
                                  new file mode 100644
                                  index 00000000000..a689c89c65c
                                  --- /dev/null
                                  +++ b/jdk/make/lib/Lib-jdk.accessibility.gmk
                                  @@ -0,0 +1,135 @@
                                  +#
                                  +# Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
                                  +# 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 LibCommon.gmk
                                  +
                                  +################################################################################
                                  +
                                  +ifeq ($(OPENJDK_TARGET_OS), windows)
                                  +
                                  +  ROOT_SRCDIR := $(JDK_TOPDIR)/src/jdk.accessibility/windows/native
                                  +  JAVA_AB_SRCDIR := $(ROOT_SRCDIR)/libjavaaccessbridge $(ROOT_SRCDIR)/common
                                  +  WIN_AB_SRCDIR := $(ROOT_SRCDIR)/libwindowsaccessbridge $(ROOT_SRCDIR)/common
                                  +  SYSINFO_SRCDIR := $(ROOT_SRCDIR)/libjabsysinfo
                                  +  ACCESSBRIDGE_CFLAGS := -I$(SUPPORT_OUTPUTDIR)/headers/jdk.accessibility \
                                  +      -I$(JDK_TOPDIR)/src/java.desktop/windows/native/include \
                                  +      -I$(JDK_TOPDIR)/src/java.desktop/share/native/include
                                  +
                                  +  define SetupJavaDLL
                                  +    # Parameter 1 Suffix
                                  +    # Parameter 2 ACCESSBRIDGE_ARCH_ suffix
                                  +
                                  +    $(call SetupNativeCompilation,BUILD_JAVAACCESSBRIDGE$1, \
                                  +        LIBRARY = javaaccessbridge$1, \
                                  +        OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                  +        SRC := $(JAVA_AB_SRCDIR), \
                                  +        OPTIMIZATION := LOW, \
                                  +        CFLAGS := $(CFLAGS_JDKLIB) $(ACCESSBRIDGE_CFLAGS) \
                                  +            $(addprefix -I,$(JAVA_AB_SRCDIR)) \
                                  +            -I$(JDK_TOPDIR)/src/jdk.accessibility/windows/native/include/bridge \
                                  +            -DACCESSBRIDGE_ARCH_$2, \
                                  +        LDFLAGS := $(LDFLAGS_JDKLIB) kernel32.lib user32.lib gdi32.lib \
                                  +            winspool.lib comdlg32.lib advapi32.lib shell32.lib \
                                  +            $(SUPPORT_OUTPUTDIR)/native/java.desktop/libjawt/jawt.lib \
                                  +            ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib \
                                  +            -subsystem:windows, \
                                  +        VERSIONINFO_RESOURCE := $(ROOT_SRCDIR)/common/AccessBridgeStatusWindow.rc, \
                                  +        RC_FLAGS := $(RC_FLAGS) \
                                  +            -D "JDK_FNAME=javaaccessbridge$1.dll" \
                                  +            -D "JDK_INTERNAL_NAME=javaaccessbridge$1" \
                                  +            -D "JDK_FTYPE=0x02L", \
                                  +        OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/native/$(MODULE)/libjavaaccessbridge$1, \
                                  +        DEBUG_SYMBOLS := true)
                                  +
                                  +    $$(BUILD_JAVAACCESSBRIDGE$1): $(SUPPORT_OUTPUTDIR)/native/java.desktop/libjawt/jawt.lib
                                  +
                                  +    TARGETS += $$(BUILD_JAVAACCESSBRIDGE$1)
                                  +  endef
                                  +
                                  +  define SetupWinDLL
                                  +    # Parameter 1 Suffix
                                  +    # Parameter 2 ACCESSBRIDGE_ARCH_ suffix
                                  +    $(call SetupNativeCompilation,BUILD_WINDOWSACCESSBRIDGE$1, \
                                  +        LIBRARY = windowsaccessbridge$1, \
                                  +        OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                  +        SRC := $(WIN_AB_SRCDIR), \
                                  +        OPTIMIZATION := LOW, \
                                  +        CFLAGS := $(filter-out -MD, $(CFLAGS_JDKLIB)) -MT $(ACCESSBRIDGE_CFLAGS) \
                                  +            $(addprefix -I,$(WIN_AB_SRCDIR)) \
                                  +            -I$(JDK_TOPDIR)/src/jdk.accessibility/windows/native/include/bridge \
                                  +            -DACCESSBRIDGE_ARCH_$2, \
                                  +        LDFLAGS := $(LDFLAGS_JDKLIB) kernel32.lib user32.lib gdi32.lib \
                                  +            winspool.lib comdlg32.lib advapi32.lib shell32.lib \
                                  +            ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib \
                                  +            -subsystem:windows \
                                  +            -def:$(ROOT_SRCDIR)/libwindowsaccessbridge/WinAccessBridge.DEF, \
                                  +        VERSIONINFO_RESOURCE := $(ROOT_SRCDIR)/common/AccessBridgeStatusWindow.rc, \
                                  +        RC_FLAGS := $(RC_FLAGS) \
                                  +            -D "JDK_FNAME=windowsaccessbridge$1.dll" \
                                  +            -D "JDK_INTERNAL_NAME=windowsaccessbridge$1" \
                                  +            -D "JDK_FTYPE=0x02L", \
                                  +        OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/native/$(MODULE)/libwindowsaccessbridge$1, \
                                  +        DEBUG_SYMBOLS := true)
                                  +
                                  +    TARGETS += $$(BUILD_WINDOWSACCESSBRIDGE$1)
                                  +
                                  +  endef
                                  +
                                  +  define SetupAccessBridgeSysInfo
                                  +
                                  +    $(call SetupNativeCompilation,BUILD_ACCESSBRIDGESYSINFO, \
                                  +        LIBRARY = jabsysinfo, \
                                  +        OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                  +        SRC := $(SYSINFO_SRCDIR), \
                                  +        OPTIMIZATION := LOW, \
                                  +        CFLAGS := $(CFLAGS_JDKLIB) $(ACCESSBRIDGE_CFLAGS), \
                                  +        LDFLAGS := $(LDFLAGS_JDKLIB) \
                                  +            -subsystem:windows -machine:I386, \
                                  +        VERSIONINFO_RESOURCE := $(ROOT_SRCDIR)/common/AccessBridgeStatusWindow.rc, \
                                  +        RC_FLAGS := $(RC_FLAGS) \
                                  +            -D "JDK_FNAME=jabsysinfo.dll" \
                                  +            -D "JDK_INTERNAL_NAME=jabsysinfo" \
                                  +            -D "JDK_FTYPE=0x02L", \
                                  +        OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/native/$(MODULE)/lib/libjabsysinfo, \
                                  +        DEBUG_SYMBOLS := true)
                                  +
                                  +    TARGETS += $$(BUILD_ACCESSBRIDGESYSINFO)
                                  +
                                  +  endef
                                  +
                                  +  ifeq ($(OPENJDK_TARGET_CPU_BITS), 32)
                                  +    $(eval $(call SetupAccessBridgeSysInfo))
                                  +    $(eval $(call SetupJavaDLL,-32,32))
                                  +    $(eval $(call SetupJavaDLL,,LEGACY))
                                  +    $(eval $(call SetupWinDLL,-32,32))
                                  +    $(eval $(call SetupWinDLL,,LEGACY))
                                  +  else
                                  +    $(eval $(call SetupJavaDLL,,64))
                                  +    $(eval $(call SetupWinDLL,-64,64))
                                  +  endif
                                  +
                                  +endif
                                  +
                                  +################################################################################
                                  diff --git a/jdk/make/lib/Lib-jdk.attach.gmk b/jdk/make/lib/Lib-jdk.attach.gmk
                                  index 3950b4a7474..c64867c070d 100644
                                  --- a/jdk/make/lib/Lib-jdk.attach.gmk
                                  +++ b/jdk/make/lib/Lib-jdk.attach.gmk
                                  @@ -32,7 +32,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBATTACH, \
                                       LIBRARY := attach, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(call FindSrcDirsForLib, jdk.attach, attach), \
                                  -    LANG := C, \
                                       OPTIMIZATION := LOW, \
                                       CFLAGS := $(CFLAGS_JDKLIB) $(CFLAGS_WARNINGS_ARE_ERRORS) \
                                           -I$(SUPPORT_OUTPUTDIR)/headers/jdk.attach \
                                  diff --git a/jdk/make/lib/Lib-jdk.crypto.ec.gmk b/jdk/make/lib/Lib-jdk.crypto.ec.gmk
                                  index 564eb402ae0..5781b777d1e 100644
                                  --- a/jdk/make/lib/Lib-jdk.crypto.ec.gmk
                                  +++ b/jdk/make/lib/Lib-jdk.crypto.ec.gmk
                                  @@ -47,7 +47,7 @@ ifeq ($(ENABLE_INTREE_EC), yes)
                                         LIBRARY := sunec, \
                                         OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                         SRC := $(LIBSUNEC_SRC), \
                                  -      LANG := C++, \
                                  +      TOOLCHAIN := TOOLCHAIN_LINK_CXX, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(filter-out $(ECC_JNI_SOLSPARC_FILTER), $(CFLAGS_JDKLIB)) \
                                             $(BUILD_LIBSUNEC_FLAGS) \
                                  diff --git a/jdk/make/lib/Lib-jdk.crypto.mscapi.gmk b/jdk/make/lib/Lib-jdk.crypto.mscapi.gmk
                                  index bc7d1a9fe3a..a2816dfc26b 100644
                                  --- a/jdk/make/lib/Lib-jdk.crypto.mscapi.gmk
                                  +++ b/jdk/make/lib/Lib-jdk.crypto.mscapi.gmk
                                  @@ -35,7 +35,6 @@ ifeq ($(OPENJDK_TARGET_OS), windows)
                                         LIBRARY := sunmscapi, \
                                         OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                         SRC := $(LIBSUNMSCAPI_SRC), \
                                  -      LANG := C++, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKLIB) \
                                             -I$(LIBSUNMSCAPI_SRC), \
                                  diff --git a/jdk/make/lib/Lib-jdk.crypto.pkcs11.gmk b/jdk/make/lib/Lib-jdk.crypto.pkcs11.gmk
                                  index 0672aa3a359..748b131045c 100644
                                  --- a/jdk/make/lib/Lib-jdk.crypto.pkcs11.gmk
                                  +++ b/jdk/make/lib/Lib-jdk.crypto.pkcs11.gmk
                                  @@ -34,7 +34,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJ2PKCS11, \
                                       LIBRARY := j2pkcs11, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(LIBJ2PKCS11_SRC), \
                                  -    LANG := C, \
                                       OPTIMIZATION := LOW, \
                                       CFLAGS := $(CFLAGS_JDKLIB) $(addprefix -I, $(LIBJ2PKCS11_SRC)) \
                                           $(LIBJAVA_HEADER_FLAGS) \
                                  diff --git a/jdk/make/lib/Lib-jdk.crypto.ucrypto.gmk b/jdk/make/lib/Lib-jdk.crypto.ucrypto.gmk
                                  index f66bd4554f9..22b865657a3 100644
                                  --- a/jdk/make/lib/Lib-jdk.crypto.ucrypto.gmk
                                  +++ b/jdk/make/lib/Lib-jdk.crypto.ucrypto.gmk
                                  @@ -35,7 +35,6 @@ ifeq ($(OPENJDK_TARGET_OS), solaris)
                                         LIBRARY := j2ucrypto, \
                                         OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                         SRC := $(LIBJ2UCRYPTO_SRC), \
                                  -      LANG := C, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKLIB) \
                                             $(addprefix -I, $(LIBJ2UCRYPTO_SRC)), \
                                  diff --git a/jdk/make/lib/Lib-jdk.deploy.osx.gmk b/jdk/make/lib/Lib-jdk.deploy.osx.gmk
                                  index f68b9c065e3..51c56355b5b 100644
                                  --- a/jdk/make/lib/Lib-jdk.deploy.osx.gmk
                                  +++ b/jdk/make/lib/Lib-jdk.deploy.osx.gmk
                                  @@ -35,7 +35,6 @@ ifeq ($(OPENJDK_TARGET_OS), macosx)
                                         LIBRARY := AppleScriptEngine, \
                                         OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                         SRC := $(LIBAPPLESCRIPTENGINE_SRC), \
                                  -      LANG := C, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKLIB) \
                                             -I$(LIBAPPLESCRIPTENGINE_SRC) \
                                  @@ -68,7 +67,6 @@ ifeq ($(OPENJDK_TARGET_OS), macosx)
                                         LIBRARY := osx, \
                                         OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                         SRC := $(LIBOSX_DIRS), \
                                  -      LANG := C, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKLIB) \
                                             $(LIBOSX_CFLAGS), \
                                  diff --git a/jdk/make/lib/Lib-jdk.hprof.agent.gmk b/jdk/make/lib/Lib-jdk.hprof.agent.gmk
                                  index 040abc35680..7c43331b33c 100644
                                  --- a/jdk/make/lib/Lib-jdk.hprof.agent.gmk
                                  +++ b/jdk/make/lib/Lib-jdk.hprof.agent.gmk
                                  @@ -45,7 +45,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBHPROF, \
                                       LIBRARY := hprof, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(BUILD_LIBHPROF_SRC), \
                                  -    LANG := C, \
                                       OPTIMIZATION := $(LIBHPROF_OPTIMIZATION), \
                                       CFLAGS := $(CFLAGS_JDKLIB) $(CFLAGS_WARNINGS_ARE_ERRORS) \
                                           $(BUILD_LIBHPROF_CFLAGS), \
                                  @@ -75,7 +74,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJAVA_CRW_DEMO, \
                                       LIBRARY := java_crw_demo, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(LIBJAVA_CRW_DEMO_SRC), \
                                  -    LANG := C, \
                                       OPTIMIZATION := LOW, \
                                       CFLAGS := $(CFLAGS_JDKLIB) $(CFLAGS_WARNINGS_ARE_ERRORS) \
                                           $(addprefix -I, $(LIBJAVA_CRW_DEMO_SRC)), \
                                  diff --git a/jdk/make/lib/Lib-jdk.jdi.gmk b/jdk/make/lib/Lib-jdk.jdi.gmk
                                  index e46a7276b71..eb1de3b43c1 100644
                                  --- a/jdk/make/lib/Lib-jdk.jdi.gmk
                                  +++ b/jdk/make/lib/Lib-jdk.jdi.gmk
                                  @@ -43,7 +43,6 @@ ifeq ($(OPENJDK_TARGET_OS), windows)
                                         LIBRARY := dt_shmem, \
                                         OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                         SRC := $(LIBDT_SHMEM_SRC), \
                                  -      LANG := C, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKLIB) $(CFLAGS_WARNINGS_ARE_ERRORS) -DUSE_MMAP \
                                             $(LIBDT_SHMEM_CPPFLAGS), \
                                  diff --git a/jdk/make/lib/Lib-jdk.jdwp.agent.gmk b/jdk/make/lib/Lib-jdk.jdwp.agent.gmk
                                  index 75c5d3b6830..0743ac85a97 100644
                                  --- a/jdk/make/lib/Lib-jdk.jdwp.agent.gmk
                                  +++ b/jdk/make/lib/Lib-jdk.jdwp.agent.gmk
                                  @@ -40,7 +40,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBDT_SOCKET, \
                                       LIBRARY := dt_socket, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(LIBDT_SOCKET_SRC), \
                                  -    LANG := C, \
                                       OPTIMIZATION := LOW, \
                                       CFLAGS := $(CFLAGS_JDKLIB) $(CFLAGS_CFLAGS_WARNINGS_ARE_ERRORS) -DUSE_MMAP \
                                           $(LIBDT_SOCKET_CPPFLAGS), \
                                  @@ -77,7 +76,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJDWP, \
                                       LIBRARY := jdwp, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(LIBJDWP_SRC), \
                                  -    LANG := C, \
                                       OPTIMIZATION := LOW, \
                                       CFLAGS := $(CFLAGS_JDKLIB) $(CFLAGS_WARNINGS_ARE_ERRORS) -DJDWP_LOGGING \
                                           $(LIBJDWP_CPPFLAGS) \
                                  diff --git a/jdk/make/lib/Lib-jdk.pack200.gmk b/jdk/make/lib/Lib-jdk.pack200.gmk
                                  index 37e32d0a725..e9baaa3dbef 100644
                                  --- a/jdk/make/lib/Lib-jdk.pack200.gmk
                                  +++ b/jdk/make/lib/Lib-jdk.pack200.gmk
                                  @@ -32,7 +32,7 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBUNPACK, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(JDK_TOPDIR)/src/jdk.pack200/share/native/libunpack \
                                           $(JDK_TOPDIR)/src/jdk.pack200/share/native/common-unpack, \
                                  -    LANG := C++, \
                                  +    TOOLCHAIN := TOOLCHAIN_LINK_CXX, \
                                       OPTIMIZATION := LOW, \
                                       CFLAGS := $(CXXFLAGS_JDKLIB) \
                                           -DNO_ZLIB -DUNPACK_JNI -DFULL \
                                  @@ -40,11 +40,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBUNPACK, \
                                           -I$(JDK_TOPDIR)/src/jdk.pack200/share/native/common-unpack \
                                           $(LIBJAVA_HEADER_FLAGS), \
                                       CFLAGS_release := -DPRODUCT, \
                                  -    DISABLED_WARNINGS_gcc := conversion-null sign-compare format-security \
                                  -        format-nonliteral parentheses, \
                                  -    DISABLED_WARNINGS_clang := bool-conversion format-security, \
                                  -    DISABLED_WARNINGS_solstudio := truncwarn, \
                                  -    DISABLED_WARNINGS_microsoft := 4267 4018, \
                                       MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libunpack/mapfile-vers, \
                                       LDFLAGS := $(LDFLAGS_JDKLIB) $(LDFLAGS_CXX_JDK) \
                                           $(call SET_SHARED_LIBRARY_ORIGIN), \
                                  diff --git a/jdk/make/lib/Lib-jdk.sctp.gmk b/jdk/make/lib/Lib-jdk.sctp.gmk
                                  index 61e236e94ff..15db8b3b380 100644
                                  --- a/jdk/make/lib/Lib-jdk.sctp.gmk
                                  +++ b/jdk/make/lib/Lib-jdk.sctp.gmk
                                  @@ -41,7 +41,6 @@ ifeq ($(OPENJDK_TARGET_OS_TYPE), unix)
                                           LIBRARY := sctp, \
                                           OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                           SRC := $(JDK_TOPDIR)/src/jdk.sctp/$(OPENJDK_TARGET_OS_TYPE)/native/libsctp, \
                                  -        LANG := C, \
                                           OPTIMIZATION := LOW, \
                                           CFLAGS := $(CFLAGS_JDKLIB) \
                                               -I $(JDK_TOPDIR)/src/java.base/$(OPENJDK_TARGET_OS_TYPE)/native/libnio/ch \
                                  diff --git a/jdk/make/lib/Lib-jdk.security.auth.gmk b/jdk/make/lib/Lib-jdk.security.auth.gmk
                                  index 80f05da0298..61cd9a66d5c 100644
                                  --- a/jdk/make/lib/Lib-jdk.security.auth.gmk
                                  +++ b/jdk/make/lib/Lib-jdk.security.auth.gmk
                                  @@ -42,7 +42,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJAAS, \
                                       LIBRARY := $(LIBJAAS_NAME), \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(call FindSrcDirsForLib, jdk.security.auth, jaas), \
                                  -    LANG := C, \
                                       OPTIMIZATION := LOW, \
                                       CFLAGS := $(CFLAGS_JDKLIB) -I$(SUPPORT_OUTPUTDIR)/headers/jdk.security.auth, \
                                       MAPFILE := $(LIBJAAS_MAPFILE), \
                                  diff --git a/jdk/make/lib/NetworkingLibraries.gmk b/jdk/make/lib/NetworkingLibraries.gmk
                                  index 4231121123e..0f4709301f6 100644
                                  --- a/jdk/make/lib/NetworkingLibraries.gmk
                                  +++ b/jdk/make/lib/NetworkingLibraries.gmk
                                  @@ -29,7 +29,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBNET, \
                                       LIBRARY := net, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(LIBNET_SRC_DIRS), \
                                  -    LANG := C, \
                                       OPTIMIZATION := LOW, \
                                       CFLAGS := $(CFLAGS_JDKLIB) -I$(SUPPORT_OUTPUTDIR)/headers/java.base \
                                           $(LIBJAVA_HEADER_FLAGS) $(addprefix -I, $(LIBNET_SRC_DIRS)), \
                                  diff --git a/jdk/make/lib/NioLibraries.gmk b/jdk/make/lib/NioLibraries.gmk
                                  index fd973ccc535..71a65138a9d 100644
                                  --- a/jdk/make/lib/NioLibraries.gmk
                                  +++ b/jdk/make/lib/NioLibraries.gmk
                                  @@ -65,7 +65,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBNIO, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(BUILD_LIBNIO_SRC), \
                                       EXCLUDE_FILES := $(BUILD_LIBNIO_EXFILES), \
                                  -    LANG := C, \
                                       OPTIMIZATION := HIGH, \
                                       CFLAGS := $(CFLAGS_JDKLIB) \
                                           $(BUILD_LIBNIO_CFLAGS), \
                                  diff --git a/jdk/make/lib/PlatformLibraries.gmk b/jdk/make/lib/PlatformLibraries.gmk
                                  index 0035b1dfbbb..74d535d9095 100644
                                  --- a/jdk/make/lib/PlatformLibraries.gmk
                                  +++ b/jdk/make/lib/PlatformLibraries.gmk
                                  @@ -33,7 +33,6 @@ ifeq ($(OPENJDK_TARGET_OS), macosx)
                                         LIBRARY := osxapp, \
                                         OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                         SRC := $(LIBOSXAPP_SRC), \
                                  -      LANG := C, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKLIB) \
                                             $(addprefix -I, $(LIBOSXAPP_SRC)) \
                                  diff --git a/jdk/make/lib/SoundLibraries.gmk b/jdk/make/lib/SoundLibraries.gmk
                                  index f123d179d7a..07bd1f28637 100644
                                  --- a/jdk/make/lib/SoundLibraries.gmk
                                  +++ b/jdk/make/lib/SoundLibraries.gmk
                                  @@ -35,8 +35,6 @@ LIBJSOUND_CFLAGS := \
                                   
                                   LIBJSOUND_SRC_FILES := Utilities.c Platform.c
                                   
                                  -LIBJSOUND_LANG := C
                                  -
                                   EXTRA_SOUND_JNI_LIBS :=
                                   
                                   LIBJSOUND_MIDIFILES := \
                                  @@ -81,7 +79,7 @@ ifeq ($(OPENJDK_TARGET_OS), aix)
                                   endif # OPENJDK_TARGET_OS aix
                                   
                                   ifeq ($(OPENJDK_TARGET_OS), macosx)
                                  -  LIBJSOUND_LANG := C++
                                  +  LIBJSOUND_TOOLCHAIN := TOOLCHAIN_LINK_CXX
                                     LIBJSOUND_CFLAGS += -DX_PLATFORM=X_MACOSX \
                                         -DUSE_PORTS=TRUE \
                                         -DUSE_DAUDIO=TRUE \
                                  @@ -124,7 +122,7 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJSOUND, \
                                       OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
                                       SRC := $(LIBJSOUND_SRC_DIRS), \
                                       INCLUDE_FILES := $(LIBJSOUND_SRC_FILES), \
                                  -    LANG := $(LIBJSOUND_LANG), \
                                  +    TOOLCHAIN := $(LIBJSOUND_TOOLCHAIN), \
                                       OPTIMIZATION := LOW, \
                                       CFLAGS := $(CFLAGS_JDKLIB) \
                                           $(LIBJSOUND_CFLAGS), \
                                  @@ -169,7 +167,6 @@ ifneq ($(filter jsoundalsa, $(EXTRA_SOUND_JNI_LIBS)), )
                                             PLATFORM_API_LinuxOS_ALSA_MidiOut.c \
                                             PLATFORM_API_LinuxOS_ALSA_MidiUtils.c \
                                             PLATFORM_API_LinuxOS_ALSA_Ports.c, \
                                  -      LANG := C, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKLIB) $(ALSA_CFLAGS) \
                                             $(LIBJSOUND_CFLAGS) \
                                  @@ -201,7 +198,6 @@ ifneq ($(filter jsoundds, $(EXTRA_SOUND_JNI_LIBS)), )
                                         SRC := $(LIBJSOUND_SRC_DIRS), \
                                         INCLUDE_FILES := Utilities.c $(LIBJSOUND_DAUDIOFILES) \
                                             PLATFORM_API_WinOS_DirectSound.cpp, \
                                  -      LANG := C++, \
                                         OPTIMIZATION := LOW, \
                                         CFLAGS := $(CFLAGS_JDKLIB) \
                                             $(LIBJSOUND_CFLAGS) \
                                  diff --git a/jdk/make/mapfiles/launchers/mapfile-x86_64 b/jdk/make/mapfiles/launchers/mapfile-x86_64
                                  index 61c2d1cc3f2..5700d67f2a0 100644
                                  --- a/jdk/make/mapfiles/launchers/mapfile-x86_64
                                  +++ b/jdk/make/mapfiles/launchers/mapfile-x86_64
                                  @@ -34,6 +34,14 @@ SUNWprivate_1.1 {
                                   		_environ;
                                   		__environ_lock;
                                   
                                  +		# These are needed by the c runtime in SS12u4
                                  +		___Argv;
                                  +		__xargv;
                                  +		__xargc;
                                  +		_start;
                                  +		__longdouble_used;
                                  +		_lib_version;
                                  +
                                   	local:
                                   		*;
                                   };
                                  diff --git a/jdk/make/mapfiles/libjava/reorder-sparc b/jdk/make/mapfiles/libjava/reorder-sparc
                                  index d10037652d1..5ae7ccabd3f 100644
                                  --- a/jdk/make/mapfiles/libjava/reorder-sparc
                                  +++ b/jdk/make/mapfiles/libjava/reorder-sparc
                                  @@ -1,7 +1,6 @@
                                   data = R0x2000;
                                   text = LOAD ?RXO;
                                   # Test Null
                                  -text: .text%init64IO: OUTPUTDIR/UnixFileSystem_md.o;
                                   text: .text%JNI_OnLoad;
                                   text: .text%Canonicalize;
                                   text: .text%canonicalize;
                                  @@ -38,10 +37,9 @@ text: .text%Java_java_lang_System_setErr0;
                                   text: .text%Java_java_lang_System_identityHashCode;
                                   text: .text%Java_sun_misc_Signal_findSignal;
                                   text: .text%Java_sun_misc_Signal_handle0;
                                  -text: .text%Java_java_io_FileSystem_getFileSystem;
                                   text: .text%JNU_NewObjectByName;
                                   text: .text%Java_java_io_UnixFileSystem_initIDs;
                                  -text: .text%Java_java_io_UnixFileSystem_canonicalize;
                                  +text: .text%Java_java_io_UnixFileSystem_canonicalize0;
                                   text: .text%JNU_GetStringPlatformChars;
                                   text: .text%JNU_ReleaseStringPlatformChars;
                                   text: .text%Java_java_io_FileInputStream_open0;
                                  @@ -52,27 +50,25 @@ text: .text%Java_java_io_FileInputStream_available;
                                   text: .text%Java_java_io_FileInputStream_close0;
                                   text: .text%Java_java_lang_System_mapLibraryName;
                                   text: .text%Java_java_io_UnixFileSystem_getBooleanAttributes0;
                                  -text: .text%statMode: OUTPUTDIR/UnixFileSystem_md.o;
                                   text: .text%Java_java_lang_ClassLoader_00024NativeLibrary_load;
                                  -text: .text%Java_java_lang_Compiler_registerNatives;
                                   text: .text%Java_java_lang_ClassLoader_00024NativeLibrary_find;
                                   text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedExceptionAction_2;
                                   text: .text%Java_java_io_UnixFileSystem_list;
                                   text: .text%JNU_ClassString;
                                   text: .text%JNU_CopyObjectArray;
                                   text: .text%Java_java_lang_String_intern;
                                  -text: .text%Java_java_lang_ClassLoader_findLoadedClass;
                                  +text: .text%Java_java_lang_ClassLoader_findLoadedClass0;
                                   text: .text%Java_java_lang_ClassLoader_findBootstrapClass;
                                   text: .text%Java_java_lang_Throwable_fillInStackTrace;
                                   text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedExceptionAction_2Ljava_security_AccessControlContext_2;
                                   text: .text%Java_java_io_UnixFileSystem_getLastModifiedTime;
                                  -text: .text%Java_java_lang_Float_floatToIntBits;
                                  -text: .text%Java_java_lang_Double_doubleToLongBits;
                                  +text: .text%Java_java_lang_Float_floatToRawIntBits;
                                  +text: .text%Java_java_lang_Double_doubleToRawLongBits;
                                   text: .text%Java_java_io_UnixFileSystem_getLength;
                                   text: .text%Java_java_lang_ClassLoader_defineClass0;
                                   text: .text%VerifyClassCodes;
                                   # Test Exit
                                  -text: .text%Java_java_lang_Shutdown_halt;
                                  +text: .text%Java_java_lang_Shutdown_halt0;
                                   # Test Hello
                                   text: .text%Java_java_io_FileOutputStream_writeBytes;
                                   text: .text%writeBytes;
                                  @@ -91,9 +87,7 @@ text: .text%JNU_NotifyAll;
                                   text: .text%JNU_CallMethodByName;
                                   text: .text%JNU_CallMethodByNameV;
                                   text: .text%Java_java_io_UnixFileSystem_createDirectory;
                                  -text: .text%Java_java_util_prefs_FileSystemPreferences_lockFile0;
                                   text: .text%Java_java_io_UnixFileSystem_setLastModifiedTime;
                                  -text: .text%Java_java_util_prefs_FileSystemPreferences_unlockFile0;
                                   # Test LoadJFrame
                                   text: .text%Java_sun_reflect_NativeMethodAccessorImpl_invoke0;
                                   text: .text%Java_java_lang_Class_isInstance;
                                  diff --git a/jdk/make/mapfiles/libjava/reorder-sparcv9 b/jdk/make/mapfiles/libjava/reorder-sparcv9
                                  index 2609711c21f..f10986626b0 100644
                                  --- a/jdk/make/mapfiles/libjava/reorder-sparcv9
                                  +++ b/jdk/make/mapfiles/libjava/reorder-sparcv9
                                  @@ -1,7 +1,6 @@
                                   data = R0x2000;
                                   text = LOAD ?RXO;
                                   # Test Null
                                  -text: .text%init64IO: OUTPUTDIR/UnixFileSystem_md.o;
                                   text: .text%JNI_OnLoad;
                                   text: .text%Canonicalize;
                                   text: .text%canonicalize;
                                  @@ -30,9 +29,9 @@ text: .text%Java_sun_reflect_Reflection_getCallerClass__;
                                   text: .text%Java_sun_reflect_Reflection_getCallerClass__I;
                                   text: .text%Java_java_lang_Class_forName0;
                                   text: .text%Java_java_lang_String_intern;
                                  -text: .text%Java_java_lang_Float_floatToIntBits;
                                  -text: .text%Java_java_lang_Double_doubleToLongBits;
                                  -text: .text%Java_java_lang_ClassLoader_findLoadedClass;
                                  +text: .text%Java_java_lang_Float_floatToRawIntBits;
                                  +text: .text%Java_java_lang_Double_doubleToRawLongBits;
                                  +text: .text%Java_java_lang_ClassLoader_findLoadedClass0;
                                   text: .text%Java_java_lang_ClassLoader_findBootstrapClass;
                                   text: .text%VerifyClassCodes;
                                   text: .text%Java_java_lang_Throwable_fillInStackTrace;
                                  @@ -41,10 +40,9 @@ text: .text%Java_java_lang_System_setErr0;
                                   text: .text%Java_java_lang_System_identityHashCode;
                                   text: .text%Java_sun_misc_Signal_findSignal;
                                   text: .text%Java_sun_misc_Signal_handle0;
                                  -text: .text%Java_java_io_FileSystem_getFileSystem;
                                   text: .text%JNU_NewObjectByName;
                                   text: .text%Java_java_io_UnixFileSystem_initIDs;
                                  -text: .text%Java_java_io_UnixFileSystem_canonicalize;
                                  +text: .text%Java_java_io_UnixFileSystem_canonicalize0;
                                   text: .text%JNU_GetStringPlatformChars;
                                   text: .text%JNU_ReleaseStringPlatformChars;
                                   text: .text%Java_java_io_FileInputStream_open0;
                                  @@ -53,13 +51,11 @@ text: .text%Java_java_io_FileInputStream_readBytes;
                                   text: .text%readBytes;
                                   text: .text%Java_java_io_FileInputStream_available;
                                   text: .text%Java_java_io_FileInputStream_close0;
                                  -text: .text%Java_java_lang_Compiler_registerNatives;
                                   text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedExceptionAction_2;
                                   text: .text%Java_java_io_UnixFileSystem_list;
                                   text: .text%JNU_ClassString;
                                   text: .text%JNU_CopyObjectArray;
                                   text: .text%Java_java_io_UnixFileSystem_getBooleanAttributes0;
                                  -text: .text%statMode: OUTPUTDIR/UnixFileSystem_md.o;
                                   text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedExceptionAction_2Ljava_security_AccessControlContext_2;
                                   text: .text%Java_java_lang_System_mapLibraryName;
                                   text: .text%Java_java_lang_ClassLoader_00024NativeLibrary_load;
                                  @@ -68,7 +64,7 @@ text: .text%Java_java_io_UnixFileSystem_getLength;
                                   text: .text%Java_java_lang_Object_getClass;
                                   text: .text%Java_java_lang_ClassLoader_defineClass0;
                                   # Test Exit
                                  -text: .text%Java_java_lang_Shutdown_halt;
                                  +text: .text%Java_java_lang_Shutdown_halt0;
                                   # Test Hello
                                   text: .text%Java_java_io_FileOutputStream_writeBytes;
                                   text: .text%writeBytes;
                                  @@ -88,9 +84,7 @@ text: .text%JNU_CallMethodByName;
                                   text: .text%JNU_CallMethodByNameV;
                                   text: .text%Java_java_io_UnixFileSystem_createDirectory;
                                   text: .text%Java_java_io_UnixFileSystem_getLastModifiedTime;
                                  -text: .text%Java_java_util_prefs_FileSystemPreferences_lockFile0;
                                   text: .text%Java_java_io_UnixFileSystem_setLastModifiedTime;
                                  -text: .text%Java_java_util_prefs_FileSystemPreferences_unlockFile0;
                                   # Test LoadJFrame
                                   text: .text%Java_java_lang_Class_isAssignableFrom;
                                   text: .text%Java_java_lang_Class_isInstance;
                                  diff --git a/jdk/make/mapfiles/libjava/reorder-x86 b/jdk/make/mapfiles/libjava/reorder-x86
                                  index b8ea2d43dae..03609c18916 100644
                                  --- a/jdk/make/mapfiles/libjava/reorder-x86
                                  +++ b/jdk/make/mapfiles/libjava/reorder-x86
                                  @@ -2,7 +2,6 @@ data = R0x2000;
                                   text = LOAD ?RXO;
                                   # Test Null
                                   text: .text%_init;
                                  -text: .text%init64IO: OUTPUTDIR/UnixFileSystem_md.o;
                                   text: .text%JNI_OnLoad;
                                   text: .text%Canonicalize;
                                   text: .text%canonicalize;
                                  @@ -36,8 +35,6 @@ text: .text%Java_sun_reflect_NativeConstructorAccessorImpl_newInstance0;
                                   text: .text%Java_java_lang_Throwable_fillInStackTrace;
                                   text: .text%Java_java_lang_System_setOut0;
                                   text: .text%Java_java_lang_System_setErr0;
                                  -text: .text%Java_java_lang_Compiler_registerNatives;
                                  -text: .text%Java_java_io_FileSystem_getFileSystem;
                                   text: .text%JNU_NewObjectByName;
                                   text: .text%Java_java_io_UnixFileSystem_initIDs;
                                   text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedExceptionAction_2;
                                  @@ -46,17 +43,17 @@ text: .text%JNU_GetStringPlatformChars;
                                   text: .text%JNU_ReleaseStringPlatformChars;
                                   text: .text%JNU_ClassString;
                                   text: .text%JNU_CopyObjectArray;
                                  -text: .text%Java_java_io_UnixFileSystem_canonicalize;
                                  +text: .text%Java_java_io_UnixFileSystem_canonicalize0;
                                   text: .text%Java_java_io_UnixFileSystem_getBooleanAttributes0;
                                  -text: .text%Java_java_lang_ClassLoader_findLoadedClass;
                                  +text: .text%Java_java_lang_ClassLoader_findLoadedClass0;
                                   text: .text%Java_java_lang_ClassLoader_findBootstrapClass;
                                   text: .text%Java_java_security_AccessController_doPrivileged__Ljava_security_PrivilegedExceptionAction_2Ljava_security_AccessControlContext_2;
                                   text: .text%Java_java_lang_System_mapLibraryName;
                                   text: .text%cpchars: OUTPUTDIR/System.o;
                                   text: .text%Java_java_lang_ClassLoader_00024NativeLibrary_load;
                                   text: .text%Java_java_lang_ClassLoader_00024NativeLibrary_find;
                                  -text: .text%Java_java_lang_Float_floatToIntBits;
                                  -text: .text%Java_java_lang_Double_doubleToLongBits;
                                  +text: .text%Java_java_lang_Float_floatToRawIntBits;
                                  +text: .text%Java_java_lang_Double_doubleToRawLongBits;
                                   text: .text%Java_java_io_FileInputStream_open0;
                                   text: .text%fileOpen;
                                   text: .text%Java_java_io_UnixFileSystem_getLength;
                                  @@ -67,7 +64,7 @@ text: .text%Java_java_lang_Object_getClass;
                                   text: .text%Java_java_lang_ClassLoader_defineClass0;
                                   text: .text%VerifyClassCodes;
                                   # Test Exit
                                  -text: .text%Java_java_lang_Shutdown_halt;
                                  +text: .text%Java_java_lang_Shutdown_halt0;
                                   # Test Hello
                                   text: .text%Java_java_io_FileOutputStream_writeBytes;
                                   text: .text%writeBytes;
                                  @@ -93,9 +90,7 @@ text: .text%Java_java_util_logging_FileHandler_lockFile;
                                   text: .text%Java_java_io_FileOutputStream_open0;
                                   text: .text%Java_java_io_UnixFileSystem_createDirectory;
                                   text: .text%Java_java_io_UnixFileSystem_getLastModifiedTime;
                                  -text: .text%Java_java_util_prefs_FileSystemPreferences_lockFile0;
                                   text: .text%Java_java_io_UnixFileSystem_setLastModifiedTime;
                                  -text: .text%Java_java_util_prefs_FileSystemPreferences_unlockFile0;
                                   text: .text%Java_java_io_FileOutputStream_close0;
                                   text: .text%Java_java_util_logging_FileHandler_unlockFile;
                                   # Test LoadJFrame
                                  diff --git a/jdk/src/java.base/unix/conf/ppc/jvm.cfg b/jdk/make/mapfiles/libunpack/mapfile-vers-unpack200-solaris-sparc
                                  similarity index 72%
                                  rename from jdk/src/java.base/unix/conf/ppc/jvm.cfg
                                  rename to jdk/make/mapfiles/libunpack/mapfile-vers-unpack200-solaris-sparc
                                  index e93034166b2..63f2a41a478 100644
                                  --- a/jdk/src/java.base/unix/conf/ppc/jvm.cfg
                                  +++ b/jdk/make/mapfiles/libunpack/mapfile-vers-unpack200-solaris-sparc
                                  @@ -1,3 +1,4 @@
                                  +#
                                   # Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                  @@ -21,15 +22,20 @@
                                   # or visit www.oracle.com if you need additional information or have any
                                   # questions.
                                   #
                                  -# List of JVMs that can be used as an option to java, javac, etc.
                                  -# Order is important -- first in this list is the default JVM.
                                  -# NOTE that this both this file and its format are UNSUPPORTED and
                                  -# WILL GO AWAY in a future release.
                                  -#
                                  -# You may also select a JVM in an arbitrary location with the
                                  -# "-XXaltjvm=" option, but that too is unsupported
                                  -# and may not be available in a future release.
                                  -#
                                  --client KNOWN
                                  --server KNOWN
                                  --minimal KNOWN
                                  +
                                  +# Define library interface.
                                  +
                                  +SUNWprivate_1.1 {
                                  +	global:
                                  +		# These are needed by the c runtime in SS12u4
                                  +		_environ;
                                  +		__environ_lock;
                                  +		___Argv;
                                  +		__xargv;
                                  +		__xargc;
                                  +		_start;
                                  +		_lib_version;
                                  +
                                  +	local:
                                  +	    *;
                                  +};
                                  diff --git a/jdk/src/java.base/unix/conf/arm/jvm.cfg b/jdk/make/mapfiles/libunpack/mapfile-vers-unpack200-solaris-x86
                                  similarity index 71%
                                  rename from jdk/src/java.base/unix/conf/arm/jvm.cfg
                                  rename to jdk/make/mapfiles/libunpack/mapfile-vers-unpack200-solaris-x86
                                  index c46211325bc..60220b18ad3 100644
                                  --- a/jdk/src/java.base/unix/conf/arm/jvm.cfg
                                  +++ b/jdk/make/mapfiles/libunpack/mapfile-vers-unpack200-solaris-x86
                                  @@ -1,3 +1,4 @@
                                  +#
                                   # Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
                                   # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                   #
                                  @@ -21,15 +22,21 @@
                                   # or visit www.oracle.com if you need additional information or have any
                                   # questions.
                                   #
                                  -# List of JVMs that can be used as an option to java, javac, etc.
                                  -# Order is important -- first in this list is the default JVM.
                                  -# NOTE that this both this file and its format are UNSUPPORTED and
                                  -# WILL GO AWAY in a future release.
                                  -#
                                  -# You may also select a JVM in an arbitrary location with the
                                  -# "-XXaltjvm=" option, but that too is unsupported
                                  -# and may not be available in a future release.
                                  -#
                                  --client IF_SERVER_CLASS -server
                                  --server KNOWN
                                  --minimal KNOWN
                                  +
                                  +# Define library interface.
                                  +
                                  +SUNWprivate_1.1 {
                                  +	global:
                                  +		# These are needed by the c runtime in SS12u4
                                  +		_environ;
                                  +		__environ_lock;
                                  +		___Argv;
                                  +		__xargv;
                                  +		__xargc;
                                  +		_start;
                                  +		__longdouble_used;
                                  +		_lib_version;
                                  +
                                  +	local:
                                  +	    *;
                                  +};
                                  diff --git a/jdk/make/mapfiles/libzip/reorder-sparcv9 b/jdk/make/mapfiles/libzip/reorder-sparcv9
                                  index c1e3237e8f9..4b72820dca5 100644
                                  --- a/jdk/make/mapfiles/libzip/reorder-sparcv9
                                  +++ b/jdk/make/mapfiles/libzip/reorder-sparcv9
                                  @@ -12,7 +12,6 @@ text: .text%addMetaName: OUTPUTDIR/zip_util.o;
                                   text: .text%ZIP_FindEntry;
                                   text: .text%ZIP_GetEntry;
                                   text: .text%ZIP_Lock;
                                  -text: .text%readLOC: OUTPUTDIR/zip_util.o;
                                   text: .text%ZIP_Unlock;
                                   text: .text%ZIP_FreeEntry;
                                   text: .text%Java_java_util_zip_ZipFile_initIDs;
                                  @@ -37,7 +36,6 @@ text: .text%Java_java_util_zip_Inflater_inflateBytes;
                                   text: .text%inflate;
                                   text: .text%Java_java_util_zip_ZipFile_read;
                                   text: .text%ZIP_Read;
                                  -text: .text%huft_build: OUTPUTDIR/inftrees.o;
                                   text: .text%zcfree;
                                   text: .text%Java_java_util_jar_JarFile_getMetaInfEntryNames;
                                   text: .text%ZIP_ReadEntry;
                                  diff --git a/jdk/make/mapfiles/libzip/reorder-x86 b/jdk/make/mapfiles/libzip/reorder-x86
                                  index f3cf4ff6183..95c47b64354 100644
                                  --- a/jdk/make/mapfiles/libzip/reorder-x86
                                  +++ b/jdk/make/mapfiles/libzip/reorder-x86
                                  @@ -13,7 +13,6 @@ text: .text%addMetaName: OUTPUTDIR/zip_util.o;
                                   text: .text%ZIP_FindEntry;
                                   text: .text%ZIP_GetEntry;
                                   text: .text%ZIP_Lock;
                                  -text: .text%readLOC: OUTPUTDIR/zip_util.o;
                                   text: .text%ZIP_Unlock;
                                   text: .text%ZIP_FreeEntry;
                                   text: .text%Java_java_util_zip_ZipFile_initIDs;
                                  @@ -38,7 +37,6 @@ text: .text%Java_java_util_zip_Inflater_inflateBytes;
                                   text: .text%inflate;
                                   text: .text%Java_java_util_zip_ZipFile_read;
                                   text: .text%ZIP_Read;
                                  -text: .text%huft_build: OUTPUTDIR/inftrees.o;
                                   text: .text%zcfree;
                                   text: .text%Java_java_util_jar_JarFile_getMetaInfEntryNames;
                                   text: .text%ZIP_ReadEntry;
                                  diff --git a/jdk/make/src/classes/build/tools/module/ext.modules b/jdk/make/src/classes/build/tools/module/ext.modules
                                  index 934d4e9ba16..15c2e9d6ae0 100644
                                  --- a/jdk/make/src/classes/build/tools/module/ext.modules
                                  +++ b/jdk/make/src/classes/build/tools/module/ext.modules
                                  @@ -4,7 +4,7 @@ java.corba
                                   java.transaction
                                   java.xml.bind
                                   java.xml.ws
                                  -jdk.accessbridge
                                  +jdk.accessibility
                                   jdk.crypto.ec
                                   jdk.crypto.mscapi
                                   jdk.crypto.pkcs11
                                  @@ -12,4 +12,5 @@ jdk.crypto.ucrypto
                                   jdk.localedata
                                   jdk.naming.dns
                                   jdk.scripting.nashorn
                                  +jdk.xml.dom
                                   jdk.zipfs
                                  diff --git a/jdk/src/java.base/linux/classes/sun/nio/ch/EPollPort.java b/jdk/src/java.base/linux/classes/sun/nio/ch/EPollPort.java
                                  index 651457e98df..27f2c7b76d1 100644
                                  --- a/jdk/src/java.base/linux/classes/sun/nio/ch/EPollPort.java
                                  +++ b/jdk/src/java.base/linux/classes/sun/nio/ch/EPollPort.java
                                  @@ -105,7 +105,7 @@ final class EPollPort
                                   
                                           // create the queue and offer the special event to ensure that the first
                                           // threads polls
                                  -        this.queue = new ArrayBlockingQueue(MAX_EPOLL_EVENTS);
                                  +        this.queue = new ArrayBlockingQueue<>(MAX_EPOLL_EVENTS);
                                           this.queue.offer(NEED_TO_POLL);
                                       }
                                   
                                  diff --git a/jdk/src/java.base/linux/classes/sun/nio/fs/LinuxNativeDispatcher.java b/jdk/src/java.base/linux/classes/sun/nio/fs/LinuxNativeDispatcher.java
                                  index e8d8dc8d6e2..5dbb331631f 100644
                                  --- a/jdk/src/java.base/linux/classes/sun/nio/fs/LinuxNativeDispatcher.java
                                  +++ b/jdk/src/java.base/linux/classes/sun/nio/fs/LinuxNativeDispatcher.java
                                  @@ -121,7 +121,7 @@ class LinuxNativeDispatcher extends UnixNativeDispatcher {
                                       private static native void init();
                                   
                                       static {
                                  -        AccessController.doPrivileged(new PrivilegedAction() {
                                  +        AccessController.doPrivileged(new PrivilegedAction<>() {
                                               public Void run() {
                                                   System.loadLibrary("nio");
                                                   return null;
                                  diff --git a/jdk/src/java.base/linux/classes/sun/nio/fs/LinuxWatchService.java b/jdk/src/java.base/linux/classes/sun/nio/fs/LinuxWatchService.java
                                  index 123fab5b3ea..19079d72878 100644
                                  --- a/jdk/src/java.base/linux/classes/sun/nio/fs/LinuxWatchService.java
                                  +++ b/jdk/src/java.base/linux/classes/sun/nio/fs/LinuxWatchService.java
                                  @@ -190,7 +190,7 @@ class LinuxWatchService
                                               this.watcher = watcher;
                                               this.ifd = ifd;
                                               this.socketpair = sp;
                                  -            this.wdToKey = new HashMap();
                                  +            this.wdToKey = new HashMap<>();
                                               this.address = unsafe.allocateMemory(BUFFER_SIZE);
                                           }
                                   
                                  @@ -457,7 +457,7 @@ class LinuxWatchService
                                       private static native int poll(int fd1, int fd2) throws UnixException;
                                   
                                       static {
                                  -        AccessController.doPrivileged(new PrivilegedAction() {
                                  +        AccessController.doPrivileged(new PrivilegedAction<>() {
                                               public Void run() {
                                                   System.loadLibrary("nio");
                                                   return null;
                                  diff --git a/jdk/src/java.base/linux/classes/sun/nio/fs/MagicFileTypeDetector.java b/jdk/src/java.base/linux/classes/sun/nio/fs/MagicFileTypeDetector.java
                                  index 801bd626724..2798c960f87 100644
                                  --- a/jdk/src/java.base/linux/classes/sun/nio/fs/MagicFileTypeDetector.java
                                  +++ b/jdk/src/java.base/linux/classes/sun/nio/fs/MagicFileTypeDetector.java
                                  @@ -68,7 +68,7 @@ class MagicFileTypeDetector extends AbstractFileTypeDetector {
                                       private static native byte[] probe0(long pathAddress);
                                   
                                       static {
                                  -        AccessController.doPrivileged(new PrivilegedAction() {
                                  +        AccessController.doPrivileged(new PrivilegedAction<>() {
                                               @Override
                                               public Void run() {
                                                   System.loadLibrary("nio");
                                  diff --git a/jdk/src/java.base/macosx/native/libjli/java_md_macosx.c b/jdk/src/java.base/macosx/native/libjli/java_md_macosx.c
                                  index eb432c12e08..d48f5255f3c 100644
                                  --- a/jdk/src/java.base/macosx/native/libjli/java_md_macosx.c
                                  +++ b/jdk/src/java.base/macosx/native/libjli/java_md_macosx.c
                                  @@ -852,7 +852,7 @@ ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void
                                       if (pthread_create(&tid, &attr, (void *(*)(void*))continuation, (void*)args) == 0) {
                                         void * tmp;
                                         pthread_join(tid, &tmp);
                                  -      rslt = (int)tmp;
                                  +      rslt = (int)(intptr_t)tmp;
                                       } else {
                                        /*
                                         * Continue execution in current thread if for some reason (e.g. out of
                                  diff --git a/jdk/src/java.base/share/classes/com/sun/crypto/provider/JceKeyStore.java b/jdk/src/java.base/share/classes/com/sun/crypto/provider/JceKeyStore.java
                                  index a364881d88a..0e3f1ed0566 100644
                                  --- a/jdk/src/java.base/share/classes/com/sun/crypto/provider/JceKeyStore.java
                                  +++ b/jdk/src/java.base/share/classes/com/sun/crypto/provider/JceKeyStore.java
                                  @@ -711,7 +711,7 @@ public final class JceKeyStore extends KeyStoreSpi {
                                                       cf = CertificateFactory.getInstance("X509");
                                                   } else {
                                                       // version 2
                                  -                    cfs = new Hashtable(3);
                                  +                    cfs = new Hashtable<>(3);
                                                   }
                                   
                                                   entries.clear();
                                  diff --git a/jdk/src/java.base/share/classes/com/sun/crypto/provider/PBEKeyFactory.java b/jdk/src/java.base/share/classes/com/sun/crypto/provider/PBEKeyFactory.java
                                  index 0c87971876f..3fd312f8737 100644
                                  --- a/jdk/src/java.base/share/classes/com/sun/crypto/provider/PBEKeyFactory.java
                                  +++ b/jdk/src/java.base/share/classes/com/sun/crypto/provider/PBEKeyFactory.java
                                  @@ -56,7 +56,7 @@ abstract class PBEKeyFactory extends SecretKeyFactorySpi {
                                       }
                                   
                                       static {
                                  -        validTypes = new HashSet(17);
                                  +        validTypes = new HashSet<>(17);
                                           validTypes.add("PBEWithMD5AndDES".toUpperCase(Locale.ENGLISH));
                                           validTypes.add("PBEWithSHA1AndDESede".toUpperCase(Locale.ENGLISH));
                                           validTypes.add("PBEWithSHA1AndRC2_40".toUpperCase(Locale.ENGLISH));
                                  diff --git a/jdk/src/java.base/share/classes/com/sun/crypto/provider/RSACipher.java b/jdk/src/java.base/share/classes/com/sun/crypto/provider/RSACipher.java
                                  index 0ce3358aaad..c912a3f04f0 100644
                                  --- a/jdk/src/java.base/share/classes/com/sun/crypto/provider/RSACipher.java
                                  +++ b/jdk/src/java.base/share/classes/com/sun/crypto/provider/RSACipher.java
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                    *
                                    * This code is free software; you can redistribute it and/or modify it
                                  @@ -350,7 +350,7 @@ public final class RSACipher extends CipherSpi {
                                               switch (mode) {
                                               case MODE_SIGN:
                                                   data = padding.pad(buffer, 0, bufOfs);
                                  -                return RSACore.rsa(data, privateKey);
                                  +                return RSACore.rsa(data, privateKey, true);
                                               case MODE_VERIFY:
                                                   byte[] verifyBuffer = RSACore.convert(buffer, 0, bufOfs);
                                                   data = RSACore.rsa(verifyBuffer, publicKey);
                                  @@ -360,7 +360,7 @@ public final class RSACipher extends CipherSpi {
                                                   return RSACore.rsa(data, publicKey);
                                               case MODE_DECRYPT:
                                                   byte[] decryptBuffer = RSACore.convert(buffer, 0, bufOfs);
                                  -                data = RSACore.rsa(decryptBuffer, privateKey);
                                  +                data = RSACore.rsa(decryptBuffer, privateKey, false);
                                                   return padding.unpad(data);
                                               default:
                                                   throw new AssertionError("Internal error");
                                  diff --git a/jdk/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java b/jdk/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java
                                  index 439acb94f47..3d588bf8a2e 100644
                                  --- a/jdk/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java
                                  +++ b/jdk/src/java.base/share/classes/com/sun/crypto/provider/SunJCE.java
                                  @@ -115,7 +115,7 @@ public final class SunJCE extends Provider {
                                           final String BLOCK_PADS = "NOPADDING|PKCS5PADDING|ISO10126PADDING";
                                   
                                           AccessController.doPrivileged(
                                  -            new java.security.PrivilegedAction() {
                                  +            new java.security.PrivilegedAction<>() {
                                                   public Object run() {
                                   
                                                       /*
                                  diff --git a/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java b/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java
                                  index 52864dfb02f..d254cb8d5d2 100644
                                  --- a/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java
                                  +++ b/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java
                                  @@ -87,7 +87,7 @@ class NativeUnpack {
                                           // If loading from stand alone build uncomment this.
                                           // System.loadLibrary("unpack");
                                           java.security.AccessController.doPrivileged(
                                  -            new java.security.PrivilegedAction() {
                                  +            new java.security.PrivilegedAction<>() {
                                                   public Void run() {
                                                       System.loadLibrary("unpack");
                                                       return null;
                                  diff --git a/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/Package.java b/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/Package.java
                                  index af78754e06b..002d88197cb 100644
                                  --- a/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/Package.java
                                  +++ b/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/Package.java
                                  @@ -1210,7 +1210,7 @@ class Package {
                                           // This keeps files of similar format near each other.
                                           // Put class files at the end, keeping their fixed order.
                                           // Be sure the JAR file's required manifest stays at the front. (4893051)
                                  -        Collections.sort(files, new Comparator() {
                                  +        Collections.sort(files, new Comparator<>() {
                                                   public int compare(File r0, File r1) {
                                                       // Get the file name.
                                                       String f0 = r0.nameString;
                                  diff --git a/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/PackageReader.java b/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/PackageReader.java
                                  index 000a643f873..018c33f6fd0 100644
                                  --- a/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/PackageReader.java
                                  +++ b/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/PackageReader.java
                                  @@ -1151,7 +1151,7 @@ class PackageReader extends BandStructure {
                                           return -1;
                                       }
                                   
                                  -    Comparator entryOutputOrder = new Comparator() {
                                  +    Comparator entryOutputOrder = new Comparator<>() {
                                           public int compare(Entry e0, Entry e1) {
                                               int k0 = getOutputIndex(e0);
                                               int k1 = getOutputIndex(e1);
                                  diff --git a/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/PackageWriter.java b/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/PackageWriter.java
                                  index bca629f8008..bd3c89951ee 100644
                                  --- a/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/PackageWriter.java
                                  +++ b/jdk/src/java.base/share/classes/com/sun/java/util/jar/pack/PackageWriter.java
                                  @@ -829,7 +829,7 @@ class PackageWriter extends BandStructure {
                                           maxFlags = new int[ATTR_CONTEXT_LIMIT];
                                           allLayouts = new FixedList<>(ATTR_CONTEXT_LIMIT);
                                           for (int i = 0; i < ATTR_CONTEXT_LIMIT; i++) {
                                  -            allLayouts.set(i, new HashMap());
                                  +            allLayouts.set(i, new HashMap<>());
                                           }
                                           // Collect maxFlags and allLayouts.
                                           for (Class cls : pkg.classes) {
                                  @@ -892,7 +892,7 @@ class PackageWriter extends BandStructure {
                                               // Sort by count, most frequent first.
                                               // Predefs. participate in this sort, though it does not matter.
                                               Arrays.sort(layoutsAndCounts,
                                  -                        new Comparator>() {
                                  +                        new Comparator<>() {
                                                   public int compare(Map.Entry e0,
                                                                      Map.Entry e1) {
                                                       // Primary sort key is count, reversed.
                                  @@ -1010,7 +1010,7 @@ class PackageWriter extends BandStructure {
                                           int numAttrDefs = defList.size();
                                           Object[][] defs = new Object[numAttrDefs][];
                                           defList.toArray(defs);
                                  -        Arrays.sort(defs, new Comparator() {
                                  +        Arrays.sort(defs, new Comparator<>() {
                                               public int compare(Object[] a0, Object[] a1) {
                                                   // Primary sort key is attr def header.
                                                   @SuppressWarnings("unchecked")
                                  diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/HttpsURLConnection.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/HttpsURLConnection.java
                                  index c60435331ec..6ce3b16ff0b 100644
                                  --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/HttpsURLConnection.java
                                  +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/HttpsURLConnection.java
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                    *
                                    * This code is free software; you can redistribute it and/or modify it
                                  @@ -32,10 +32,10 @@ package com.sun.net.ssl;
                                   import java.net.URL;
                                   import java.net.HttpURLConnection;
                                   import java.io.IOException;
                                  +import java.security.cert.Certificate;
                                   import javax.net.SocketFactory;
                                   import javax.net.ssl.SSLSocketFactory;
                                  -
                                  -import javax.security.cert.X509Certificate;
                                  +import javax.net.ssl.SSLPeerUnverifiedException;
                                   
                                   /**
                                    * HTTP URL connection with support for HTTPS-specific features. See
                                  @@ -70,7 +70,8 @@ class HttpsURLConnection extends HttpURLConnection
                                        * the server did not authenticate.
                                        * @return the server certificate chain
                                        */
                                  -    public abstract X509Certificate [] getServerCertificateChain();
                                  +    public abstract Certificate[] getServerCertificates()
                                  +        throws SSLPeerUnverifiedException;
                                   
                                       /**
                                        * HostnameVerifier provides a callback mechanism so that
                                  diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactory.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactory.java
                                  index 30e941a89d5..6ddf6bf6917 100644
                                  --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactory.java
                                  +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/KeyManagerFactory.java
                                  @@ -63,7 +63,7 @@ public class KeyManagerFactory {
                                        */
                                       public final static String getDefaultAlgorithm() {
                                           String type;
                                  -        type = AccessController.doPrivileged(new PrivilegedAction() {
                                  +        type = AccessController.doPrivileged(new PrivilegedAction<>() {
                                               public String run() {
                                                   return Security.getProperty("sun.ssl.keymanager.type");
                                               }
                                  diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java
                                  index b9ef566a0e7..8b0701c0a29 100644
                                  --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java
                                  +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/TrustManagerFactory.java
                                  @@ -63,7 +63,7 @@ public class TrustManagerFactory {
                                        */
                                       public final static String getDefaultAlgorithm() {
                                           String type;
                                  -        type = AccessController.doPrivileged(new PrivilegedAction() {
                                  +        type = AccessController.doPrivileged(new PrivilegedAction<>() {
                                               public String run() {
                                                   return Security.getProperty("sun.ssl.trustmanager.type");
                                               }
                                  diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java
                                  index fba0b3befce..07ff87ba85a 100644
                                  --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java
                                  +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java
                                  @@ -1,5 +1,5 @@
                                   /*
                                  - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
                                  + * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
                                    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
                                    *
                                    * This code is free software; you can redistribute it and/or modify it
                                  @@ -187,25 +187,6 @@ public class HttpsURLConnectionOldImpl
                                           return delegate.getServerCertificates();
                                       }
                                   
                                  -    /**
                                  -     * Returns the server's X.509 certificate chain, or null if
                                  -     * the server did not authenticate.
                                  -     *
                                  -     * NOTE: This method is not necessary for the version of this class
                                  -     * implementing javax.net.ssl.HttpsURLConnection, but provided for
                                  -     * compatibility with the com.sun.net.ssl.HttpsURLConnection version.
                                  -     */
                                  -    public javax.security.cert.X509Certificate[] getServerCertificateChain() {
                                  -        try {
                                  -            return delegate.getServerCertificateChain();
                                  -        } catch (SSLPeerUnverifiedException e) {
                                  -            // this method does not throw an exception as declared in
                                  -            // com.sun.net.ssl.HttpsURLConnection.
                                  -            // Return null for compatibility.
                                  -            return null;
                                  -        }
                                  -    }
                                  -
                                       /*
                                        * Allowable input/output sequences:
                                        * [interpreted as POST/PUT]
                                  diff --git a/jdk/src/java.base/share/classes/java/io/ExpiringCache.java b/jdk/src/java.base/share/classes/java/io/ExpiringCache.java
                                  index 5f16877313a..3cd295bda16 100644
                                  --- a/jdk/src/java.base/share/classes/java/io/ExpiringCache.java
                                  +++ b/jdk/src/java.base/share/classes/java/io/ExpiringCache.java
                                  @@ -64,7 +64,7 @@ class ExpiringCache {
                                       @SuppressWarnings("serial")
                                       ExpiringCache(long millisUntilExpiration) {
                                           this.millisUntilExpiration = millisUntilExpiration;
                                  -        map = new LinkedHashMap() {
                                  +        map = new LinkedHashMap<>() {
                                               protected boolean removeEldestEntry(Map.Entry eldest) {
                                                 return size() > MAX_ENTRIES;
                                               }
                                  diff --git a/jdk/src/java.base/share/classes/java/io/FilePermission.java b/jdk/src/java.base/share/classes/java/io/FilePermission.java
                                  index b008d4f933a..0c5bcf35178 100644
                                  --- a/jdk/src/java.base/share/classes/java/io/FilePermission.java
                                  +++ b/jdk/src/java.base/share/classes/java/io/FilePermission.java
                                  @@ -201,7 +201,7 @@ public final class FilePermission extends Permission implements Serializable {
                                           }
                                   
                                           // store only the canonical cpath if possible
                                  -        cpath = AccessController.doPrivileged(new PrivilegedAction() {
                                  +        cpath = AccessController.doPrivileged(new PrivilegedAction<>() {
                                               public String run() {
                                                   try {
                                                       String path = cpath;
                                  diff --git a/jdk/src/java.base/share/classes/java/io/ObjectInputStream.java b/jdk/src/java.base/share/classes/java/io/ObjectInputStream.java
                                  index 6ae3a542c10..3f098418207 100644
                                  --- a/jdk/src/java.base/share/classes/java/io/ObjectInputStream.java
                                  +++ b/jdk/src/java.base/share/classes/java/io/ObjectInputStream.java
                                  @@ -1263,7 +1263,7 @@ public class ObjectInputStream
                                        */
                                       private static boolean auditSubclass(final Class subcl) {
                                           Boolean result = AccessController.doPrivileged(
                                  -            new PrivilegedAction() {
                                  +            new PrivilegedAction<>() {
                                                   public Boolean run() {
                                                       for (Class cl = subcl;
                                                            cl != ObjectInputStream.class;
                                  @@ -2255,7 +2255,7 @@ public class ObjectInputStream
                                               try {
                                                   while (list != null) {
                                                       AccessController.doPrivileged(
                                  -                        new PrivilegedExceptionAction()
                                  +                        new PrivilegedExceptionAction<>()
                                                       {
                                                           public Void run() throws InvalidObjectException {
                                                               list.obj.validateObject();
                                  diff --git a/jdk/src/java.base/share/classes/java/io/ObjectOutputStream.java b/jdk/src/java.base/share/classes/java/io/ObjectOutputStream.java
                                  index e99e0257f31..861b201aae8 100644
                                  --- a/jdk/src/java.base/share/classes/java/io/ObjectOutputStream.java
                                  +++ b/jdk/src/java.base/share/classes/java/io/ObjectOutputStream.java
                                  @@ -1066,7 +1066,7 @@ public class ObjectOutputStream
                                        */
                                       private static boolean auditSubclass(final Class subcl) {
                                           Boolean result = AccessController.doPrivileged(
                                  -            new PrivilegedAction() {
                                  +            new PrivilegedAction<>() {
                                                   public Boolean run() {
                                                       for (Class cl = subcl;
                                                            cl != ObjectOutputStream.class;
                                  diff --git a/jdk/src/java.base/share/classes/java/io/ObjectStreamClass.java b/jdk/src/java.base/share/classes/java/io/ObjectStreamClass.java
                                  index 1e8a4342390..7220eb3ab0b 100644
                                  --- a/jdk/src/java.base/share/classes/java/io/ObjectStreamClass.java
                                  +++ b/jdk/src/java.base/share/classes/java/io/ObjectStreamClass.java
                                  @@ -367,7 +367,7 @@ public class ObjectStreamClass implements Serializable {
                                                   entry = th;
                                               }
                                               if (future.set(entry)) {
                                  -                Caches.localDescs.put(key, new SoftReference(entry));
                                  +                Caches.localDescs.put(key, new SoftReference<>(entry));
                                               } else {
                                                   // nested lookup call already set future
                                                   entry = future.get();
                                  @@ -430,7 +430,7 @@ public class ObjectStreamClass implements Serializable {
                                               }
                                               if (interrupted) {
                                                   AccessController.doPrivileged(
                                  -                    new PrivilegedAction() {
                                  +                    new PrivilegedAction<>() {
                                                           public Void run() {
                                                               Thread.currentThread().interrupt();
                                                               return null;
                                  @@ -465,7 +465,7 @@ public class ObjectStreamClass implements Serializable {
                                           localDesc = this;
                                   
                                           if (serializable) {
                                  -            AccessController.doPrivileged(new PrivilegedAction() {
                                  +            AccessController.doPrivileged(new PrivilegedAction<>() {
                                                   public Void run() {
                                                       if (isEnum) {
                                                           suid = Long.valueOf(0);
                                  @@ -1733,7 +1733,7 @@ public class ObjectStreamClass implements Serializable {
                                               for (int i = 0; i < fields.length; i++) {
                                                   fieldSigs[i] = new MemberSignature(fields[i]);
                                               }
                                  -            Arrays.sort(fieldSigs, new Comparator() {
                                  +            Arrays.sort(fieldSigs, new Comparator<>() {
                                                   public int compare(MemberSignature ms1, MemberSignature ms2) {
                                                       return ms1.name.compareTo(ms2.name);
                                                   }
                                  @@ -1764,7 +1764,7 @@ public class ObjectStreamClass implements Serializable {
                                               for (int i = 0; i < cons.length; i++) {
                                                   consSigs[i] = new MemberSignature(cons[i]);
                                               }
                                  -            Arrays.sort(consSigs, new Comparator() {
                                  +            Arrays.sort(consSigs, new Comparator<>() {
                                                   public int compare(MemberSignature ms1, MemberSignature ms2) {
                                                       return ms1.signature.compareTo(ms2.signature);
                                                   }
                                  @@ -1787,7 +1787,7 @@ public class ObjectStreamClass implements Serializable {
                                               for (int i = 0; i < methods.length; i++) {
                                                   methSigs[i] = new MemberSignature(methods[i]);
                                               }
                                  -            Arrays.sort(methSigs, new Comparator() {
                                  +            Arrays.sort(methSigs, new Comparator<>() {
                                                   public int compare(MemberSignature ms1, MemberSignature ms2) {
                                                       int comp = ms1.name.compareTo(ms2.name);
                                                       if (comp == 0) {
                                  @@ -2164,7 +2164,7 @@ public class ObjectStreamClass implements Serializable {
                                                   entry = th;
                                               }
                                               future.set(entry);
                                  -            Caches.reflectors.put(key, new SoftReference(entry));
                                  +            Caches.reflectors.put(key, new SoftReference<>(entry));
                                           }
                                   
                                           if (entry instanceof FieldReflector) {
                                  diff --git a/jdk/src/java.base/share/classes/java/io/ObjectStreamException.java b/jdk/src/java.base/share/classes/java/io/ObjectStreamException.java
                                  index d87a56fb8c5..94fc560139f 100644
                                  --- a/jdk/src/java.base/share/classes/java/io/ObjectStreamException.java
                                  +++ b/jdk/src/java.base/share/classes/java/io/ObjectStreamException.java
                                  @@ -38,10 +38,10 @@ public abstract class ObjectStreamException extends IOException {
                                       /**
                                        * Create an ObjectStreamException with the specified argument.
                                        *
                                  -     * @param classname the detailed message for the exception
                                  +     * @param message the detailed message for the exception
                                        */
                                  -    protected ObjectStreamException(String classname) {
                                  -        super(classname);
                                  +    protected ObjectStreamException(String message) {
                                  +        super(message);
                                       }
                                   
                                       /**
                                  diff --git a/jdk/src/java.base/share/classes/java/lang/CharacterName.java b/jdk/src/java.base/share/classes/java/lang/CharacterName.java
                                  index 9dbbffc7299..bcc715180d0 100644
                                  --- a/jdk/src/java.base/share/classes/java/lang/CharacterName.java
                                  +++ b/jdk/src/java.base/share/classes/java/lang/CharacterName.java
                                  @@ -45,7 +45,7 @@ class CharacterName {
                                           DataInputStream dis = null;
                                           try {
                                               dis = new DataInputStream(new InflaterInputStream(
                                  -                AccessController.doPrivileged(new PrivilegedAction()
                                  +                AccessController.doPrivileged(new PrivilegedAction<>()
                                                   {
                                                       public InputStream run() {
                                                           return getClass().getResourceAsStream("uniName.dat");
                                  diff --git a/jdk/src/java.base/share/classes/java/lang/Class.java b/jdk/src/java.base/share/classes/java/lang/Class.java
                                  index 258ec369ce5..9748cc6c804 100644
                                  --- a/jdk/src/java.base/share/classes/java/lang/Class.java
                                  +++ b/jdk/src/java.base/share/classes/java/lang/Class.java
                                  @@ -437,7 +437,7 @@ public final class Class implements java.io.Serializable,
                                                   // (the stack depth is wrong for the Constructor's
                                                   // security check to work)
                                                   java.security.AccessController.doPrivileged(
                                  -                    new java.security.PrivilegedAction() {
                                  +                    new java.security.PrivilegedAction<>() {
                                                           public Void run() {
                                                                   c.setAccessible(true);
                                                                   return null;
                                  @@ -1068,7 +1068,7 @@ public final class Class implements java.io.Serializable,
                                                                                    Reflection.getCallerClass(), true);
                                               // Client is ok to access declared methods but j.l.Class might not be.
                                               Method[] candidates = AccessController.doPrivileged(
                                  -                    new PrivilegedAction() {
                                  +                    new PrivilegedAction<>() {
                                                           @Override
                                                           public Method[] run() {
                                                               return enclosingCandidate.getDeclaredMethods();
                                  @@ -1228,7 +1228,7 @@ public final class Class implements java.io.Serializable,
                                                                                    Reflection.getCallerClass(), true);
                                               // Client is ok to access declared methods but j.l.Class might not be.
                                               Constructor[] candidates = AccessController.doPrivileged(
                                  -                    new PrivilegedAction[]>() {
                                  +                    new PrivilegedAction<>() {
                                                           @Override
                                                           public Constructor[] run() {
                                                               return enclosingCandidate.getDeclaredConstructors();
                                  @@ -1542,7 +1542,7 @@ public final class Class implements java.io.Serializable,
                                           // has already been ok'd by the SecurityManager.
                                   
                                           return java.security.AccessController.doPrivileged(
                                  -            new java.security.PrivilegedAction[]>() {
                                  +            new java.security.PrivilegedAction<>() {
                                                   public Class[] run() {
                                                       List> list = new ArrayList<>();
                                                       Class currentClass = Class.this;
                                  @@ -3293,7 +3293,7 @@ public final class Class implements java.io.Serializable,
                                       private static boolean initted = false;
                                       private static void checkInitted() {
                                           if (initted) return;
                                  -        AccessController.doPrivileged(new PrivilegedAction() {
                                  +        AccessController.doPrivileged(new PrivilegedAction<>() {
                                                   public Void run() {
                                                       // Tests to ensure the system properties table is fully
                                                       // initialized. This is needed because reflection code is
                                  @@ -3349,7 +3349,7 @@ public final class Class implements java.io.Serializable,
                                               try {
                                                   final Method values = getMethod("values");
                                                   java.security.AccessController.doPrivileged(
                                  -                    new java.security.PrivilegedAction() {
                                  +                    new java.security.PrivilegedAction<>() {
                                                           public Void run() {
                                                                   values.setAccessible(true);
                                                                   return null;
                                  diff --git a/jdk/src/java.base/share/classes/java/lang/ClassLoader.java b/jdk/src/java.base/share/classes/java/lang/ClassLoader.java
                                  index 3eb5819473e..295955847ca 100644
                                  --- a/jdk/src/java.base/share/classes/java/lang/ClassLoader.java
                                  +++ b/jdk/src/java.base/share/classes/java/lang/ClassLoader.java
                                  @@ -496,7 +496,7 @@ public abstract class ClassLoader {
                                               final String name = cls.getName();
                                               final int i = name.lastIndexOf('.');
                                               if (i != -1) {
                                  -                AccessController.doPrivileged(new PrivilegedAction() {
                                  +                AccessController.doPrivileged(new PrivilegedAction<>() {
                                                       public Void run() {
                                                           sm.checkPackageAccess(name.substring(0, i));
                                                           return null;
                                  @@ -1265,7 +1265,7 @@ public abstract class ClassLoader {
                                       {
                                           final Enumeration e =
                                               getBootstrapClassPath().getResources(name);
                                  -        return new Enumeration () {
                                  +        return new Enumeration<> () {
                                               public URL nextElement() {
                                                   return e.nextElement().getURL();
                                               }
                                  @@ -1867,7 +1867,7 @@ public abstract class ClassLoader {
                                           boolean isBuiltin = (name != null);
                                           if (!isBuiltin) {
                                               name = AccessController.doPrivileged(
                                  -                new PrivilegedAction() {
                                  +                new PrivilegedAction<>() {
                                                       public String run() {
                                                           try {
                                                               return file.exists() ? file.getCanonicalPath() : null;
                                  diff --git a/jdk/src/java.base/share/classes/java/lang/Package.java b/jdk/src/java.base/share/classes/java/lang/Package.java
                                  index 725429d4b2e..9cd63274b65 100644
                                  --- a/jdk/src/java.base/share/classes/java/lang/Package.java
                                  +++ b/jdk/src/java.base/share/classes/java/lang/Package.java
                                  @@ -595,7 +595,7 @@ public class Package implements java.lang.reflect.AnnotatedElement {
                                   
                                           CachedManifest(final String fileName) {
                                               this.fileName = fileName;
                                  -            this.url = AccessController.doPrivileged(new PrivilegedAction() {
                                  +            this.url = AccessController.doPrivileged(new PrivilegedAction<>() {
                                                   public URL run() {
                                                       final File file = new File(fileName);
                                                       if (file.isFile()) {
                                  @@ -626,7 +626,7 @@ public class Package implements java.lang.reflect.AnnotatedElement {
                                                   if (m != null) {
                                                       return m;
                                                   }
                                  -                m = AccessController.doPrivileged(new PrivilegedAction() {
                                  +                m = AccessController.doPrivileged(new PrivilegedAction<>() {
                                                       public Manifest run() {
                                                           try (FileInputStream fis = new FileInputStream(fileName);
                                                                JarInputStream jis = new JarInputStream(fis, false)) {
                                  diff --git a/jdk/src/java.base/share/classes/java/lang/ProcessBuilder.java b/jdk/src/java.base/share/classes/java/lang/ProcessBuilder.java
                                  index 940084cfbc6..f49b6a9cb9b 100644
                                  --- a/jdk/src/java.base/share/classes/java/lang/ProcessBuilder.java
                                  +++ b/jdk/src/java.base/share/classes/java/lang/ProcessBuilder.java
                                  @@ -82,7 +82,7 @@ import java.util.Map;
                                    * 
                                • a destination for standard output * and standard error. By default, the subprocess writes standard * output and standard error to pipes. Java code can access these pipes - * via the input streams returned by {@link Process#getInputStream()} and + * via the input streams returned by {@link Process#getOutputStream()} and * {@link Process#getErrorStream()}. However, standard output and * standard error may be redirected to other destinations using * {@link #redirectOutput(Redirect) redirectOutput} and @@ -988,14 +988,14 @@ public final class ProcessBuilder *
                                • the standard input to the subprocess was * {@linkplain #redirectInput redirected from a file} * and the security manager's - * {@link SecurityManager#checkRead checkRead} method + * {@link SecurityManager#checkRead(String) checkRead} method * denies read access to the file, or * *
                                • the standard output or standard error of the * subprocess was * {@linkplain #redirectOutput redirected to a file} * and the security manager's - * {@link SecurityManager#checkWrite checkWrite} method + * {@link SecurityManager#checkWrite(String) checkWrite} method * denies write access to the file * * diff --git a/jdk/src/java.base/share/classes/java/lang/Runtime.java b/jdk/src/java.base/share/classes/java/lang/Runtime.java index 114f6cb968f..e75fcb439cf 100644 --- a/jdk/src/java.base/share/classes/java/lang/Runtime.java +++ b/jdk/src/java.base/share/classes/java/lang/Runtime.java @@ -32,9 +32,9 @@ import sun.reflect.Reflection; /** * Every Java application has a single instance of class - * Runtime that allows the application to interface with + * {@code Runtime} that allows the application to interface with * the environment in which the application is running. The current - * runtime can be obtained from the getRuntime method. + * runtime can be obtained from the {@code getRuntime} method. *

                                  * An application cannot create its own instance of this class. * @@ -48,10 +48,10 @@ public class Runtime { /** * Returns the runtime object associated with the current Java application. - * Most of the methods of class Runtime are instance + * Most of the methods of class {@code Runtime} are instance * methods and must be invoked with respect to the current runtime object. * - * @return the Runtime object associated with the current + * @return the {@code Runtime} object associated with the current * Java application. */ public static Runtime getRuntime() { @@ -72,8 +72,7 @@ public class Runtime { * if any, are started in some unspecified order and allowed to run * concurrently until they finish. In the second phase all uninvoked * finalizers are run if {@link #runFinalizersOnExit finalization-on-exit} - * has been enabled. Once this is done the virtual machine {@link #halt - * halts}. + * has been enabled. Once this is done the virtual machine {@link #halt halts}. * *

                                  If this method is invoked after the virtual machine has begun its * shutdown sequence then if shutdown hooks are being run this method will @@ -82,7 +81,7 @@ public class Runtime { * with the given status code if the status is nonzero; otherwise, it * blocks indefinitely. * - *

                                  The {@link System#exit(int) System.exit} method is the + *

                                  The {@link System#exit(int) System.exit} method is the * conventional and convenient means of invoking this method. * * @param status @@ -90,8 +89,8 @@ public class Runtime { * indicates abnormal termination. * * @throws SecurityException - * If a security manager is present and its {@link - * SecurityManager#checkExit checkExit} method does not permit + * If a security manager is present and its + * {@link SecurityManager#checkExit checkExit} method does not permit * exiting with the specified status * * @see java.lang.SecurityException @@ -118,11 +117,11 @@ public class Runtime { *

                                    * *
                                  • The program exits normally, when the last non-daemon - * thread exits or when the {@link #exit exit} (equivalently, + * thread exits or when the {@link #exit exit} (equivalently, * {@link System#exit(int) System.exit}) method is invoked, or * *
                                  • The virtual machine is terminated in response to a - * user interrupt, such as typing ^C, or a system-wide event, + * user interrupt, such as typing {@code ^C}, or a system-wide event, * such as user logoff or system shutdown. * *
                                  @@ -134,17 +133,16 @@ public class Runtime { * run all uninvoked finalizers if finalization-on-exit has been enabled. * Finally, the virtual machine will halt. Note that daemon threads will * continue to run during the shutdown sequence, as will non-daemon threads - * if shutdown was initiated by invoking the {@link #exit exit} - * method. + * if shutdown was initiated by invoking the {@link #exit exit} method. * *

                                  Once the shutdown sequence has begun it can be stopped only by - * invoking the {@link #halt halt} method, which forcibly + * invoking the {@link #halt halt} method, which forcibly * terminates the virtual machine. * *

                                  Once the shutdown sequence has begun it is impossible to register a * new shutdown hook or de-register a previously-registered hook. * Attempting either of these operations will cause an - * {@link IllegalStateException} to be thrown. + * {@link IllegalStateException} to be thrown. * *

                                  Shutdown hooks run at a delicate time in the life cycle of a virtual * machine and should therefore be coded defensively. They should, in @@ -156,7 +154,7 @@ public class Runtime { * deadlocks. * *

                                  Shutdown hooks should also finish their work quickly. When a - * program invokes {@link #exit exit} the expectation is + * program invokes {@link #exit exit} the expectation is * that the virtual machine will promptly shut down and exit. When the * virtual machine is terminated due to user logoff or system shutdown the * underlying operating system may only allow a fixed amount of time in @@ -165,17 +163,17 @@ public class Runtime { * hook. * *

                                  Uncaught exceptions are handled in shutdown hooks just as in any - * other thread, by invoking the {@link ThreadGroup#uncaughtException - * uncaughtException} method of the thread's {@link - * ThreadGroup} object. The default implementation of this method - * prints the exception's stack trace to {@link System#err} and + * other thread, by invoking the + * {@link ThreadGroup#uncaughtException uncaughtException} method of the + * thread's {@link ThreadGroup} object. The default implementation of this + * method prints the exception's stack trace to {@link System#err} and * terminates the thread; it does not cause the virtual machine to exit or * halt. * *

                                  In rare circumstances the virtual machine may abort, that is, * stop running without shutting down cleanly. This occurs when the * virtual machine is terminated externally, for example with the - * SIGKILL signal on Unix or the TerminateProcess call on + * {@code SIGKILL} signal on Unix or the {@code TerminateProcess} call on * Microsoft Windows. The virtual machine may also abort if a native * method goes awry by, for example, corrupting internal data structures or * attempting to access nonexistent memory. If the virtual machine aborts @@ -183,7 +181,7 @@ public class Runtime { * will be run. * * @param hook - * An initialized but unstarted {@link Thread} object + * An initialized but unstarted {@link Thread} object * * @throws IllegalArgumentException * If the specified hook has already been registered, @@ -196,7 +194,7 @@ public class Runtime { * * @throws SecurityException * If a security manager is present and it denies - * {@link RuntimePermission}("shutdownHooks") + * {@link RuntimePermission}("shutdownHooks") * * @see #removeShutdownHook * @see #halt(int) @@ -212,11 +210,11 @@ public class Runtime { } /** - * De-registers a previously-registered virtual-machine shutdown hook.

                                  + * De-registers a previously-registered virtual-machine shutdown hook. * * @param hook the hook to remove - * @return true if the specified hook had previously been - * registered and was successfully de-registered, false + * @return {@code true} if the specified hook had previously been + * registered and was successfully de-registered, {@code false} * otherwise. * * @throws IllegalStateException @@ -225,7 +223,7 @@ public class Runtime { * * @throws SecurityException * If a security manager is present and it denies - * {@link RuntimePermission}("shutdownHooks") + * {@link RuntimePermission}("shutdownHooks") * * @see #addShutdownHook * @see #exit(int) @@ -244,23 +242,23 @@ public class Runtime { * method never returns normally. * *

                                  This method should be used with extreme caution. Unlike the - * {@link #exit exit} method, this method does not cause shutdown + * {@link #exit exit} method, this method does not cause shutdown * hooks to be started and does not run uninvoked finalizers if * finalization-on-exit has been enabled. If the shutdown sequence has * already been initiated then this method does not wait for any running * shutdown hooks or finalizers to finish their work. * * @param status - * Termination status. By convention, a nonzero status code - * indicates abnormal termination. If the {@link Runtime#exit - * exit} (equivalently, {@link System#exit(int) - * System.exit}) method has already been invoked then this - * status code will override the status code passed to that method. + * Termination status. By convention, a nonzero status code + * indicates abnormal termination. If the {@link Runtime#exit exit} + * (equivalently, {@link System#exit(int) System.exit}) method + * has already been invoked then this status code + * will override the status code passed to that method. * * @throws SecurityException - * If a security manager is present and its {@link - * SecurityManager#checkExit checkExit} method does not permit - * an exit with the specified status + * If a security manager is present and its + * {@link SecurityManager#checkExit checkExit} method + * does not permit an exit with the specified status * * @see #exit * @see #addShutdownHook @@ -282,7 +280,7 @@ public class Runtime { * By default, finalization on exit is disabled. * *

                                  If there is a security manager, - * its checkExit method is first called + * its {@code checkExit} method is first called * with 0 as its argument to ensure the exit is allowed. * This could result in a SecurityException. * @@ -293,7 +291,7 @@ public class Runtime { * behavior or deadlock. * * @throws SecurityException - * if a security manager exists and its checkExit + * if a security manager exists and its {@code checkExit} * method doesn't allow the exit. * * @see java.lang.Runtime#exit(int) @@ -318,9 +316,9 @@ public class Runtime { * Executes the specified string command in a separate process. * *

                                  This is a convenience method. An invocation of the form - * exec(command) + * {@code exec(command)} * behaves in exactly the same way as the invocation - * {@link #exec(String, String[], File) exec}(command, null, null). + * {@link #exec(String, String[], File) exec}{@code (command, null, null)}. * * @param command a specified system command. * @@ -335,10 +333,10 @@ public class Runtime { * If an I/O error occurs * * @throws NullPointerException - * If command is null + * If {@code command} is {@code null} * * @throws IllegalArgumentException - * If command is empty + * If {@code command} is empty * * @see #exec(String[], String[], File) * @see ProcessBuilder @@ -352,16 +350,16 @@ public class Runtime { * specified environment. * *

                                  This is a convenience method. An invocation of the form - * exec(command, envp) + * {@code exec(command, envp)} * behaves in exactly the same way as the invocation - * {@link #exec(String, String[], File) exec}(command, envp, null). + * {@link #exec(String, String[], File) exec}{@code (command, envp, null)}. * * @param command a specified system command. * * @param envp array of strings, each element of which * has environment variable settings in the format * name=value, or - * null if the subprocess should inherit + * {@code null} if the subprocess should inherit * the environment of the current process. * * @return A new {@link Process} object for managing the subprocess @@ -375,11 +373,11 @@ public class Runtime { * If an I/O error occurs * * @throws NullPointerException - * If command is null, - * or one of the elements of envp is null + * If {@code command} is {@code null}, + * or one of the elements of {@code envp} is {@code null} * * @throws IllegalArgumentException - * If command is empty + * If {@code command} is empty * * @see #exec(String[], String[], File) * @see ProcessBuilder @@ -393,29 +391,29 @@ public class Runtime { * specified environment and working directory. * *

                                  This is a convenience method. An invocation of the form - * exec(command, envp, dir) + * {@code exec(command, envp, dir)} * behaves in exactly the same way as the invocation - * {@link #exec(String[], String[], File) exec}(cmdarray, envp, dir), - * where cmdarray is an array of all the tokens in - * command. + * {@link #exec(String[], String[], File) exec}{@code (cmdarray, envp, dir)}, + * where {@code cmdarray} is an array of all the tokens in + * {@code command}. * - *

                                  More precisely, the command string is broken + *

                                  More precisely, the {@code command} string is broken * into tokens using a {@link StringTokenizer} created by the call - * new {@link StringTokenizer}(command) with no + * {@code new {@link StringTokenizer}(command)} with no * further modification of the character categories. The tokens * produced by the tokenizer are then placed in the new string - * array cmdarray, in the same order. + * array {@code cmdarray}, in the same order. * * @param command a specified system command. * * @param envp array of strings, each element of which * has environment variable settings in the format * name=value, or - * null if the subprocess should inherit + * {@code null} if the subprocess should inherit * the environment of the current process. * * @param dir the working directory of the subprocess, or - * null if the subprocess should inherit + * {@code null} if the subprocess should inherit * the working directory of the current process. * * @return A new {@link Process} object for managing the subprocess @@ -429,11 +427,11 @@ public class Runtime { * If an I/O error occurs * * @throws NullPointerException - * If command is null, - * or one of the elements of envp is null + * If {@code command} is {@code null}, + * or one of the elements of {@code envp} is {@code null} * * @throws IllegalArgumentException - * If command is empty + * If {@code command} is empty * * @see ProcessBuilder * @since 1.3 @@ -454,9 +452,9 @@ public class Runtime { * Executes the specified command and arguments in a separate process. * *

                                  This is a convenience method. An invocation of the form - * exec(cmdarray) + * {@code exec(cmdarray)} * behaves in exactly the same way as the invocation - * {@link #exec(String[], String[], File) exec}(cmdarray, null, null). + * {@link #exec(String[], String[], File) exec}{@code (cmdarray, null, null)}. * * @param cmdarray array containing the command to call and * its arguments. @@ -472,12 +470,12 @@ public class Runtime { * If an I/O error occurs * * @throws NullPointerException - * If cmdarray is null, - * or one of the elements of cmdarray is null + * If {@code cmdarray} is {@code null}, + * or one of the elements of {@code cmdarray} is {@code null} * * @throws IndexOutOfBoundsException - * If cmdarray is an empty array - * (has length 0) + * If {@code cmdarray} is an empty array + * (has length {@code 0}) * * @see ProcessBuilder */ @@ -490,9 +488,9 @@ public class Runtime { * with the specified environment. * *

                                  This is a convenience method. An invocation of the form - * exec(cmdarray, envp) + * {@code exec(cmdarray, envp)} * behaves in exactly the same way as the invocation - * {@link #exec(String[], String[], File) exec}(cmdarray, envp, null). + * {@link #exec(String[], String[], File) exec}{@code (cmdarray, envp, null)}. * * @param cmdarray array containing the command to call and * its arguments. @@ -500,7 +498,7 @@ public class Runtime { * @param envp array of strings, each element of which * has environment variable settings in the format * name=value, or - * null if the subprocess should inherit + * {@code null} if the subprocess should inherit * the environment of the current process. * * @return A new {@link Process} object for managing the subprocess @@ -514,13 +512,13 @@ public class Runtime { * If an I/O error occurs * * @throws NullPointerException - * If cmdarray is null, - * or one of the elements of cmdarray is null, - * or one of the elements of envp is null + * If {@code cmdarray} is {@code null}, + * or one of the elements of {@code cmdarray} is {@code null}, + * or one of the elements of {@code envp} is {@code null} * * @throws IndexOutOfBoundsException - * If cmdarray is an empty array - * (has length 0) + * If {@code cmdarray} is an empty array + * (has length {@code 0}) * * @see ProcessBuilder */ @@ -533,17 +531,17 @@ public class Runtime { * Executes the specified command and arguments in a separate process with * the specified environment and working directory. * - *

                                  Given an array of strings cmdarray, representing the - * tokens of a command line, and an array of strings envp, + *

                                  Given an array of strings {@code cmdarray}, representing the + * tokens of a command line, and an array of strings {@code envp}, * representing "environment" variable settings, this method creates * a new process in which to execute the specified command. * - *

                                  This method checks that cmdarray is a valid operating + *

                                  This method checks that {@code cmdarray} is a valid operating * system command. Which commands are valid is system-dependent, * but at the very least the command must be a non-empty list of * non-null strings. * - *

                                  If envp is null, the subprocess inherits the + *

                                  If {@code envp} is {@code null}, the subprocess inherits the * environment settings of the current process. * *

                                  A minimal set of system dependent environment variables may @@ -554,14 +552,14 @@ public class Runtime { *

                                  {@link ProcessBuilder#start()} is now the preferred way to * start a process with a modified environment. * - *

                                  The working directory of the new subprocess is specified by dir. - * If dir is null, the subprocess inherits the + *

                                  The working directory of the new subprocess is specified by {@code dir}. + * If {@code dir} is {@code null}, the subprocess inherits the * current working directory of the current process. * *

                                  If a security manager exists, its * {@link SecurityManager#checkExec checkExec} * method is invoked with the first component of the array - * cmdarray as its argument. This may result in a + * {@code cmdarray} as its argument. This may result in a * {@link SecurityException} being thrown. * *

                                  Starting an operating system process is highly system-dependent. @@ -586,11 +584,11 @@ public class Runtime { * @param envp array of strings, each element of which * has environment variable settings in the format * name=value, or - * null if the subprocess should inherit + * {@code null} if the subprocess should inherit * the environment of the current process. * * @param dir the working directory of the subprocess, or - * null if the subprocess should inherit + * {@code null} if the subprocess should inherit * the working directory of the current process. * * @return A new {@link Process} object for managing the subprocess @@ -607,13 +605,13 @@ public class Runtime { * If an I/O error occurs * * @throws NullPointerException - * If cmdarray is null, - * or one of the elements of cmdarray is null, - * or one of the elements of envp is null + * If {@code cmdarray} is {@code null}, + * or one of the elements of {@code cmdarray} is {@code null}, + * or one of the elements of {@code envp} is {@code null} * * @throws IndexOutOfBoundsException - * If cmdarray is an empty array - * (has length 0) + * If {@code cmdarray} is an empty array + * (has length {@code 0}) * * @see ProcessBuilder * @since 1.3 @@ -643,8 +641,8 @@ public class Runtime { /** * Returns the amount of free memory in the Java Virtual Machine. * Calling the - * gc method may result in increasing the value returned - * by freeMemory. + * {@code gc} method may result in increasing the value returned + * by {@code freeMemory.} * * @return an approximation to the total amount of memory currently * available for future allocated objects, measured in bytes. @@ -665,9 +663,9 @@ public class Runtime { public native long totalMemory(); /** - * Returns the maximum amount of memory that the Java virtual machine will - * attempt to use. If there is no inherent limit then the value {@link - * java.lang.Long#MAX_VALUE} will be returned. + * Returns the maximum amount of memory that the Java virtual machine + * will attempt to use. If there is no inherent limit then the value + * {@link java.lang.Long#MAX_VALUE} will be returned. * * @return the maximum amount of memory that the virtual machine will * attempt to use, measured in bytes @@ -683,10 +681,10 @@ public class Runtime { * returns from the method call, the virtual machine has made * its best effort to recycle all discarded objects. *

                                  - * The name gc stands for "garbage + * The name {@code gc} stands for "garbage * collector". The virtual machine performs this recycling * process automatically as needed, in a separate thread, even if the - * gc method is not invoked explicitly. + * {@code gc} method is not invoked explicitly. *

                                  * The method {@link System#gc()} is the conventional and convenient * means of invoking this method. @@ -699,15 +697,15 @@ public class Runtime { /** * Runs the finalization methods of any objects pending finalization. * Calling this method suggests that the Java virtual machine expend - * effort toward running the finalize methods of objects - * that have been found to be discarded but whose finalize + * effort toward running the {@code finalize} methods of objects + * that have been found to be discarded but whose {@code finalize} * methods have not yet been run. When control returns from the * method call, the virtual machine has made a best effort to * complete all outstanding finalizations. *

                                  * The virtual machine performs the finalization process * automatically as needed, in a separate thread, if the - * runFinalization method is not invoked explicitly. + * {@code runFinalization} method is not invoked explicitly. *

                                  * The method {@link System#runFinalization()} is the conventional * and convenient means of invoking this method. @@ -720,7 +718,7 @@ public class Runtime { /** * Enables/Disables tracing of instructions. - * If the boolean argument is true, this + * If the {@code boolean} argument is {@code true}, this * method suggests that the Java virtual machine emit debugging * information for each instruction in the virtual machine as it * is executed. The format of this information, and the file or other @@ -729,18 +727,18 @@ public class Runtime { * this feature. The destination of the trace output is system * dependent. *

                                  - * If the boolean argument is false, this + * If the {@code boolean} argument is {@code false}, this * method causes the virtual machine to stop performing the * detailed instruction trace it is performing. * - * @param on true to enable instruction tracing; - * false to disable this feature. + * @param on {@code true} to enable instruction tracing; + * {@code false} to disable this feature. */ public void traceInstructions(boolean on) { } /** * Enables/Disables tracing of method calls. - * If the boolean argument is true, this + * If the {@code boolean} argument is {@code true}, this * method suggests that the Java virtual machine emit debugging * information for each method in the virtual machine as it is * called. The format of this information, and the file or other output @@ -751,8 +749,8 @@ public class Runtime { * Calling this method with argument false suggests that the * virtual machine cease emitting per-call debugging information. * - * @param on true to enable instruction tracing; - * false to disable this feature. + * @param on {@code true} to enable instruction tracing; + * {@code false} to disable this feature. */ public void traceMethodCalls(boolean on) { } @@ -760,7 +758,7 @@ public class Runtime { * Loads the native library specified by the filename argument. The filename * argument must be an absolute path name. * (for example - * Runtime.getRuntime().load("/home/avh/lib/libX11.so");). + * {@code Runtime.getRuntime().load("/home/avh/lib/libX11.so");}). * * If the filename argument, when stripped of any platform-specific library * prefix, path, and file extension, indicates a library whose name is, @@ -773,8 +771,8 @@ public class Runtime { * Otherwise, the filename argument is mapped to a native library image in * an implementation-dependent manner. *

                                  - * First, if there is a security manager, its checkLink - * method is called with the filename as its argument. + * First, if there is a security manager, its {@code checkLink} + * method is called with the {@code filename} as its argument. * This may result in a security exception. *

                                  * This is similar to the method {@link #loadLibrary(String)}, but it @@ -786,14 +784,14 @@ public class Runtime { * * @param filename the file to load. * @exception SecurityException if a security manager exists and its - * checkLink method doesn't allow + * {@code checkLink} method doesn't allow * loading of the specified dynamic library * @exception UnsatisfiedLinkError if either the filename is not an * absolute path name, the native library is not statically * linked with the VM, or the library cannot be mapped to * a native library image by the host system. - * @exception NullPointerException if filename is - * null + * @exception NullPointerException if {@code filename} is + * {@code null} * @see java.lang.Runtime#getRuntime() * @see java.lang.SecurityException * @see java.lang.SecurityManager#checkLink(java.lang.String) @@ -816,26 +814,26 @@ public class Runtime { } /** - * Loads the native library specified by the libname - * argument. The libname argument must not contain any platform + * Loads the native library specified by the {@code libname} + * argument. The {@code libname} argument must not contain any platform * specific prefix, file extension or path. If a native library - * called libname is statically linked with the VM, then the - * JNI_OnLoad_libname function exported by the library is invoked. + * called {@code libname} is statically linked with the VM, then the + * JNI_OnLoad_{@code libname} function exported by the library is invoked. * See the JNI Specification for more details. * * Otherwise, the libname argument is loaded from a system library * location and mapped to a native library image in an implementation- * dependent manner. *

                                  - * First, if there is a security manager, its checkLink - * method is called with the libname as its argument. + * First, if there is a security manager, its {@code checkLink} + * method is called with the {@code libname} as its argument. * This may result in a security exception. *

                                  * The method {@link System#loadLibrary(String)} is the conventional * and convenient means of invoking this method. If native * methods are to be used in the implementation of a class, a standard * strategy is to put the native code in a library file (call it - * LibFile) and then to put a static initializer: + * {@code LibFile}) and then to put a static initializer: *

                                        * static { System.loadLibrary("LibFile"); }
                                        * 
                                  @@ -848,14 +846,14 @@ public class Runtime { * * @param libname the name of the library. * @exception SecurityException if a security manager exists and its - * checkLink method doesn't allow + * {@code checkLink} method doesn't allow * loading of the specified dynamic library * @exception UnsatisfiedLinkError if either the libname argument * contains a file path, the native library is not statically * linked with the VM, or the library cannot be mapped to a * native library image by the host system. - * @exception NullPointerException if libname is - * null + * @exception NullPointerException if {@code libname} is + * {@code null} * @see java.lang.SecurityException * @see java.lang.SecurityManager#checkLink(java.lang.String) */ @@ -878,7 +876,7 @@ public class Runtime { /** * Creates a localized version of an input stream. This method takes - * an InputStream and returns an InputStream + * an {@code InputStream} and returns an {@code InputStream} * equivalent to the argument in all respects except that it is * localized: as characters in the local character set are read from * the stream, they are automatically converted from the local @@ -894,7 +892,7 @@ public class Runtime { * @see java.io.InputStreamReader#InputStreamReader(java.io.InputStream) * @deprecated As of JDK 1.1, the preferred way to translate a byte * stream in the local encoding into a character stream in Unicode is via - * the InputStreamReader and BufferedReader + * the {@code InputStreamReader} and {@code BufferedReader} * classes. */ @Deprecated @@ -904,8 +902,8 @@ public class Runtime { /** * Creates a localized version of an output stream. This method - * takes an OutputStream and returns an - * OutputStream equivalent to the argument in all respects + * takes an {@code OutputStream} and returns an + * {@code OutputStream} equivalent to the argument in all respects * except that it is localized: as Unicode characters are written to * the stream, they are automatically converted to the local * character set. @@ -915,8 +913,8 @@ public class Runtime { * * @deprecated As of JDK 1.1, the preferred way to translate a * Unicode character stream into a byte stream in the local encoding is via - * the OutputStreamWriter, BufferedWriter, and - * PrintWriter classes. + * the {@code OutputStreamWriter}, {@code BufferedWriter}, and + * {@code PrintWriter} classes. * * @param out OutputStream to localize * @return a localized output stream diff --git a/jdk/src/java.base/share/classes/java/lang/SecurityManager.java b/jdk/src/java.base/share/classes/java/lang/SecurityManager.java index 1714cf03b23..7f1e90d6c04 100644 --- a/jdk/src/java.base/share/classes/java/lang/SecurityManager.java +++ b/jdk/src/java.base/share/classes/java/lang/SecurityManager.java @@ -1455,7 +1455,7 @@ class SecurityManager { if (!packageAccessValid) { String tmpPropertyStr = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public String run() { return java.security.Security.getProperty( "package.access"); @@ -1524,7 +1524,7 @@ class SecurityManager { if (!packageDefinitionValid) { String tmpPropertyStr = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public String run() { return java.security.Security.getProperty( "package.definition"); diff --git a/jdk/src/java.base/share/classes/java/lang/StringBuffer.java b/jdk/src/java.base/share/classes/java/lang/StringBuffer.java index a53c7c4c2bb..80d6718399f 100644 --- a/jdk/src/java.base/share/classes/java/lang/StringBuffer.java +++ b/jdk/src/java.base/share/classes/java/lang/StringBuffer.java @@ -206,6 +206,7 @@ import java.util.Arrays; } /** + * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ @Override @@ -214,6 +215,7 @@ import java.util.Arrays; } /** + * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ @Override @@ -222,6 +224,7 @@ import java.util.Arrays; } /** + * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ @Override @@ -230,6 +233,7 @@ import java.util.Arrays; } /** + * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ @Override diff --git a/jdk/src/java.base/share/classes/java/lang/System.java b/jdk/src/java.base/share/classes/java/lang/System.java index ee6588491f9..699467ca5a4 100644 --- a/jdk/src/java.base/share/classes/java/lang/System.java +++ b/jdk/src/java.base/share/classes/java/lang/System.java @@ -309,7 +309,7 @@ public final class System { // calls the installed security manager's checkPermission method // which will loop infinitely if there is a non-system class // (in this case: the new security manager class) on the stack). - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public Object run() { s.getClass().getProtectionDomain().implies (SecurityConstants.ALL_PERMISSION); diff --git a/jdk/src/java.base/share/classes/java/lang/Thread.java b/jdk/src/java.base/share/classes/java/lang/Thread.java index e7477416ecb..af2a2a2b049 100644 --- a/jdk/src/java.base/share/classes/java/lang/Thread.java +++ b/jdk/src/java.base/share/classes/java/lang/Thread.java @@ -1661,7 +1661,7 @@ class Thread implements Runnable { */ private static boolean auditSubclass(final Class subcl) { Boolean result = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public Boolean run() { for (Class cl = subcl; cl != Thread.class; diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/InfoFromMemberName.java b/jdk/src/java.base/share/classes/java/lang/invoke/InfoFromMemberName.java index 0ecd005a8d3..6e9e1de81ee 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/InfoFromMemberName.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/InfoFromMemberName.java @@ -87,7 +87,7 @@ class InfoFromMemberName implements MethodHandleInfo { // For more information see comments on {@link MethodHandleNatives#linkMethod}. throw new IllegalArgumentException("cannot reflect signature polymorphic method"); } - Member mem = AccessController.doPrivileged(new PrivilegedAction() { + Member mem = AccessController.doPrivileged(new PrivilegedAction<>() { public Member run() { try { return reflectUnchecked(); diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java b/jdk/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java index 421db68b464..69d80ec0e61 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java @@ -194,7 +194,7 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*; final Class innerClass = spinInnerClass(); if (invokedType.parameterCount() == 0) { final Constructor[] ctrs = AccessController.doPrivileged( - new PrivilegedAction[]>() { + new PrivilegedAction<>() { @Override public Constructor[] run() { Constructor[] ctrs = innerClass.getDeclaredConstructors(); @@ -311,7 +311,7 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*; // If requested, dump out to a file for debugging purposes if (dumper != null) { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { @Override public Void run() { dumper.dumpClass(lambdaClassName, classBytes); diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java b/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java index a29eed9417a..b44f9adf62f 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java @@ -167,7 +167,7 @@ class InvokerBytecodeGenerator { static void maybeDump(final String className, final byte[] classFile) { if (DUMP_CLASS_FILES) { java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public Void run() { try { String dumpName = className; diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java b/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java index 5c441071b92..09a742f55ec 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java @@ -631,7 +631,7 @@ class LambdaForm { * as a sort of pre-invocation linkage step.) */ public void prepare() { - if (COMPILE_THRESHOLD == 0) { + if (COMPILE_THRESHOLD == 0 && !isCompiled) { compileToBytecode(); } if (this.vmentry != null) { @@ -645,11 +645,11 @@ class LambdaForm { /** Generate optimizable bytecode for this form. */ MemberName compileToBytecode() { - MethodType invokerType = methodType(); - assert(vmentry == null || vmentry.getMethodType().basicType().equals(invokerType)); if (vmentry != null && isCompiled) { return vmentry; // already compiled somehow } + MethodType invokerType = methodType(); + assert(vmentry == null || vmentry.getMethodType().basicType().equals(invokerType)); try { vmentry = InvokerBytecodeGenerator.generateCustomizedCode(this, invokerType); if (TRACE_INTERPRETER) diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java index 57568ece696..c138676a8fb 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java @@ -51,7 +51,7 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; private static final int MAX_ARITY; static { final Object[] values = { 255 }; - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { @Override public Void run() { values[0] = Integer.getInteger(MethodHandleImpl.class.getName()+".MAX_ARITY", 255); @@ -1234,7 +1234,7 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; private static final byte[] T_BYTES; static { final Object[] values = {null}; - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public Void run() { try { Class tClass = T.class; diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleProxies.java b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleProxies.java index 1167eeb4a2b..37373de1a59 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleProxies.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleProxies.java @@ -199,7 +199,7 @@ public class MethodHandleProxies { // sun.invoke.WrapperInstance is a restricted interface not accessible // by any non-null class loader. final ClassLoader loader = proxyLoader; - proxy = AccessController.doPrivileged(new PrivilegedAction() { + proxy = AccessController.doPrivileged(new PrivilegedAction<>() { public Object run() { return Proxy.newProxyInstance( loader, diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleStatics.java b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleStatics.java index 144de11094f..092a5135879 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleStatics.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleStatics.java @@ -53,7 +53,7 @@ import sun.misc.Unsafe; static { final Object[] values = new Object[9]; - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public Void run() { values[0] = Boolean.getBoolean("java.lang.invoke.MethodHandle.DEBUG_NAMES"); values[1] = Boolean.getBoolean("java.lang.invoke.MethodHandle.DUMP_CLASS_FILES"); diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/ProxyClassesDumper.java b/jdk/src/java.base/share/classes/java/lang/invoke/ProxyClassesDumper.java index 463f1ff286c..3f143765925 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/ProxyClassesDumper.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/ProxyClassesDumper.java @@ -64,7 +64,7 @@ final class ProxyClassesDumper { try { path = path.trim(); final Path dir = Paths.get(path.length() == 0 ? "." : path); - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { @Override public Void run() { validateDumpDir(dir); diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/SerializedLambda.java b/jdk/src/java.base/share/classes/java/lang/invoke/SerializedLambda.java index e6412012721..d9f94f39e77 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/SerializedLambda.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/SerializedLambda.java @@ -218,7 +218,7 @@ public final class SerializedLambda implements Serializable { private Object readResolve() throws ReflectiveOperationException { try { - Method deserialize = AccessController.doPrivileged(new PrivilegedExceptionAction() { + Method deserialize = AccessController.doPrivileged(new PrivilegedExceptionAction<>() { @Override public Method run() throws Exception { Method m = capturingClass.getDeclaredMethod("$deserializeLambda$", SerializedLambda.class); diff --git a/jdk/src/java.base/share/classes/java/lang/ref/Finalizer.java b/jdk/src/java.base/share/classes/java/lang/ref/Finalizer.java index 6ae2262c5aa..d9cabe61543 100644 --- a/jdk/src/java.base/share/classes/java/lang/ref/Finalizer.java +++ b/jdk/src/java.base/share/classes/java/lang/ref/Finalizer.java @@ -28,6 +28,7 @@ package java.lang.ref; import java.security.PrivilegedAction; import java.security.AccessController; import sun.misc.JavaLangAccess; +import sun.misc.ManagedLocalsThread; import sun.misc.SharedSecrets; import sun.misc.VM; @@ -120,13 +121,13 @@ final class Finalizer extends FinalReference { /* Package-private; must */ private static void forkSecondaryFinalizer(final Runnable proc) { AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public Void run() { ThreadGroup tg = Thread.currentThread().getThreadGroup(); for (ThreadGroup tgn = tg; tgn != null; tg = tgn, tgn = tg.getParent()); - Thread sft = new Thread(tg, proc, "Secondary finalizer"); + Thread sft = new ManagedLocalsThread(tg, proc, "Secondary finalizer"); sft.start(); try { sft.join(); @@ -185,7 +186,7 @@ final class Finalizer extends FinalReference { /* Package-private; must }}}); } - private static class FinalizerThread extends Thread { + private static class FinalizerThread extends ManagedLocalsThread { private volatile boolean running; FinalizerThread(ThreadGroup g) { super(g, "Finalizer"); diff --git a/jdk/src/java.base/share/classes/java/lang/ref/Reference.java b/jdk/src/java.base/share/classes/java/lang/ref/Reference.java index 5febcae0299..2bab588f1f4 100644 --- a/jdk/src/java.base/share/classes/java/lang/ref/Reference.java +++ b/jdk/src/java.base/share/classes/java/lang/ref/Reference.java @@ -27,6 +27,7 @@ package java.lang.ref; import sun.misc.Cleaner; import sun.misc.JavaLangRefAccess; +import sun.misc.ManagedLocalsThread; import sun.misc.SharedSecrets; /** @@ -126,7 +127,7 @@ public abstract class Reference { /* High-priority thread to enqueue pending References */ - private static class ReferenceHandler extends Thread { + private static class ReferenceHandler extends ManagedLocalsThread { private static void ensureClassInitialized(Class clazz) { try { diff --git a/jdk/src/java.base/share/classes/java/lang/reflect/Proxy.java b/jdk/src/java.base/share/classes/java/lang/reflect/Proxy.java index 34f0d4c3c01..99b39ce9c76 100644 --- a/jdk/src/java.base/share/classes/java/lang/reflect/Proxy.java +++ b/jdk/src/java.base/share/classes/java/lang/reflect/Proxy.java @@ -728,7 +728,7 @@ public class Proxy implements java.io.Serializable { final Constructor cons = cl.getConstructor(constructorParams); if (!Modifier.isPublic(cl.getModifiers())) { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public Void run() { cons.setAccessible(true); return null; diff --git a/jdk/src/java.base/share/classes/java/net/AbstractPlainDatagramSocketImpl.java b/jdk/src/java.base/share/classes/java/net/AbstractPlainDatagramSocketImpl.java index 0ffe37f8d9f..1331df397d2 100644 --- a/jdk/src/java.base/share/classes/java/net/AbstractPlainDatagramSocketImpl.java +++ b/jdk/src/java.base/share/classes/java/net/AbstractPlainDatagramSocketImpl.java @@ -62,7 +62,7 @@ abstract class AbstractPlainDatagramSocketImpl extends DatagramSocketImpl */ static { java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public Void run() { System.loadLibrary("net"); return null; diff --git a/jdk/src/java.base/share/classes/java/net/AbstractPlainSocketImpl.java b/jdk/src/java.base/share/classes/java/net/AbstractPlainSocketImpl.java index 2220533459b..b611273f958 100644 --- a/jdk/src/java.base/share/classes/java/net/AbstractPlainSocketImpl.java +++ b/jdk/src/java.base/share/classes/java/net/AbstractPlainSocketImpl.java @@ -79,7 +79,7 @@ abstract class AbstractPlainSocketImpl extends SocketImpl */ static { java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public Void run() { System.loadLibrary("net"); return null; diff --git a/jdk/src/java.base/share/classes/java/net/CookieManager.java b/jdk/src/java.base/share/classes/java/net/CookieManager.java index 4dbc9aa2dfa..74216eb4de0 100644 --- a/jdk/src/java.base/share/classes/java/net/CookieManager.java +++ b/jdk/src/java.base/share/classes/java/net/CookieManager.java @@ -201,14 +201,13 @@ public class CookieManager extends CookieHandler throw new IllegalArgumentException("Argument is null"); } - Map> cookieMap = - new java.util.HashMap>(); + Map> cookieMap = new java.util.HashMap<>(); // if there's no default CookieStore, no way for us to get any cookie if (cookieJar == null) return Collections.unmodifiableMap(cookieMap); boolean secureLink = "https".equalsIgnoreCase(uri.getScheme()); - List cookies = new java.util.ArrayList(); + List cookies = new java.util.ArrayList<>(); String path = uri.getPath(); if (path == null || path.isEmpty()) { path = "/"; @@ -411,7 +410,7 @@ public class CookieManager extends CookieHandler private List sortByPath(List cookies) { Collections.sort(cookies, new CookiePathComparator()); - List cookieHeader = new java.util.ArrayList(); + List cookieHeader = new java.util.ArrayList<>(); for (HttpCookie cookie : cookies) { // Netscape cookie spec and RFC 2965 have different format of Cookie // header; RFC 2965 requires a leading $Version="1" string while Netscape diff --git a/jdk/src/java.base/share/classes/java/net/DatagramPacket.java b/jdk/src/java.base/share/classes/java/net/DatagramPacket.java index eb8e4000173..2fb419db282 100644 --- a/jdk/src/java.base/share/classes/java/net/DatagramPacket.java +++ b/jdk/src/java.base/share/classes/java/net/DatagramPacket.java @@ -47,7 +47,7 @@ class DatagramPacket { */ static { java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public Void run() { System.loadLibrary("net"); return null; diff --git a/jdk/src/java.base/share/classes/java/net/DatagramSocket.java b/jdk/src/java.base/share/classes/java/net/DatagramSocket.java index 77a12f247a0..f2120eaef04 100644 --- a/jdk/src/java.base/share/classes/java/net/DatagramSocket.java +++ b/jdk/src/java.base/share/classes/java/net/DatagramSocket.java @@ -308,7 +308,7 @@ class DatagramSocket implements java.io.Closeable { // getDeclaredMethod, therefore we need permission to access the member try { AccessController.doPrivileged( - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public Void run() throws NoSuchMethodException { Class[] cl = new Class[1]; cl[0] = DatagramPacket.class; diff --git a/jdk/src/java.base/share/classes/java/net/HttpConnectSocketImpl.java b/jdk/src/java.base/share/classes/java/net/HttpConnectSocketImpl.java index b6e70cafd94..eb6eb13a8bb 100644 --- a/jdk/src/java.base/share/classes/java/net/HttpConnectSocketImpl.java +++ b/jdk/src/java.base/share/classes/java/net/HttpConnectSocketImpl.java @@ -64,7 +64,7 @@ import java.util.Set; serverSocketField = netClientClazz.getDeclaredField("serverSocket"); java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public Void run() { httpField.setAccessible(true); serverSocketField.setAccessible(true); @@ -146,7 +146,7 @@ import java.util.Set; { try { return java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { + new java.security.PrivilegedExceptionAction<>() { public Socket run() throws IOException { return doTunnel(urlString, timeout); } diff --git a/jdk/src/java.base/share/classes/java/net/HttpCookie.java b/jdk/src/java.base/share/classes/java/net/HttpCookie.java index ff6f0ab70a9..92dcd68c0b5 100644 --- a/jdk/src/java.base/share/classes/java/net/HttpCookie.java +++ b/jdk/src/java.base/share/classes/java/net/HttpCookie.java @@ -1125,7 +1125,7 @@ public final class HttpCookie implements Cloneable { * @return list of strings; never null */ private static List splitMultiCookies(String header) { - List cookies = new java.util.ArrayList(); + List cookies = new java.util.ArrayList<>(); int quoteCount = 0; int p, q; diff --git a/jdk/src/java.base/share/classes/java/net/IDN.java b/jdk/src/java.base/share/classes/java/net/IDN.java index d4c8f5e426d..5d3ae15dc62 100644 --- a/jdk/src/java.base/share/classes/java/net/IDN.java +++ b/jdk/src/java.base/share/classes/java/net/IDN.java @@ -228,7 +228,7 @@ public final class IDN { try { final String IDN_PROFILE = "uidna.spp"; if (System.getSecurityManager() != null) { - stream = AccessController.doPrivileged(new PrivilegedAction() { + stream = AccessController.doPrivileged(new PrivilegedAction<>() { public InputStream run() { return StringPrep.class.getResourceAsStream(IDN_PROFILE); } diff --git a/jdk/src/java.base/share/classes/java/net/InMemoryCookieStore.java b/jdk/src/java.base/share/classes/java/net/InMemoryCookieStore.java index 487c9eb2a89..a08be4a1c2c 100644 --- a/jdk/src/java.base/share/classes/java/net/InMemoryCookieStore.java +++ b/jdk/src/java.base/share/classes/java/net/InMemoryCookieStore.java @@ -62,9 +62,9 @@ class InMemoryCookieStore implements CookieStore { * The default ctor */ public InMemoryCookieStore() { - cookieJar = new ArrayList(); - domainIndex = new HashMap>(); - uriIndex = new HashMap>(); + cookieJar = new ArrayList<>(); + domainIndex = new HashMap<>(); + uriIndex = new HashMap<>(); lock = new ReentrantLock(false); } @@ -115,7 +115,7 @@ class InMemoryCookieStore implements CookieStore { throw new NullPointerException("uri is null"); } - List cookies = new ArrayList(); + List cookies = new ArrayList<>(); boolean secureLink = "https".equalsIgnoreCase(uri.getScheme()); lock.lock(); try { @@ -157,7 +157,7 @@ class InMemoryCookieStore implements CookieStore { * of this cookie store. */ public List getURIs() { - List uris = new ArrayList(); + List uris = new ArrayList<>(); lock.lock(); try { @@ -281,7 +281,7 @@ class InMemoryCookieStore implements CookieStore { String host, boolean secureLink) { // Use a separate list to handle cookies that need to be removed so // that there is no conflict with iterators. - ArrayList toRemove = new ArrayList(); + ArrayList toRemove = new ArrayList<>(); for (Map.Entry> entry : cookieIndex.entrySet()) { String domain = entry.getKey(); List lst = entry.getValue(); @@ -368,7 +368,7 @@ class InMemoryCookieStore implements CookieStore { cookies.add(cookie); } else { - cookies = new ArrayList(); + cookies = new ArrayList<>(); cookies.add(cookie); indexStore.put(index, cookies); } diff --git a/jdk/src/java.base/share/classes/java/net/InetAddress.java b/jdk/src/java.base/share/classes/java/net/InetAddress.java index eb72c091285..b39fa5dc2d6 100644 --- a/jdk/src/java.base/share/classes/java/net/InetAddress.java +++ b/jdk/src/java.base/share/classes/java/net/InetAddress.java @@ -270,7 +270,7 @@ class InetAddress implements java.io.Serializable { preferIPv6Address = java.security.AccessController.doPrivileged( new GetBooleanAction("java.net.preferIPv6Addresses")).booleanValue(); AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public Void run() { System.loadLibrary("net"); return null; @@ -852,7 +852,7 @@ class InetAddress implements java.io.Serializable { final String providerName = provider; try { nameService = java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { + new java.security.PrivilegedExceptionAction<>() { public NameService run() { Iterator itr = ServiceLoader.load(NameServiceDescriptor.class) @@ -892,7 +892,7 @@ class InetAddress implements java.io.Serializable { String provider = null;; String propPrefix = "sun.net.spi.nameservice.provider."; int n = 1; - nameServices = new ArrayList(); + nameServices = new ArrayList<>(); provider = AccessController.doPrivileged( new GetPropertyAction(propPrefix + n)); while (provider != null) { diff --git a/jdk/src/java.base/share/classes/java/net/NetworkInterface.java b/jdk/src/java.base/share/classes/java/net/NetworkInterface.java index 411d8df14b9..3376bafdf20 100644 --- a/jdk/src/java.base/share/classes/java/net/NetworkInterface.java +++ b/jdk/src/java.base/share/classes/java/net/NetworkInterface.java @@ -54,7 +54,7 @@ public final class NetworkInterface { static { AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public Void run() { System.loadLibrary("net"); return null; @@ -167,7 +167,7 @@ public final class NetworkInterface { * @since 1.6 */ public java.util.List getInterfaceAddresses() { - java.util.List lst = new java.util.ArrayList(1); + java.util.List lst = new java.util.ArrayList<>(1); SecurityManager sec = System.getSecurityManager(); for (int j=0; j() { + return new Enumeration<>() { private int i = 0; public NetworkInterface nextElement() { if (netifs != null && i < netifs.length) { diff --git a/jdk/src/java.base/share/classes/java/net/ProtocolException.java b/jdk/src/java.base/share/classes/java/net/ProtocolException.java index 828636e8461..e2bd4111cc1 100644 --- a/jdk/src/java.base/share/classes/java/net/ProtocolException.java +++ b/jdk/src/java.base/share/classes/java/net/ProtocolException.java @@ -42,10 +42,10 @@ class ProtocolException extends IOException { * Constructs a new {@code ProtocolException} with the * specified detail message. * - * @param host the detail message. + * @param message the detail message. */ - public ProtocolException(String host) { - super(host); + public ProtocolException(String message) { + super(message); } /** diff --git a/jdk/src/java.base/share/classes/java/net/Socket.java b/jdk/src/java.base/share/classes/java/net/Socket.java index a0ca24e5224..a94d2ef9994 100644 --- a/jdk/src/java.base/share/classes/java/net/Socket.java +++ b/jdk/src/java.base/share/classes/java/net/Socket.java @@ -470,7 +470,7 @@ class Socket implements java.io.Closeable { // getDeclaredMethod, therefore we need permission to access the member oldImpl = AccessController.doPrivileged - (new PrivilegedAction() { + (new PrivilegedAction<>() { public Boolean run() { Class clazz = impl.getClass(); while (true) { @@ -911,7 +911,7 @@ class Socket implements java.io.Closeable { InputStream is = null; try { is = AccessController.doPrivileged( - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public InputStream run() throws IOException { return impl.getInputStream(); } @@ -951,7 +951,7 @@ class Socket implements java.io.Closeable { OutputStream os = null; try { os = AccessController.doPrivileged( - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public OutputStream run() throws IOException { return impl.getOutputStream(); } diff --git a/jdk/src/java.base/share/classes/java/net/SocketPermission.java b/jdk/src/java.base/share/classes/java/net/SocketPermission.java index 8894152512b..52c71b0f7a3 100644 --- a/jdk/src/java.base/share/classes/java/net/SocketPermission.java +++ b/jdk/src/java.base/share/classes/java/net/SocketPermission.java @@ -1194,7 +1194,7 @@ public final class SocketPermission extends Permission */ private static int initEphemeralPorts(String suffix, int defval) { return AccessController.doPrivileged( - new PrivilegedAction(){ + new PrivilegedAction<>(){ public Integer run() { int val = Integer.getInteger( "jdk.net.ephemeralPortRange."+suffix, -1 @@ -1328,7 +1328,7 @@ final class SocketPermissionCollection extends PermissionCollection */ public SocketPermissionCollection() { - perms = new ArrayList(); + perms = new ArrayList<>(); } /** @@ -1466,7 +1466,7 @@ final class SocketPermissionCollection extends PermissionCollection // Get the one we want @SuppressWarnings("unchecked") Vector permissions = (Vector)gfields.get("permissions", null); - perms = new ArrayList(permissions.size()); + perms = new ArrayList<>(permissions.size()); perms.addAll(permissions); } } diff --git a/jdk/src/java.base/share/classes/java/net/SocksSocketImpl.java b/jdk/src/java.base/share/classes/java/net/SocksSocketImpl.java index 3dd4259cd9a..573945b9632 100644 --- a/jdk/src/java.base/share/classes/java/net/SocksSocketImpl.java +++ b/jdk/src/java.base/share/classes/java/net/SocksSocketImpl.java @@ -82,7 +82,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { { try { AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { + new java.security.PrivilegedExceptionAction<>() { public Void run() throws IOException { superConnectServer(host, port, timeout); cmdIn = getInputStream(); @@ -157,7 +157,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { final InetAddress addr = InetAddress.getByName(server); PasswordAuthentication pw = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public PasswordAuthentication run() { return Authenticator.requestPasswordAuthentication( server, addr, serverPort, "SOCKS5", "SOCKS authentication", null); @@ -351,7 +351,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { // server is not null only when the socket was created with a // specified proxy in which case it does bypass the ProxySelector ProxySelector sel = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public ProxySelector run() { return ProxySelector.getDefault(); } @@ -595,7 +595,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { InetAddress naddr = baddr; if (naddr.isAnyLocalAddress()) { naddr = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public InetAddress run() { return cmdsock.getLocalAddress(); @@ -671,7 +671,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { // server is not null only when the socket was created with a // specified proxy in which case it does bypass the ProxySelector ProxySelector sel = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public ProxySelector run() { return ProxySelector.getDefault(); } @@ -724,7 +724,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { // Connects to the SOCKS server try { AccessController.doPrivileged( - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public Void run() throws Exception { cmdsock = new Socket(new PlainSocketImpl()); cmdsock.connect(new InetSocketAddress(server, serverPort)); @@ -755,7 +755,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts { } else { try { AccessController.doPrivileged( - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public Void run() throws Exception { cmdsock = new Socket(new PlainSocketImpl()); cmdsock.connect(new InetSocketAddress(server, serverPort)); diff --git a/jdk/src/java.base/share/classes/java/net/URL.java b/jdk/src/java.base/share/classes/java/net/URL.java index fc7ecb513bb..1a32a236ba0 100644 --- a/jdk/src/java.base/share/classes/java/net/URL.java +++ b/jdk/src/java.base/share/classes/java/net/URL.java @@ -268,6 +268,23 @@ public final class URL implements java.io.Serializable { * createURLStreamHandler} method of each provider, if instantiated, is * invoked, with the protocol string, until a provider returns non-null, * or all providers have been exhausted. + *
                                • If the previous step fails to find a protocol handler, the + * constructor reads the value of the system property: + *
                                  {@code + * java.protocol.handler.pkgs + * }
                                  + * If the value of that system property is not {@code null}, + * it is interpreted as a list of packages separated by a vertical + * slash character '{@code |}'. The constructor tries to load + * the class named: + *
                                  {@code + * ..Handler + * }
                                  + * where {@code } is replaced by the name of the package + * and {@code } is replaced by the name of the protocol. + * If this class does not exist, or if the class exists but it is not + * a subclass of {@code URLStreamHandler}, then the next package + * in the list is tried. *
                                • If the previous step fails to find a protocol handler, then the * constructor tries to load a built-in protocol handler. * If this class does not exist, or if the class exists but it is not a @@ -1139,8 +1156,41 @@ public final class URL implements java.io.Serializable { } } + private static URLStreamHandler lookupViaProperty(String protocol) { + String packagePrefixList = java.security.AccessController.doPrivileged( + new PrivilegedAction<>() { + public String run() { + return System.getProperty(protocolPathProp, ""); + } + }); + String[] packagePrefixes = packagePrefixList.split("\\|"); + + URLStreamHandler handler = null; + for (int i=0; handler == null && i cls = null; + try { + cls = Class.forName(clsName); + } catch (ClassNotFoundException e) { + ClassLoader cl = ClassLoader.getSystemClassLoader(); + if (cl != null) { + cls = cl.loadClass(clsName); + } + } + if (cls != null) { + handler = (URLStreamHandler)cls.newInstance(); + } + } catch (Exception e) { + // any number of exceptions can get thrown here + } + } + return handler; + } + private static Iterator providers() { - return new Iterator() { + return new Iterator<>() { ClassLoader cl = ClassLoader.getSystemClassLoader(); ServiceLoader sl = @@ -1193,7 +1243,7 @@ public final class URL implements java.io.Serializable { gate.set(gate); try { return AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public URLStreamHandler run() { Iterator itr = providers(); while (itr.hasNext()) { @@ -1251,6 +1301,10 @@ public final class URL implements java.io.Serializable { if (handler == null && !protocol.equalsIgnoreCase("jar")) { handler = lookupViaProviders(protocol); } + + if (handler == null) { + handler = lookupViaProperty(protocol); + } } synchronized (streamHandlerLock) { diff --git a/jdk/src/java.base/share/classes/java/net/URLClassLoader.java b/jdk/src/java.base/share/classes/java/net/URLClassLoader.java index 7bb5fc54a9e..3b5c1e264ff 100644 --- a/jdk/src/java.base/share/classes/java/net/URLClassLoader.java +++ b/jdk/src/java.base/share/classes/java/net/URLClassLoader.java @@ -359,7 +359,7 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { final Class result; try { result = AccessController.doPrivileged( - new PrivilegedExceptionAction>() { + new PrivilegedExceptionAction<>() { public Class run() throws ClassNotFoundException { String path = name.replace('.', '/').concat(".class"); Resource res = ucp.getResource(path, false); @@ -564,7 +564,7 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { * The same restriction to finding classes applies to resources */ URL url = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public URL run() { return ucp.findResource(name, true); } @@ -587,7 +587,7 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { { final Enumeration e = ucp.findResources(name, true); - return new Enumeration() { + return new Enumeration<>() { private URL url = null; private boolean next() { @@ -596,7 +596,7 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { } do { URL u = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public URL run() { if (!e.hasMoreElements()) return null; @@ -704,7 +704,7 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { final Permission fp = p; - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public Void run() throws SecurityException { sm.checkPermission(fp); return null; @@ -735,7 +735,7 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { final AccessControlContext acc = AccessController.getContext(); // Need a privileged block to create the class loader URLClassLoader ucl = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public URLClassLoader run() { return new FactoryURLClassLoader(urls, parent, acc); } @@ -760,7 +760,7 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { final AccessControlContext acc = AccessController.getContext(); // Need a privileged block to create the class loader URLClassLoader ucl = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public URLClassLoader run() { return new FactoryURLClassLoader(urls, acc); } diff --git a/jdk/src/java.base/share/classes/java/net/UnknownHostException.java b/jdk/src/java.base/share/classes/java/net/UnknownHostException.java index a990f69cecd..9a9fea53fa0 100644 --- a/jdk/src/java.base/share/classes/java/net/UnknownHostException.java +++ b/jdk/src/java.base/share/classes/java/net/UnknownHostException.java @@ -41,10 +41,10 @@ class UnknownHostException extends IOException { * Constructs a new {@code UnknownHostException} with the * specified detail message. * - * @param host the detail message. + * @param message the detail message. */ - public UnknownHostException(String host) { - super(host); + public UnknownHostException(String message) { + super(message); } /** diff --git a/jdk/src/java.base/share/classes/java/nio/channels/AsynchronousFileChannel.java b/jdk/src/java.base/share/classes/java/nio/channels/AsynchronousFileChannel.java index b985d775748..4b5548e79e5 100644 --- a/jdk/src/java.base/share/classes/java/nio/channels/AsynchronousFileChannel.java +++ b/jdk/src/java.base/share/classes/java/nio/channels/AsynchronousFileChannel.java @@ -296,7 +296,7 @@ public abstract class AsynchronousFileChannel public static AsynchronousFileChannel open(Path file, OpenOption... options) throws IOException { - Set set = new HashSet(options.length); + Set set = new HashSet<>(options.length); Collections.addAll(set, options); return open(file, set, null, NO_ATTRIBUTES); } diff --git a/jdk/src/java.base/share/classes/java/nio/channels/FileChannel.java b/jdk/src/java.base/share/classes/java/nio/channels/FileChannel.java index a23f1c3c336..eb3934d3dea 100644 --- a/jdk/src/java.base/share/classes/java/nio/channels/FileChannel.java +++ b/jdk/src/java.base/share/classes/java/nio/channels/FileChannel.java @@ -330,7 +330,7 @@ public abstract class FileChannel public static FileChannel open(Path path, OpenOption... options) throws IOException { - Set set = new HashSet(options.length); + Set set = new HashSet<>(options.length); Collections.addAll(set, options); return open(path, set, NO_ATTRIBUTES); } diff --git a/jdk/src/java.base/share/classes/java/nio/channels/spi/AsynchronousChannelProvider.java b/jdk/src/java.base/share/classes/java/nio/channels/spi/AsynchronousChannelProvider.java index 464b4fc435d..d14c853522b 100644 --- a/jdk/src/java.base/share/classes/java/nio/channels/spi/AsynchronousChannelProvider.java +++ b/jdk/src/java.base/share/classes/java/nio/channels/spi/AsynchronousChannelProvider.java @@ -76,7 +76,7 @@ public abstract class AsynchronousChannelProvider { private static AsynchronousChannelProvider load() { return AccessController - .doPrivileged(new PrivilegedAction() { + .doPrivileged(new PrivilegedAction<>() { public AsynchronousChannelProvider run() { AsynchronousChannelProvider p; p = loadProviderFromProperty(); diff --git a/jdk/src/java.base/share/classes/java/nio/channels/spi/SelectorProvider.java b/jdk/src/java.base/share/classes/java/nio/channels/spi/SelectorProvider.java index ae876005bac..ca704a8e5a5 100644 --- a/jdk/src/java.base/share/classes/java/nio/channels/spi/SelectorProvider.java +++ b/jdk/src/java.base/share/classes/java/nio/channels/spi/SelectorProvider.java @@ -172,7 +172,7 @@ public abstract class SelectorProvider { if (provider != null) return provider; return AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public SelectorProvider run() { if (loadProviderFromProperty()) return provider; diff --git a/jdk/src/java.base/share/classes/java/nio/charset/Charset.java b/jdk/src/java.base/share/classes/java/nio/charset/Charset.java index ae0566174b5..8d67ebbc8d6 100644 --- a/jdk/src/java.base/share/classes/java/nio/charset/Charset.java +++ b/jdk/src/java.base/share/classes/java/nio/charset/Charset.java @@ -335,7 +335,7 @@ public abstract class Charset // thrown. Should be invoked with full privileges. // private static Iterator providers() { - return new Iterator() { + return new Iterator<>() { ClassLoader cl = ClassLoader.getSystemClassLoader(); ServiceLoader sl = @@ -404,7 +404,7 @@ public abstract class Charset gate.set(gate); return AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public Charset run() { for (Iterator i = providers(); i.hasNext();) { @@ -428,7 +428,7 @@ public abstract class Charset // returns ExtendedProvider, if installed private static CharsetProvider extendedProvider() { return AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public CharsetProvider run() { try { Class epc @@ -570,10 +570,10 @@ public abstract class Charset */ public static SortedMap availableCharsets() { return AccessController.doPrivileged( - new PrivilegedAction>() { + new PrivilegedAction<>() { public SortedMap run() { TreeMap m = - new TreeMap( + new TreeMap<>( ASCIICaseInsensitiveComparator.CASE_INSENSITIVE_ORDER); put(standardProvider.charsets(), m); CharsetProvider ecp = ExtendedProviderHolder.extendedProvider; @@ -663,7 +663,7 @@ public abstract class Charset if (aliasSet != null) return aliasSet; int n = aliases.length; - HashSet hs = new HashSet(n); + HashSet hs = new HashSet<>(n); for (int i = 0; i < n; i++) hs.add(aliases[i]); aliasSet = Collections.unmodifiableSet(hs); diff --git a/jdk/src/java.base/share/classes/java/nio/charset/CoderResult.java b/jdk/src/java.base/share/classes/java/nio/charset/CoderResult.java index 1c9250cf19f..79d4843e2de 100644 --- a/jdk/src/java.base/share/classes/java/nio/charset/CoderResult.java +++ b/jdk/src/java.base/share/classes/java/nio/charset/CoderResult.java @@ -204,13 +204,13 @@ public class CoderResult { WeakReference w; CoderResult e = null; if (cache == null) { - cache = new HashMap>(); + cache = new HashMap<>(); } else if ((w = cache.get(k)) != null) { e = w.get(); } if (e == null) { e = create(len); - cache.put(k, new WeakReference(e)); + cache.put(k, new WeakReference<>(e)); } return e; } diff --git a/jdk/src/java.base/share/classes/java/nio/file/AtomicMoveNotSupportedException.java b/jdk/src/java.base/share/classes/java/nio/file/AtomicMoveNotSupportedException.java index 27947c31a8c..5849565330e 100644 --- a/jdk/src/java.base/share/classes/java/nio/file/AtomicMoveNotSupportedException.java +++ b/jdk/src/java.base/share/classes/java/nio/file/AtomicMoveNotSupportedException.java @@ -45,7 +45,7 @@ public class AtomicMoveNotSupportedException * @param target * a string identifying the target file or {@code null} if not known * @param reason - * a reason message with additional information + * a reason message with additional information or {@code null} */ public AtomicMoveNotSupportedException(String source, String target, diff --git a/jdk/src/java.base/share/classes/java/nio/file/FileSystems.java b/jdk/src/java.base/share/classes/java/nio/file/FileSystems.java index 17c295e95ef..8524518f9f3 100644 --- a/jdk/src/java.base/share/classes/java/nio/file/FileSystems.java +++ b/jdk/src/java.base/share/classes/java/nio/file/FileSystems.java @@ -93,7 +93,7 @@ public final class FileSystems { private static FileSystem defaultFileSystem() { // load default provider FileSystemProvider provider = AccessController - .doPrivileged(new PrivilegedAction() { + .doPrivileged(new PrivilegedAction<>() { public FileSystemProvider run() { return getDefaultProvider(); } diff --git a/jdk/src/java.base/share/classes/java/nio/file/Files.java b/jdk/src/java.base/share/classes/java/nio/file/Files.java index 0c7891458b8..80c76a2f571 100644 --- a/jdk/src/java.base/share/classes/java/nio/file/Files.java +++ b/jdk/src/java.base/share/classes/java/nio/file/Files.java @@ -402,7 +402,7 @@ public final class Files { public static SeekableByteChannel newByteChannel(Path path, OpenOption... options) throws IOException { - Set set = new HashSet(options.length); + Set set = new HashSet<>(options.length); Collections.addAll(set, options); return newByteChannel(path, set); } @@ -516,7 +516,7 @@ public final class Files { // create a matcher and return a filter that uses it. FileSystem fs = dir.getFileSystem(); final PathMatcher matcher = fs.getPathMatcher("glob:" + glob); - DirectoryStream.Filter filter = new DirectoryStream.Filter() { + DirectoryStream.Filter filter = new DirectoryStream.Filter<>() { @Override public boolean accept(Path entry) { return matcher.matches(entry.getFileName()); @@ -1541,7 +1541,7 @@ public final class Files { // creates the default file type detector private static FileTypeDetector createDefaultFileTypeDetector() { return AccessController - .doPrivileged(new PrivilegedAction() { + .doPrivileged(new PrivilegedAction<>() { @Override public FileTypeDetector run() { return sun.nio.fs.DefaultFileTypeDetector.create(); }}); @@ -1550,7 +1550,7 @@ public final class Files { // loads all installed file type detectors private static List loadInstalledDetectors() { return AccessController - .doPrivileged(new PrivilegedAction>() { + .doPrivileged(new PrivilegedAction<>() { @Override public List run() { List list = new ArrayList<>(); ServiceLoader loader = ServiceLoader @@ -3468,7 +3468,7 @@ public final class Files { final Iterator delegate = ds.iterator(); // Re-wrap DirectoryIteratorException to UncheckedIOException - Iterator iterator = new Iterator() { + Iterator iterator = new Iterator<>() { @Override public boolean hasNext() { try { diff --git a/jdk/src/java.base/share/classes/java/nio/file/Path.java b/jdk/src/java.base/share/classes/java/nio/file/Path.java index fdb28cfd716..8387a8e9597 100644 --- a/jdk/src/java.base/share/classes/java/nio/file/Path.java +++ b/jdk/src/java.base/share/classes/java/nio/file/Path.java @@ -801,7 +801,7 @@ public interface Path */ @Override default Iterator iterator() { - return new Iterator() { + return new Iterator<>() { private int i = 0; @Override diff --git a/jdk/src/java.base/share/classes/java/nio/file/attribute/AclEntry.java b/jdk/src/java.base/share/classes/java/nio/file/attribute/AclEntry.java index b0084946283..26818be4219 100644 --- a/jdk/src/java.base/share/classes/java/nio/file/attribute/AclEntry.java +++ b/jdk/src/java.base/share/classes/java/nio/file/attribute/AclEntry.java @@ -306,7 +306,7 @@ public final class AclEntry { * @return the permissions component */ public Set permissions() { - return new HashSet(perms); + return new HashSet<>(perms); } /** @@ -317,7 +317,7 @@ public final class AclEntry { * @return the flags component */ public Set flags() { - return new HashSet(flags); + return new HashSet<>(flags); } /** diff --git a/jdk/src/java.base/share/classes/java/nio/file/attribute/PosixFilePermissions.java b/jdk/src/java.base/share/classes/java/nio/file/attribute/PosixFilePermissions.java index 45a866a5f1d..c98b69deaba 100644 --- a/jdk/src/java.base/share/classes/java/nio/file/attribute/PosixFilePermissions.java +++ b/jdk/src/java.base/share/classes/java/nio/file/attribute/PosixFilePermissions.java @@ -160,13 +160,13 @@ public final class PosixFilePermissions { { // copy set and check for nulls (CCE will be thrown if an element is not // a PosixFilePermission) - perms = new HashSet(perms); + perms = new HashSet<>(perms); for (PosixFilePermission p: perms) { if (p == null) throw new NullPointerException(); } final Set value = perms; - return new FileAttribute>() { + return new FileAttribute<>() { @Override public String name() { return "posix:permissions"; diff --git a/jdk/src/java.base/share/classes/java/nio/file/spi/FileSystemProvider.java b/jdk/src/java.base/share/classes/java/nio/file/spi/FileSystemProvider.java index def1cca7a57..dad51083401 100644 --- a/jdk/src/java.base/share/classes/java/nio/file/spi/FileSystemProvider.java +++ b/jdk/src/java.base/share/classes/java/nio/file/spi/FileSystemProvider.java @@ -110,7 +110,7 @@ public abstract class FileSystemProvider { // loads all installed providers private static List loadInstalledProviders() { - List list = new ArrayList(); + List list = new ArrayList<>(); ServiceLoader sl = ServiceLoader .load(FileSystemProvider.class, ClassLoader.getSystemClassLoader()); @@ -163,7 +163,7 @@ public abstract class FileSystemProvider { loadingProviders = true; List list = AccessController - .doPrivileged(new PrivilegedAction>() { + .doPrivileged(new PrivilegedAction<>() { @Override public List run() { return loadInstalledProviders(); @@ -419,7 +419,7 @@ public abstract class FileSystemProvider { throws IOException { int len = options.length; - Set opts = new HashSet(len + 3); + Set opts = new HashSet<>(len + 3); if (len == 0) { opts.add(StandardOpenOption.CREATE); opts.add(StandardOpenOption.TRUNCATE_EXISTING); diff --git a/jdk/src/java.base/share/classes/java/security/AccessControlContext.java b/jdk/src/java.base/share/classes/java/security/AccessControlContext.java index feed0cf11e1..5e588602c97 100644 --- a/jdk/src/java.base/share/classes/java/security/AccessControlContext.java +++ b/jdk/src/java.base/share/classes/java/security/AccessControlContext.java @@ -458,7 +458,7 @@ public final class AccessControlContext { Thread.dumpStack(); final ProtectionDomain pd = context[i]; final Debug db = debug; - AccessController.doPrivileged (new PrivilegedAction() { + AccessController.doPrivileged (new PrivilegedAction<>() { public Void run() { db.println("domain that failed "+pd); return null; diff --git a/jdk/src/java.base/share/classes/java/security/AccessController.java b/jdk/src/java.base/share/classes/java/security/AccessController.java index e2b8e584560..90503d29cf8 100644 --- a/jdk/src/java.base/share/classes/java/security/AccessController.java +++ b/jdk/src/java.base/share/classes/java/security/AccessController.java @@ -612,7 +612,7 @@ public final class AccessController { private static ProtectionDomain getCallerPD(final Class caller) { ProtectionDomain callerPd = doPrivileged - (new PrivilegedAction() { + (new PrivilegedAction<>() { public ProtectionDomain run() { return caller.getProtectionDomain(); } diff --git a/jdk/src/java.base/share/classes/java/security/AllPermission.java b/jdk/src/java.base/share/classes/java/security/AllPermission.java index b830b884c59..fcda7ce0bc1 100644 --- a/jdk/src/java.base/share/classes/java/security/AllPermission.java +++ b/jdk/src/java.base/share/classes/java/security/AllPermission.java @@ -212,7 +212,7 @@ final class AllPermissionCollection * @return an enumeration of all the AllPermission objects. */ public Enumeration elements() { - return new Enumeration() { + return new Enumeration<>() { private boolean hasMore = all_allowed; public boolean hasMoreElements() { diff --git a/jdk/src/java.base/share/classes/java/security/BasicPermission.java b/jdk/src/java.base/share/classes/java/security/BasicPermission.java index 7e0f4fb85b4..92dbe345b26 100644 --- a/jdk/src/java.base/share/classes/java/security/BasicPermission.java +++ b/jdk/src/java.base/share/classes/java/security/BasicPermission.java @@ -332,7 +332,7 @@ final class BasicPermissionCollection */ public BasicPermissionCollection(Class clazz) { - perms = new HashMap(11); + perms = new HashMap<>(11); all_allowed = false; permClass = clazz; } @@ -533,7 +533,7 @@ final class BasicPermissionCollection @SuppressWarnings("unchecked") Hashtable permissions = (Hashtable)gfields.get("permissions", null); - perms = new HashMap(permissions.size()*2); + perms = new HashMap<>(permissions.size()*2); perms.putAll(permissions); // Get all_allowed diff --git a/jdk/src/java.base/share/classes/java/security/CodeSource.java b/jdk/src/java.base/share/classes/java/security/CodeSource.java index 62a5959ecd8..e05c68f9e49 100644 --- a/jdk/src/java.base/share/classes/java/security/CodeSource.java +++ b/jdk/src/java.base/share/classes/java/security/CodeSource.java @@ -543,7 +543,7 @@ public class CodeSource implements java.io.Serializable { if (size > 0) { // we know of 3 different cert types: X.509, PGP, SDSI, which // could all be present in the stream at the same time - cfs = new Hashtable(3); + cfs = new Hashtable<>(3); this.certs = new java.security.cert.Certificate[size]; } diff --git a/jdk/src/java.base/share/classes/java/security/Identity.java b/jdk/src/java.base/share/classes/java/security/Identity.java index 6a5e87e20fa..467e18d1b84 100644 --- a/jdk/src/java.base/share/classes/java/security/Identity.java +++ b/jdk/src/java.base/share/classes/java/security/Identity.java @@ -185,7 +185,7 @@ public abstract class Identity implements Principal, Serializable { check("setIdentityPublicKey"); this.publicKey = key; - certificates = new Vector(); + certificates = new Vector<>(); } /** @@ -248,7 +248,7 @@ public abstract class Identity implements Principal, Serializable { check("addIdentityCertificate"); if (certificates == null) { - certificates = new Vector(); + certificates = new Vector<>(); } if (publicKey != null) { if (!keyEquals(publicKey, certificate.getPublicKey())) { diff --git a/jdk/src/java.base/share/classes/java/security/IdentityScope.java b/jdk/src/java.base/share/classes/java/security/IdentityScope.java index 64c4a634374..763f8308c53 100644 --- a/jdk/src/java.base/share/classes/java/security/IdentityScope.java +++ b/jdk/src/java.base/share/classes/java/security/IdentityScope.java @@ -74,7 +74,7 @@ class IdentityScope extends Identity { private static void initializeSystemScope() { String classname = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public String run() { return Security.getProperty("system.scope"); } diff --git a/jdk/src/java.base/share/classes/java/security/KeyStore.java b/jdk/src/java.base/share/classes/java/security/KeyStore.java index 8fde796e041..75b64ab337a 100644 --- a/jdk/src/java.base/share/classes/java/security/KeyStore.java +++ b/jdk/src/java.base/share/classes/java/security/KeyStore.java @@ -976,7 +976,7 @@ public class KeyStore { */ public final static String getDefaultType() { String kstype; - kstype = AccessController.doPrivileged(new PrivilegedAction() { + kstype = AccessController.doPrivileged(new PrivilegedAction<>() { public String run() { return Security.getProperty(KEYSTORE_TYPE); } diff --git a/jdk/src/java.base/share/classes/java/security/Permissions.java b/jdk/src/java.base/share/classes/java/security/Permissions.java index cc9c69358ee..56a5059351b 100644 --- a/jdk/src/java.base/share/classes/java/security/Permissions.java +++ b/jdk/src/java.base/share/classes/java/security/Permissions.java @@ -99,7 +99,7 @@ implements Serializable * Creates a new Permissions object containing no PermissionCollections. */ public Permissions() { - permsMap = new HashMap, PermissionCollection>(11); + permsMap = new HashMap<>(11); allPermission = null; } @@ -394,7 +394,7 @@ implements Serializable @SuppressWarnings("unchecked") Hashtable, PermissionCollection> perms = (Hashtable, PermissionCollection>)gfields.get("perms", null); - permsMap = new HashMap, PermissionCollection>(perms.size()*2); + permsMap = new HashMap<>(perms.size()*2); permsMap.putAll(perms); // Set hasUnresolved @@ -488,7 +488,7 @@ implements Serializable */ PermissionsHash() { - permsMap = new HashMap(11); + permsMap = new HashMap<>(11); } /** @@ -597,7 +597,7 @@ implements Serializable @SuppressWarnings("unchecked") Hashtable perms = (Hashtable)gfields.get("perms", null); - permsMap = new HashMap(perms.size()*2); + permsMap = new HashMap<>(perms.size()*2); permsMap.putAll(perms); } } diff --git a/jdk/src/java.base/share/classes/java/security/Policy.java b/jdk/src/java.base/share/classes/java/security/Policy.java index ffbcb44cf3f..0864f10d188 100644 --- a/jdk/src/java.base/share/classes/java/security/Policy.java +++ b/jdk/src/java.base/share/classes/java/security/Policy.java @@ -170,7 +170,7 @@ public abstract class Policy { PolicyInfo pinfo = policy.get(); if (pinfo.policy == null) { String policy_class = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public String run() { return Security.getProperty("policy.provider"); } @@ -199,7 +199,7 @@ public abstract class Policy { final String pc = policy_class; Policy pol = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public Policy run() { try { ClassLoader cl = @@ -303,7 +303,7 @@ public abstract class Policy { */ ProtectionDomain policyDomain = - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public ProtectionDomain run() { return p.getClass().getProtectionDomain(); } diff --git a/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java b/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java index 6e7056ddc92..3dd5933fb06 100644 --- a/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java +++ b/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java @@ -367,7 +367,7 @@ public class ProtectionDomain { PermissionCollection perms = java.security.AccessController.doPrivileged - (new java.security.PrivilegedAction() { + (new java.security.PrivilegedAction<>() { public PermissionCollection run() { Policy p = Policy.getPolicyNoCheck(); return p.getPermissions(ProtectionDomain.this); diff --git a/jdk/src/java.base/share/classes/java/security/Provider.java b/jdk/src/java.base/share/classes/java/security/Provider.java index fa20e072d5f..80e510f7fba 100644 --- a/jdk/src/java.base/share/classes/java/security/Provider.java +++ b/jdk/src/java.base/share/classes/java/security/Provider.java @@ -711,7 +711,7 @@ public abstract class Provider extends Properties { legacyChanged = true; if (legacyStrings == null) { - legacyStrings = new LinkedHashMap(); + legacyStrings = new LinkedHashMap<>(); } return true; } @@ -773,7 +773,7 @@ public abstract class Provider extends Properties { private void implReplaceAll(BiFunction function) { legacyChanged = true; if (legacyStrings == null) { - legacyStrings = new LinkedHashMap(); + legacyStrings = new LinkedHashMap<>(); } else { legacyStrings.replaceAll((BiFunction) function); } @@ -905,7 +905,7 @@ public abstract class Provider extends Properties { } serviceSet = null; if (legacyMap == null) { - legacyMap = new LinkedHashMap(); + legacyMap = new LinkedHashMap<>(); } else { legacyMap.clear(); } @@ -1133,7 +1133,7 @@ public abstract class Provider extends Properties { ("service.getProvider() must match this Provider object"); } if (serviceMap == null) { - serviceMap = new LinkedHashMap(); + serviceMap = new LinkedHashMap<>(); } servicesChanged = true; String type = s.getType(); @@ -1305,7 +1305,7 @@ public abstract class Provider extends Properties { } static { - knownEngines = new HashMap(); + knownEngines = new HashMap<>(); // JCA addEngine("AlgorithmParameterGenerator", false, null); addEngine("AlgorithmParameters", false, null); @@ -1431,14 +1431,14 @@ public abstract class Provider extends Properties { private void addAlias(String alias) { if (aliases.isEmpty()) { - aliases = new ArrayList(2); + aliases = new ArrayList<>(2); } aliases.add(alias); } void addAttribute(String type, String value) { if (attributes.isEmpty()) { - attributes = new HashMap(8); + attributes = new HashMap<>(8); } attributes.put(new UString(type), value); } @@ -1471,12 +1471,12 @@ public abstract class Provider extends Properties { if (aliases == null) { this.aliases = Collections.emptyList(); } else { - this.aliases = new ArrayList(aliases); + this.aliases = new ArrayList<>(aliases); } if (attributes == null) { this.attributes = Collections.emptyMap(); } else { - this.attributes = new HashMap(); + this.attributes = new HashMap<>(); for (Map.Entry entry : attributes.entrySet()) { this.attributes.put(new UString(entry.getKey()), entry.getValue()); } @@ -1644,7 +1644,7 @@ public abstract class Provider extends Properties { ("class configured for " + type + " (provider: " + provider.getName() + ") is not public."); } - classRef = new WeakReference>(clazz); + classRef = new WeakReference<>(clazz); } return clazz; } catch (ClassNotFoundException e) { diff --git a/jdk/src/java.base/share/classes/java/security/SecureRandom.java b/jdk/src/java.base/share/classes/java/security/SecureRandom.java index a9c4469e8e1..f1531de25f7 100644 --- a/jdk/src/java.base/share/classes/java/security/SecureRandom.java +++ b/jdk/src/java.base/share/classes/java/security/SecureRandom.java @@ -616,7 +616,7 @@ public class SecureRandom extends java.util.Random { throws NoSuchAlgorithmException { String property = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { @Override public String run() { return Security.getProperty( diff --git a/jdk/src/java.base/share/classes/java/security/Security.java b/jdk/src/java.base/share/classes/java/security/Security.java index 11e1a997639..5b7be62ca67 100644 --- a/jdk/src/java.base/share/classes/java/security/Security.java +++ b/jdk/src/java.base/share/classes/java/security/Security.java @@ -66,7 +66,7 @@ public final class Security { // things in initialize that might require privs. // (the FileInputStream call and the File.exists call, // the securityPropFile call, etc) - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public Void run() { initialize(); return null; @@ -810,7 +810,7 @@ public final class Security { final boolean pd = key.equals("package.definition"); if (pa || pd) { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public Void run() { try { /* Get the class via the bootstrap class loader. */ diff --git a/jdk/src/java.base/share/classes/java/security/Signature.java b/jdk/src/java.base/share/classes/java/security/Signature.java index bb2e75dd1ac..e23b0dde121 100644 --- a/jdk/src/java.base/share/classes/java/security/Signature.java +++ b/jdk/src/java.base/share/classes/java/security/Signature.java @@ -265,7 +265,7 @@ public abstract class Signature extends SignatureSpi { private final static Map signatureInfo; static { - signatureInfo = new ConcurrentHashMap(); + signatureInfo = new ConcurrentHashMap<>(); Boolean TRUE = Boolean.TRUE; // pre-initialize with values for our SignatureSpi implementations signatureInfo.put("sun.security.provider.DSA$RawDSA", TRUE); diff --git a/jdk/src/java.base/share/classes/java/security/Signer.java b/jdk/src/java.base/share/classes/java/security/Signer.java index 077538da979..2edf668b530 100644 --- a/jdk/src/java.base/share/classes/java/security/Signer.java +++ b/jdk/src/java.base/share/classes/java/security/Signer.java @@ -140,7 +140,7 @@ public abstract class Signer extends Identity { } try { AccessController.doPrivileged( - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public Void run() throws KeyManagementException { setPublicKey(pub); return null; diff --git a/jdk/src/java.base/share/classes/java/security/UnresolvedPermission.java b/jdk/src/java.base/share/classes/java/security/UnresolvedPermission.java index 9dff324920e..e5b0d3047aa 100644 --- a/jdk/src/java.base/share/classes/java/security/UnresolvedPermission.java +++ b/jdk/src/java.base/share/classes/java/security/UnresolvedPermission.java @@ -560,7 +560,7 @@ implements java.io.Serializable if (size > 0) { // we know of 3 different cert types: X.509, PGP, SDSI, which // could all be present in the stream at the same time - cfs = new Hashtable(3); + cfs = new Hashtable<>(3); this.certs = new java.security.cert.Certificate[size]; } diff --git a/jdk/src/java.base/share/classes/java/security/UnresolvedPermissionCollection.java b/jdk/src/java.base/share/classes/java/security/UnresolvedPermissionCollection.java index 76336485842..87ab32d54f9 100644 --- a/jdk/src/java.base/share/classes/java/security/UnresolvedPermissionCollection.java +++ b/jdk/src/java.base/share/classes/java/security/UnresolvedPermissionCollection.java @@ -61,7 +61,7 @@ implements java.io.Serializable * */ public UnresolvedPermissionCollection() { - perms = new HashMap>(11); + perms = new HashMap<>(11); } /** @@ -82,7 +82,7 @@ implements java.io.Serializable synchronized (this) { v = perms.get(up.getName()); if (v == null) { - v = new ArrayList(); + v = new ArrayList<>(); perms.put(up.getName(), v); } } @@ -203,7 +203,7 @@ implements java.io.Serializable Hashtable> permissions = (Hashtable>) gfields.get("permissions", null); - perms = new HashMap>(permissions.size()*2); + perms = new HashMap<>(permissions.size()*2); // Convert each entry (Vector) into a List Set>> set = permissions.entrySet(); diff --git a/jdk/src/java.base/share/classes/java/security/cert/CertPathBuilder.java b/jdk/src/java.base/share/classes/java/security/cert/CertPathBuilder.java index 6008e9ec180..06c0d04fefa 100644 --- a/jdk/src/java.base/share/classes/java/security/cert/CertPathBuilder.java +++ b/jdk/src/java.base/share/classes/java/security/cert/CertPathBuilder.java @@ -301,7 +301,7 @@ public class CertPathBuilder { */ public final static String getDefaultType() { String cpbtype = - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public String run() { return Security.getProperty(CPB_TYPE); } diff --git a/jdk/src/java.base/share/classes/java/security/cert/CertPathValidator.java b/jdk/src/java.base/share/classes/java/security/cert/CertPathValidator.java index bd2ff56dd0c..ce9d38d1800 100644 --- a/jdk/src/java.base/share/classes/java/security/cert/CertPathValidator.java +++ b/jdk/src/java.base/share/classes/java/security/cert/CertPathValidator.java @@ -313,7 +313,7 @@ public class CertPathValidator { */ public final static String getDefaultType() { String cpvtype = - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public String run() { return Security.getProperty(CPV_TYPE); } diff --git a/jdk/src/java.base/share/classes/java/security/cert/CertStore.java b/jdk/src/java.base/share/classes/java/security/cert/CertStore.java index 1a8ed628c13..d39d6703b9a 100644 --- a/jdk/src/java.base/share/classes/java/security/cert/CertStore.java +++ b/jdk/src/java.base/share/classes/java/security/cert/CertStore.java @@ -409,7 +409,7 @@ public class CertStore { */ public final static String getDefaultType() { String cstype; - cstype = AccessController.doPrivileged(new PrivilegedAction() { + cstype = AccessController.doPrivileged(new PrivilegedAction<>() { public String run() { return Security.getProperty(CERTSTORE_TYPE); } diff --git a/jdk/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java b/jdk/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java index 8c1f0664023..0fce92f0ef7 100644 --- a/jdk/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java +++ b/jdk/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java @@ -231,7 +231,7 @@ public class CertificateRevokedException extends CertificateException { if (size == 0) { extensions = Collections.emptyMap(); } else { - extensions = new HashMap(size); + extensions = new HashMap<>(size); } // Read in the extensions and put the mappings in the extensions map diff --git a/jdk/src/java.base/share/classes/java/security/cert/PKIXParameters.java b/jdk/src/java.base/share/classes/java/security/cert/PKIXParameters.java index a411f6e2aec..4bc453ca956 100644 --- a/jdk/src/java.base/share/classes/java/security/cert/PKIXParameters.java +++ b/jdk/src/java.base/share/classes/java/security/cert/PKIXParameters.java @@ -120,8 +120,8 @@ public class PKIXParameters implements CertPathParameters { setTrustAnchors(trustAnchors); this.unmodInitialPolicies = Collections.emptySet(); - this.certPathCheckers = new ArrayList(); - this.certStores = new ArrayList(); + this.certPathCheckers = new ArrayList<>(); + this.certStores = new ArrayList<>(); } /** @@ -144,7 +144,7 @@ public class PKIXParameters implements CertPathParameters { if (keystore == null) throw new NullPointerException("the keystore parameter must be " + "non-null"); - Set hashSet = new HashSet(); + Set hashSet = new HashSet<>(); Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); @@ -156,8 +156,8 @@ public class PKIXParameters implements CertPathParameters { } setTrustAnchors(hashSet); this.unmodInitialPolicies = Collections.emptySet(); - this.certPathCheckers = new ArrayList(); - this.certStores = new ArrayList(); + this.certPathCheckers = new ArrayList<>(); + this.certStores = new ArrayList<>(); } /** @@ -207,7 +207,7 @@ public class PKIXParameters implements CertPathParameters { } } this.unmodTrustAnchors = Collections.unmodifiableSet - (new HashSet(trustAnchors)); + (new HashSet<>(trustAnchors)); } /** @@ -256,7 +256,7 @@ public class PKIXParameters implements CertPathParameters { + "of type java.lang.String"); } this.unmodInitialPolicies = - Collections.unmodifiableSet(new HashSet(initialPolicies)); + Collections.unmodifiableSet(new HashSet<>(initialPolicies)); } else this.unmodInitialPolicies = Collections.emptySet(); } @@ -280,7 +280,7 @@ public class PKIXParameters implements CertPathParameters { */ public void setCertStores(List stores) { if (stores == null) { - this.certStores = new ArrayList(); + this.certStores = new ArrayList<>(); } else { for (Iterator i = stores.iterator(); i.hasNext();) { if (!(i.next() instanceof CertStore)) { @@ -288,7 +288,7 @@ public class PKIXParameters implements CertPathParameters { + "of type java.security.cert.CertStore"); } } - this.certStores = new ArrayList(stores); + this.certStores = new ArrayList<>(stores); } } @@ -316,7 +316,7 @@ public class PKIXParameters implements CertPathParameters { */ public List getCertStores() { return Collections.unmodifiableList - (new ArrayList(this.certStores)); + (new ArrayList<>(this.certStores)); } /** @@ -544,14 +544,13 @@ public class PKIXParameters implements CertPathParameters { */ public void setCertPathCheckers(List checkers) { if (checkers != null) { - List tmpList = - new ArrayList(); + List tmpList = new ArrayList<>(); for (PKIXCertPathChecker checker : checkers) { tmpList.add((PKIXCertPathChecker)checker.clone()); } this.certPathCheckers = tmpList; } else { - this.certPathCheckers = new ArrayList(); + this.certPathCheckers = new ArrayList<>(); } } @@ -567,7 +566,7 @@ public class PKIXParameters implements CertPathParameters { * @see #setCertPathCheckers */ public List getCertPathCheckers() { - List tmpList = new ArrayList(); + List tmpList = new ArrayList<>(); for (PKIXCertPathChecker ck : certPathCheckers) { tmpList.add((PKIXCertPathChecker)ck.clone()); } @@ -667,11 +666,11 @@ public class PKIXParameters implements CertPathParameters { // must clone these because addCertStore, et al. modify them if (certStores != null) { - copy.certStores = new ArrayList(certStores); + copy.certStores = new ArrayList<>(certStores); } if (certPathCheckers != null) { copy.certPathCheckers = - new ArrayList(certPathCheckers.size()); + new ArrayList<>(certPathCheckers.size()); for (PKIXCertPathChecker checker : certPathCheckers) { copy.certPathCheckers.add( (PKIXCertPathChecker)checker.clone()); diff --git a/jdk/src/java.base/share/classes/java/security/cert/PKIXRevocationChecker.java b/jdk/src/java.base/share/classes/java/security/cert/PKIXRevocationChecker.java index a345c96cac8..14e17cccb2d 100644 --- a/jdk/src/java.base/share/classes/java/security/cert/PKIXRevocationChecker.java +++ b/jdk/src/java.base/share/classes/java/security/cert/PKIXRevocationChecker.java @@ -170,7 +170,7 @@ public abstract class PKIXRevocationChecker extends PKIXCertPathChecker { { this.ocspExtensions = (extensions == null) ? Collections.emptyList() - : new ArrayList(extensions); + : new ArrayList<>(extensions); } /** @@ -232,7 +232,7 @@ public abstract class PKIXRevocationChecker extends PKIXCertPathChecker { public void setOptions(Set
                                Class{}[property]+ -> elements[property]+ {@literal ->} elementscomplexcontent
                                xs:all
                                Classnon empty[property]+ -> elements[property]+ {@literal ->} elementscomplexcontent
                                xs:sequence
                                ClassXno property -> elementno property {@literal ->} elementcomplexcontent
                                empty sequence
                                ClassX1 [@XmlValue property] {@literal &&}
                                [property]+ -> attributes
                                1 [@XmlValue property] {@literal &&}
                                [property]+ {@literal ->} attributes
                                simplecontent
                                ClassX1 [@XmlValue property] {@literal &&}
                                no properties -> attribute
                                1 [@XmlValue property] {@literal &&}
                                no properties {@literal ->} attribute
                                simpletype
                                * diff --git a/jdk/src/java.base/share/classes/sun/misc/Cleaner.java b/jdk/src/java.base/share/classes/sun/misc/Cleaner.java index 5e92f35d616..6cc90a74760 100644 --- a/jdk/src/java.base/share/classes/sun/misc/Cleaner.java +++ b/jdk/src/java.base/share/classes/sun/misc/Cleaner.java @@ -142,7 +142,7 @@ public class Cleaner try { thunk.run(); } catch (final Throwable x) { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public Void run() { if (System.err != null) new Error("Cleaner terminated abnormally", x) diff --git a/jdk/src/java.base/share/classes/sun/misc/GC.java b/jdk/src/java.base/share/classes/sun/misc/GC.java index c77bf1d055b..4cfd9781274 100644 --- a/jdk/src/java.base/share/classes/sun/misc/GC.java +++ b/jdk/src/java.base/share/classes/sun/misc/GC.java @@ -82,8 +82,7 @@ public class GC { */ public static native long maxObjectInspectionAge(); - - private static class Daemon extends Thread { + private static class Daemon extends ManagedLocalsThread { public void run() { for (;;) { diff --git a/jdk/src/java.base/share/classes/sun/misc/InnocuousThread.java b/jdk/src/java.base/share/classes/sun/misc/InnocuousThread.java index db431029484..78a0a185f0a 100644 --- a/jdk/src/java.base/share/classes/sun/misc/InnocuousThread.java +++ b/jdk/src/java.base/share/classes/sun/misc/InnocuousThread.java @@ -26,32 +26,37 @@ package sun.misc; import java.security.AccessControlContext; +import java.security.AccessController; import java.security.ProtectionDomain; +import java.security.PrivilegedAction; +import java.util.concurrent.atomic.AtomicInteger; /** * A thread that has no permissions, is not a member of any user-defined * ThreadGroup and supports the ability to erase ThreadLocals. - * - * @implNote Based on the implementation of InnocuousForkJoinWorkerThread. */ -public final class InnocuousThread extends Thread { +public final class InnocuousThread extends ManagedLocalsThread { private static final Unsafe UNSAFE; - private static final ThreadGroup THREADGROUP; + private static final ThreadGroup INNOCUOUSTHREADGROUP; private static final AccessControlContext ACC; - private static final long THREADLOCALS; - private static final long INHERITABLETHREADLOCALS; private static final long INHERITEDACCESSCONTROLCONTEXT; + private static final long CONTEXTCLASSLOADER; + + private static final AtomicInteger threadNumber = new AtomicInteger(1); public InnocuousThread(Runnable target) { - super(THREADGROUP, target, "anInnocuousThread"); - UNSAFE.putOrderedObject(this, INHERITEDACCESSCONTROLCONTEXT, ACC); - eraseThreadLocals(); + this(INNOCUOUSTHREADGROUP, target, + "InnocuousThread-" + threadNumber.getAndIncrement()); } - @Override - public ClassLoader getContextClassLoader() { - // always report system class loader - return ClassLoader.getSystemClassLoader(); + public InnocuousThread(Runnable target, String name) { + this(INNOCUOUSTHREADGROUP, target, name); + } + + public InnocuousThread(ThreadGroup group, Runnable target, String name) { + super(group, target, name); + UNSAFE.putOrderedObject(this, INHERITEDACCESSCONTROLCONTEXT, ACC); + UNSAFE.putOrderedObject(this, CONTEXTCLASSLOADER, ClassLoader.getSystemClassLoader()); } @Override @@ -61,7 +66,11 @@ public final class InnocuousThread extends Thread { @Override public void setContextClassLoader(ClassLoader cl) { - throw new SecurityException("setContextClassLoader"); + // Allow clearing of the TCCL to remove the reference to the system classloader. + if (cl == null) + super.setContextClassLoader(null); + else + throw new SecurityException("setContextClassLoader"); } // ensure run method is run only once @@ -75,14 +84,6 @@ public final class InnocuousThread extends Thread { } } - /** - * Drops all thread locals (and inherited thread locals). - */ - public void eraseThreadLocals() { - UNSAFE.putObject(this, THREADLOCALS, null); - UNSAFE.putObject(this, INHERITABLETHREADLOCALS, null); - } - // Use Unsafe to access Thread group and ThreadGroup parent fields static { try { @@ -95,12 +96,10 @@ public final class InnocuousThread extends Thread { Class tk = Thread.class; Class gk = ThreadGroup.class; - THREADLOCALS = UNSAFE.objectFieldOffset - (tk.getDeclaredField("threadLocals")); - INHERITABLETHREADLOCALS = UNSAFE.objectFieldOffset - (tk.getDeclaredField("inheritableThreadLocals")); INHERITEDACCESSCONTROLCONTEXT = UNSAFE.objectFieldOffset (tk.getDeclaredField("inheritedAccessControlContext")); + CONTEXTCLASSLOADER = UNSAFE.objectFieldOffset + (tk.getDeclaredField("contextClassLoader")); long tg = UNSAFE.objectFieldOffset(tk.getDeclaredField("group")); long gp = UNSAFE.objectFieldOffset(gk.getDeclaredField("parent")); @@ -113,7 +112,10 @@ public final class InnocuousThread extends Thread { break; group = parent; } - THREADGROUP = new ThreadGroup(group, "InnocuousThreadGroup"); + final ThreadGroup root = group; + INNOCUOUSTHREADGROUP = AccessController.doPrivileged( + (PrivilegedAction) () -> + { return new ThreadGroup(root, "InnocuousThreadGroup"); }); } catch (Exception e) { throw new Error(e); } diff --git a/jdk/src/java.base/share/classes/sun/misc/ManagedLocalsThread.java b/jdk/src/java.base/share/classes/sun/misc/ManagedLocalsThread.java new file mode 100644 index 00000000000..cd75ef237ce --- /dev/null +++ b/jdk/src/java.base/share/classes/sun/misc/ManagedLocalsThread.java @@ -0,0 +1,87 @@ +/* + * 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. + */ + +package sun.misc; + +/** + * A thread that has it's thread locals, and inheritable thread + * locals erased on construction. + */ +public class ManagedLocalsThread extends Thread { + private static final Unsafe UNSAFE; + private static final long THREAD_LOCALS; + private static final long INHERITABLE_THREAD_LOCALS; + + public ManagedLocalsThread() { + eraseThreadLocals(); + } + + public ManagedLocalsThread(Runnable target) { + super(target); + eraseThreadLocals(); + } + + public ManagedLocalsThread(String name) { + super(name); + eraseThreadLocals(); + } + + public ManagedLocalsThread(Runnable target, String name) { + super(target, name); + eraseThreadLocals(); + } + + public ManagedLocalsThread(ThreadGroup group, String name) { + super(group, name); + eraseThreadLocals(); + } + + public ManagedLocalsThread(ThreadGroup group, Runnable target, String name) { + super(group, target, name); + eraseThreadLocals(); + } + + /** + * Drops all thread locals (and inherited thread locals). + */ + public final void eraseThreadLocals() { + UNSAFE.putObject(this, THREAD_LOCALS, null); + UNSAFE.putObject(this, INHERITABLE_THREAD_LOCALS, null); + } + + static { + UNSAFE = Unsafe.getUnsafe(); + Class t = Thread.class; + try { + THREAD_LOCALS = UNSAFE.objectFieldOffset + (t.getDeclaredField("threadLocals")); + INHERITABLE_THREAD_LOCALS = UNSAFE.objectFieldOffset + (t.getDeclaredField("inheritableThreadLocals")); + } catch (Exception e) { + throw new Error(e); + } + } +} + diff --git a/jdk/src/java.base/share/classes/sun/misc/RequestProcessor.java b/jdk/src/java.base/share/classes/sun/misc/RequestProcessor.java index 54a62724de0..30131f42b29 100644 --- a/jdk/src/java.base/share/classes/sun/misc/RequestProcessor.java +++ b/jdk/src/java.base/share/classes/sun/misc/RequestProcessor.java @@ -77,7 +77,7 @@ public class RequestProcessor implements Runnable { */ public static synchronized void startProcessing() { if (dispatcher == null) { - dispatcher = new Thread(new RequestProcessor(), "Request Processor"); + dispatcher = new ManagedLocalsThread(new RequestProcessor(), "Request Processor"); dispatcher.setPriority(Thread.NORM_PRIORITY + 2); dispatcher.start(); } diff --git a/jdk/src/java.base/share/classes/sun/misc/Signal.java b/jdk/src/java.base/share/classes/sun/misc/Signal.java index 07557a8d78f..a00ee9f089d 100644 --- a/jdk/src/java.base/share/classes/sun/misc/Signal.java +++ b/jdk/src/java.base/share/classes/sun/misc/Signal.java @@ -213,7 +213,7 @@ public final class Signal { } }; if (handler != null) { - new Thread(runnable, sig + " handler").start(); + new ManagedLocalsThread(runnable, sig + " handler").start(); } } diff --git a/jdk/src/java.base/share/classes/sun/misc/URLClassPath.java b/jdk/src/java.base/share/classes/sun/misc/URLClassPath.java index 04321d65512..56482db0a23 100644 --- a/jdk/src/java.base/share/classes/sun/misc/URLClassPath.java +++ b/jdk/src/java.base/share/classes/sun/misc/URLClassPath.java @@ -97,16 +97,16 @@ public class URLClassPath { } /* The original search path of URLs. */ - private ArrayList path = new ArrayList(); + private ArrayList path = new ArrayList<>(); /* The stack of unopened URLs */ - Stack urls = new Stack(); + Stack urls = new Stack<>(); /* The resulting search path of Loaders */ - ArrayList loaders = new ArrayList(); + ArrayList loaders = new ArrayList<>(); /* Map of each URL opened to its corresponding Loader */ - HashMap lmap = new HashMap(); + HashMap lmap = new HashMap<>(); /* The jar protocol handler to use when creating new URLs */ private URLStreamHandler jarHandler; @@ -142,7 +142,7 @@ public class URLClassPath { if (closed) { return Collections.emptyList(); } - List result = new LinkedList(); + List result = new LinkedList<>(); for (Loader loader : loaders) { try { loader.close(); @@ -234,7 +234,7 @@ public class URLClassPath { */ public Enumeration findResources(final String name, final boolean check) { - return new Enumeration() { + return new Enumeration<>() { private int index = 0; private URL url = null; @@ -281,7 +281,7 @@ public class URLClassPath { */ public Enumeration getResources(final String name, final boolean check) { - return new Enumeration() { + return new Enumeration<>() { private int index = 0; private Resource res = null; @@ -374,7 +374,7 @@ public class URLClassPath { private Loader getLoader(final URL url) throws IOException { try { return java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { + new java.security.PrivilegedExceptionAction<>() { public Loader run() throws IOException { String file = url.getFile(); if (file != null && file.endsWith("/")) { @@ -689,7 +689,7 @@ public class URLClassPath { if (jar == null) { try { java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { + new java.security.PrivilegedExceptionAction<>() { public Void run() throws IOException { if (DEBUG) { System.err.println("Opening " + csu); @@ -870,7 +870,7 @@ public class URLClassPath { if (index == null) return null; - HashSet visited = new HashSet(); + HashSet visited = new HashSet<>(); return getResource(name, check, visited); } @@ -912,7 +912,7 @@ public class URLClassPath { * before */ newLoader = AccessController.doPrivileged( - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public JarLoader run() throws IOException { return new JarLoader(url, handler, lmap); diff --git a/jdk/src/java.base/share/classes/sun/misc/Unsafe.java b/jdk/src/java.base/share/classes/sun/misc/Unsafe.java index ef25c517f03..5ca9cb3059d 100644 --- a/jdk/src/java.base/share/classes/sun/misc/Unsafe.java +++ b/jdk/src/java.base/share/classes/sun/misc/Unsafe.java @@ -631,6 +631,10 @@ public final class Unsafe { /** * Atomically updates Java variable to {@code x} if it is currently * holding {@code expected}. + * + *

                                This operation has memory semantics of a {@code volatile} read + * and write. Corresponds to C11 atomic_compare_exchange_strong. + * * @return {@code true} if successful */ public final native boolean compareAndSwapObject(Object o, long offset, @@ -640,6 +644,10 @@ public final class Unsafe { /** * Atomically updates Java variable to {@code x} if it is currently * holding {@code expected}. + * + *

                                This operation has memory semantics of a {@code volatile} read + * and write. Corresponds to C11 atomic_compare_exchange_strong. + * * @return {@code true} if successful */ public final native boolean compareAndSwapInt(Object o, long offset, @@ -649,6 +657,10 @@ public final class Unsafe { /** * Atomically updates Java variable to {@code x} if it is currently * holding {@code expected}. + * + *

                                This operation has memory semantics of a {@code volatile} read + * and write. Corresponds to C11 atomic_compare_exchange_strong. + * * @return {@code true} if successful */ public final native boolean compareAndSwapLong(Object o, long offset, diff --git a/jdk/src/java.base/share/classes/sun/net/NetworkClient.java b/jdk/src/java.base/share/classes/sun/net/NetworkClient.java index 0f76bf62398..f5cd53c295e 100644 --- a/jdk/src/java.base/share/classes/sun/net/NetworkClient.java +++ b/jdk/src/java.base/share/classes/sun/net/NetworkClient.java @@ -69,7 +69,7 @@ public class NetworkClient { final String encs[] = { null }; AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public Void run() { vals[0] = Integer.getInteger("sun.net.client.defaultReadTimeout", 0).intValue(); vals[1] = Integer.getInteger("sun.net.client.defaultConnectTimeout", 0).intValue(); @@ -154,7 +154,7 @@ public class NetworkClient { if (proxy != null) { if (proxy.type() == Proxy.Type.SOCKS) { s = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public Socket run() { return new Socket(proxy); }}); @@ -201,7 +201,7 @@ public class NetworkClient { if (serverSocket == null) throw new IOException("not connected"); return AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public InetAddress run() { return serverSocket.getLocalAddress(); diff --git a/jdk/src/java.base/share/classes/sun/net/NetworkServer.java b/jdk/src/java.base/share/classes/sun/net/NetworkServer.java index d4a9cc78e5b..6937775d40e 100644 --- a/jdk/src/java.base/share/classes/sun/net/NetworkServer.java +++ b/jdk/src/java.base/share/classes/sun/net/NetworkServer.java @@ -27,6 +27,7 @@ package sun.net; import java.io.*; import java.net.Socket; import java.net.ServerSocket; +import sun.misc.ManagedLocalsThread; /** * This is the base class for network servers. To define a new type @@ -72,7 +73,7 @@ public class NetworkServer implements Runnable, Cloneable { NetworkServer n = (NetworkServer)clone(); n.serverSocket = null; n.clientSocket = ns; - new Thread(n).start(); + new ManagedLocalsThread(n).start(); } catch(Exception e) { System.out.print("Server failure\n"); e.printStackTrace(); @@ -107,7 +108,7 @@ public class NetworkServer implements Runnable, Cloneable { for each new connection. */ final public void startServer(int port) throws IOException { serverSocket = new ServerSocket(port, 50); - serverInstance = new Thread(this); + serverInstance = new ManagedLocalsThread(this); serverInstance.start(); } diff --git a/jdk/src/java.base/share/classes/sun/net/ProgressMonitor.java b/jdk/src/java.base/share/classes/sun/net/ProgressMonitor.java index e9ddce85df6..6aa7b351bad 100644 --- a/jdk/src/java.base/share/classes/sun/net/ProgressMonitor.java +++ b/jdk/src/java.base/share/classes/sun/net/ProgressMonitor.java @@ -64,7 +64,7 @@ public class ProgressMonitor * Return a snapshot of the ProgressSource list */ public ArrayList getProgressSources() { - ArrayList snapshot = new ArrayList(); + ArrayList snapshot = new ArrayList<>(); try { synchronized(progressSourceList) { @@ -114,7 +114,7 @@ public class ProgressMonitor if (progressListenerList.size() > 0) { // Notify progress listener if there is progress change - ArrayList listeners = new ArrayList(); + ArrayList listeners = new ArrayList<>(); // Copy progress listeners to another list to avoid holding locks synchronized(progressListenerList) { @@ -151,7 +151,7 @@ public class ProgressMonitor if (progressListenerList.size() > 0) { // Notify progress listener if there is progress change - ArrayList listeners = new ArrayList(); + ArrayList listeners = new ArrayList<>(); // Copy progress listeners to another list to avoid holding locks synchronized(progressListenerList) { @@ -183,7 +183,7 @@ public class ProgressMonitor if (progressListenerList.size() > 0) { // Notify progress listener if there is progress change - ArrayList listeners = new ArrayList(); + ArrayList listeners = new ArrayList<>(); // Copy progress listeners to another list to avoid holding locks synchronized(progressListenerList) { diff --git a/jdk/src/java.base/share/classes/sun/net/www/MessageHeader.java b/jdk/src/java.base/share/classes/sun/net/www/MessageHeader.java index 34b6307826f..c4ab99ac34c 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/MessageHeader.java +++ b/jdk/src/java.base/share/classes/sun/net/www/MessageHeader.java @@ -244,7 +244,7 @@ class MessageHeader { public synchronized Map> filterAndAddHeaders( String[] excludeList, Map> include) { boolean skipIt = false; - Map> m = new HashMap>(); + Map> m = new HashMap<>(); for (int i = nkeys; --i >= 0;) { if (excludeList != null) { // check if the key is in the excludeList. @@ -260,7 +260,7 @@ class MessageHeader { if (!skipIt) { List l = m.get(keys[i]); if (l == null) { - l = new ArrayList(); + l = new ArrayList<>(); m.put(keys[i], l); } l.add(values[i]); @@ -274,7 +274,7 @@ class MessageHeader { for (Map.Entry> entry: include.entrySet()) { List l = m.get(entry.getKey()); if (l == null) { - l = new ArrayList(); + l = new ArrayList<>(); m.put(entry.getKey(), l); } l.addAll(entry.getValue()); diff --git a/jdk/src/java.base/share/classes/sun/net/www/MimeLauncher.java b/jdk/src/java.base/share/classes/sun/net/www/MimeLauncher.java index ee4fb40eeca..32b3603de82 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/MimeLauncher.java +++ b/jdk/src/java.base/share/classes/sun/net/www/MimeLauncher.java @@ -27,8 +27,9 @@ package sun.net.www; import java.net.URL; import java.io.*; import java.util.StringTokenizer; +import sun.misc.ManagedLocalsThread; -class MimeLauncher extends Thread { +class MimeLauncher extends ManagedLocalsThread { java.net.URLConnection uc; MimeEntry m; String genericTempFileTemplate; diff --git a/jdk/src/java.base/share/classes/sun/net/www/http/HttpCapture.java b/jdk/src/java.base/share/classes/sun/net/www/http/HttpCapture.java index 7035295a372..43eff0435f4 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/http/HttpCapture.java +++ b/jdk/src/java.base/share/classes/sun/net/www/http/HttpCapture.java @@ -64,7 +64,7 @@ public class HttpCapture { private static synchronized void init() { initialized = true; String rulesFile = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public String run() { return NetProperties.get("sun.net.http.captureRules"); } @@ -85,8 +85,8 @@ public class HttpCapture { String[] s = line.split(","); if (s.length == 2) { if (patterns == null) { - patterns = new ArrayList(); - capFiles = new ArrayList(); + patterns = new ArrayList<>(); + capFiles = new ArrayList<>(); } patterns.add(Pattern.compile(s[0].trim())); capFiles.add(s[1].trim()); diff --git a/jdk/src/java.base/share/classes/sun/net/www/http/HttpClient.java b/jdk/src/java.base/share/classes/sun/net/www/http/HttpClient.java index fcdd50943ab..0d7f09c6132 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/http/HttpClient.java +++ b/jdk/src/java.base/share/classes/sun/net/www/http/HttpClient.java @@ -479,7 +479,7 @@ public class HttpClient extends NetworkClient { { try { java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { + new java.security.PrivilegedExceptionAction<>() { public Void run() throws IOException { openServer(server.getHostString(), server.getPort()); return null; diff --git a/jdk/src/java.base/share/classes/sun/net/www/http/KeepAliveCache.java b/jdk/src/java.base/share/classes/sun/net/www/http/KeepAliveCache.java index 16f02d7cdde..42902b0148b 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/http/KeepAliveCache.java +++ b/jdk/src/java.base/share/classes/sun/net/www/http/KeepAliveCache.java @@ -30,6 +30,7 @@ import java.io.NotSerializableException; import java.util.ArrayList; import java.util.HashMap; import java.net.URL; +import sun.misc.InnocuousThread; /** * A class that implements a cache of idle Http connections for keep-alive @@ -93,17 +94,9 @@ public class KeepAliveCache */ final KeepAliveCache cache = this; java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public Void run() { - // We want to create the Keep-Alive-Timer in the - // system threadgroup - ThreadGroup grp = Thread.currentThread().getThreadGroup(); - ThreadGroup parent = null; - while ((parent = grp.getParent()) != null) { - grp = parent; - } - - keepAliveTimer = new Thread(grp, cache, "Keep-Alive-Timer"); + keepAliveTimer = new InnocuousThread(cache, "Keep-Alive-Timer"); keepAliveTimer.setDaemon(true); keepAliveTimer.setPriority(Thread.MAX_PRIORITY - 2); // Set the context class loader to null in order to avoid @@ -185,7 +178,7 @@ public class KeepAliveCache long currentTime = System.currentTimeMillis(); ArrayList keysToRemove - = new ArrayList(); + = new ArrayList<>(); for (KeepAliveKey key : keySet()) { ClientVector v = get(key); diff --git a/jdk/src/java.base/share/classes/sun/net/www/http/KeepAliveStream.java b/jdk/src/java.base/share/classes/sun/net/www/http/KeepAliveStream.java index 9155c4ae8c5..53835df7f6a 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/http/KeepAliveStream.java +++ b/jdk/src/java.base/share/classes/sun/net/www/http/KeepAliveStream.java @@ -26,6 +26,8 @@ package sun.net.www.http; import java.io.*; + +import sun.misc.InnocuousThread; import sun.net.ProgressSource; import sun.net.www.MeteredStream; @@ -171,15 +173,7 @@ class KeepAliveStream extends MeteredStream implements Hurryable { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Void run() { - // We want to create the Keep-Alive-SocketCleaner in the - // system threadgroup - ThreadGroup grp = Thread.currentThread().getThreadGroup(); - ThreadGroup parent = null; - while ((parent = grp.getParent()) != null) { - grp = parent; - } - - cleanerThread = new Thread(grp, queue, "Keep-Alive-SocketCleaner"); + cleanerThread = new InnocuousThread(queue, "Keep-Alive-SocketCleaner"); cleanerThread.setDaemon(true); cleanerThread.setPriority(Thread.MAX_PRIORITY - 2); // Set the context class loader to null in order to avoid diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationHeader.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationHeader.java index 89b4d991ea8..42f692c3738 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationHeader.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationHeader.java @@ -122,7 +122,7 @@ public class AuthenticationHeader { this.dontUseNegotiate = dontUseNegotiate; rsp = response; this.hdrname = hdrname; - schemes = new HashMap(); + schemes = new HashMap<>(); parse(); } diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java index 5f0ee771a91..5ad27159253 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java @@ -62,7 +62,7 @@ class DigestAuthentication extends AuthenticationInfo { static { Boolean b = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public Boolean run() { return NetProperties.getBoolean(compatPropName); } diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java index 2cc199c16f0..a012c3b6a1c 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java @@ -244,7 +244,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { new sun.security.action.GetBooleanAction( "sun.net.http.allowRestrictedHeaders")).booleanValue(); if (!allowRestrictedHeaders) { - restrictedHeaderSet = new HashSet(restrictedHeaders.length); + restrictedHeaderSet = new HashSet<>(restrictedHeaders.length); for (int i=0; i < restrictedHeaders.length; i++) { restrictedHeaderSet.add(restrictedHeaders[i].toLowerCase()); } @@ -413,7 +413,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { final URL url, final RequestorType authType) { return java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public PasswordAuthentication run() { if (logger.isLoggable(PlatformLogger.Level.FINEST)) { logger.finest("Requesting Authentication: host =" + host + " url = " + url); @@ -817,14 +817,14 @@ public class HttpURLConnection extends java.net.HttpURLConnection { } catch (SecurityException se) { /* swallow exception */ } } else { cookieHandler = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public CookieHandler run() { return CookieHandler.getDefault(); } }); } cacheHandler = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public ResponseCache run() { return ResponseCache.getDefault(); } @@ -909,7 +909,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { final boolean result[] = {false}; java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public Void run() { try { InetAddress a1 = InetAddress.getByName(h1); @@ -954,7 +954,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { try { // lookup hostname and use IP address if available host = AccessController.doPrivileged( - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public String run() throws IOException { InetAddress addr = InetAddress.getByName(hostarg); return addr.getHostAddress(); @@ -984,7 +984,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { if (p != null) { try { AccessController.doPrivileged( - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public Void run() throws IOException { plainConnect0(); return null; @@ -1086,7 +1086,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { */ ProxySelector sel = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public ProxySelector run() { return ProxySelector.getDefault(); } @@ -1245,7 +1245,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { if (p != null) { try { return AccessController.doPrivileged( - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public OutputStream run() throws IOException { return getOutputStream0(); } @@ -1423,7 +1423,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { if (p != null) { try { return AccessController.doPrivileged( - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public InputStream run() throws IOException { return getInputStream0(); } @@ -1877,7 +1877,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { final Object[] args = { rememberedException.getMessage() }; IOException chainedException = java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { + new java.security.PrivilegedExceptionAction<>() { public IOException run() throws Exception { return (IOException) rememberedException.getClass() @@ -2204,7 +2204,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { try { final String finalHost = host; addr = java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { + new java.security.PrivilegedExceptionAction<>() { public InetAddress run() throws java.net.UnknownHostException { return InetAddress.getByName(finalHost); @@ -2566,7 +2566,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { if (p != null) { try { return AccessController.doPrivileged( - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public Boolean run() throws IOException { return followRedirect0(loc, stat, locUrl0); } diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/AbstractDelegateHttpsURLConnection.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/AbstractDelegateHttpsURLConnection.java index 9d70053d35f..cb80173b506 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/AbstractDelegateHttpsURLConnection.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/AbstractDelegateHttpsURLConnection.java @@ -261,27 +261,6 @@ public abstract class AbstractDelegateHttpsURLConnection extends } } - /** - * Returns the server's X.509 certificate chain, or null if - * the server did not authenticate. - * - * @deprecated This method returns the deprecated - * {@code javax.security.cert.X509Certificate} type. - * Use {@code getServerCertificates()} instead. - */ - @Deprecated - public javax.security.cert.X509Certificate[] getServerCertificateChain() - throws SSLPeerUnverifiedException { - if (cachedResponse != null) { - throw new UnsupportedOperationException("this method is not supported when using cache"); - } - if (http == null) { - throw new IllegalStateException("connection not yet open"); - } else { - return ((HttpsClient)http).getServerCertificateChain(); - } - } - /** * Returns the server's principal, or throws SSLPeerUnverifiedException * if the server did not authenticate. diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java index 5bc55ed9e50..3aecc419cb2 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java @@ -696,21 +696,6 @@ final class HttpsClient extends HttpClient return session.getPeerCertificates(); } - /** - * Returns the X.509 certificate chain with which the server - * authenticated itself, or null if the server did not authenticate. - * - * @deprecated This method returns the deprecated - * {@code javax.security.cert.X509Certificate} type. - * Use {@code getServerCertificates()} instead. - */ - @Deprecated - javax.security.cert.X509Certificate [] getServerCertificateChain() - throws SSLPeerUnverifiedException - { - return session.getPeerCertificateChain(); - } - /** * Returns the principal with which the server authenticated * itself, or throw a SSLPeerUnverifiedException if the diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java index 5477b2cab80..429079804f0 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java @@ -197,30 +197,6 @@ public class HttpsURLConnectionImpl return delegate.getServerCertificates(); } - /** - * Returns the server's X.509 certificate chain, or null if - * the server did not authenticate. - * - * NOTE: This method is not necessary for the version of this class - * implementing javax.net.ssl.HttpsURLConnection, but provided for - * compatibility with the com.sun.net.ssl.HttpsURLConnection version. - * - * @deprecated This method returns the deprecated - * {@code javax.security.cert.X509Certificate} type. - * Use {@code getServerCertificates()} instead. - */ - @Deprecated - public javax.security.cert.X509Certificate[] getServerCertificateChain() { - try { - return delegate.getServerCertificateChain(); - } catch (SSLPeerUnverifiedException e) { - // this method does not throw an exception as declared in - // com.sun.net.ssl.HttpsURLConnection. - // Return null for compatibility. - return null; - } - } - /** * Returns the principal with which the server authenticated itself, * or throw a SSLPeerUnverifiedException if the server did not authenticate. diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/jar/URLJarFile.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/jar/URLJarFile.java index e7e6ad05ad6..f78e1d28b19 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/jar/URLJarFile.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/jar/URLJarFile.java @@ -213,7 +213,7 @@ public class URLJarFile extends JarFile { /* get the stream before asserting privileges */ try (final InputStream in = url.openConnection().getInputStream()) { result = AccessController.doPrivileged( - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public JarFile run() throws IOException { Path tmpFile = Files.createTempFile("jar_cache", null); try { diff --git a/jdk/src/java.base/share/classes/sun/nio/ch/AsynchronousChannelGroupImpl.java b/jdk/src/java.base/share/classes/sun/nio/ch/AsynchronousChannelGroupImpl.java index a584ce9dbf5..117df2452dc 100644 --- a/jdk/src/java.base/share/classes/sun/nio/ch/AsynchronousChannelGroupImpl.java +++ b/jdk/src/java.base/share/classes/sun/nio/ch/AsynchronousChannelGroupImpl.java @@ -76,7 +76,7 @@ abstract class AsynchronousChannelGroupImpl this.pool = pool; if (pool.isFixedThreadPool()) { - taskQueue = new ConcurrentLinkedQueue(); + taskQueue = new ConcurrentLinkedQueue<>(); } else { taskQueue = null; // not used } @@ -115,7 +115,7 @@ abstract class AsynchronousChannelGroupImpl } private void startInternalThread(final Runnable task) { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { @Override public Void run() { // internal threads should not be visible to application so @@ -246,7 +246,7 @@ abstract class AsynchronousChannelGroupImpl abstract void shutdownHandlerTasks(); private void shutdownExecutors() { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public Void run() { pool.executor().shutdown(); timeoutExecutor.shutdown(); @@ -323,7 +323,7 @@ abstract class AsynchronousChannelGroupImpl task = new Runnable() { @Override public void run() { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { @Override public Void run() { delegate.run(); diff --git a/jdk/src/java.base/share/classes/sun/nio/ch/AsynchronousServerSocketChannelImpl.java b/jdk/src/java.base/share/classes/sun/nio/ch/AsynchronousServerSocketChannelImpl.java index e9521ea4e5b..2d0ef217e3c 100644 --- a/jdk/src/java.base/share/classes/sun/nio/ch/AsynchronousServerSocketChannelImpl.java +++ b/jdk/src/java.base/share/classes/sun/nio/ch/AsynchronousServerSocketChannelImpl.java @@ -228,7 +228,7 @@ abstract class AsynchronousServerSocketChannelImpl static final Set> defaultOptions = defaultOptions(); private static Set> defaultOptions() { - HashSet> set = new HashSet>(2); + HashSet> set = new HashSet<>(2); set.add(StandardSocketOptions.SO_RCVBUF); set.add(StandardSocketOptions.SO_REUSEADDR); return Collections.unmodifiableSet(set); diff --git a/jdk/src/java.base/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java b/jdk/src/java.base/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java index 9899d759b71..16a4d391881 100644 --- a/jdk/src/java.base/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java +++ b/jdk/src/java.base/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java @@ -503,7 +503,7 @@ abstract class AsynchronousSocketChannelImpl static final Set> defaultOptions = defaultOptions(); private static Set> defaultOptions() { - HashSet> set = new HashSet>(5); + HashSet> set = new HashSet<>(5); set.add(StandardSocketOptions.SO_SNDBUF); set.add(StandardSocketOptions.SO_RCVBUF); set.add(StandardSocketOptions.SO_KEEPALIVE); diff --git a/jdk/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java b/jdk/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java index e316facf491..9d4a2e828c1 100644 --- a/jdk/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java +++ b/jdk/src/java.base/share/classes/sun/nio/ch/DatagramChannelImpl.java @@ -294,7 +294,7 @@ class DatagramChannelImpl static final Set> defaultOptions = defaultOptions(); private static Set> defaultOptions() { - HashSet> set = new HashSet>(8); + HashSet> set = new HashSet<>(8); set.add(StandardSocketOptions.SO_SNDBUF); set.add(StandardSocketOptions.SO_RCVBUF); set.add(StandardSocketOptions.SO_REUSEADDR); diff --git a/jdk/src/java.base/share/classes/sun/nio/ch/MembershipKeyImpl.java b/jdk/src/java.base/share/classes/sun/nio/ch/MembershipKeyImpl.java index 5ecc39608e4..4d47b41ad9b 100644 --- a/jdk/src/java.base/share/classes/sun/nio/ch/MembershipKeyImpl.java +++ b/jdk/src/java.base/share/classes/sun/nio/ch/MembershipKeyImpl.java @@ -184,7 +184,7 @@ class MembershipKeyImpl // created blocked set if required and add source address if (blockedSet == null) - blockedSet = new HashSet(); + blockedSet = new HashSet<>(); blockedSet.add(toBlock); } return this; diff --git a/jdk/src/java.base/share/classes/sun/nio/ch/MembershipRegistry.java b/jdk/src/java.base/share/classes/sun/nio/ch/MembershipRegistry.java index 6607fc841d0..9f01c51601f 100644 --- a/jdk/src/java.base/share/classes/sun/nio/ch/MembershipRegistry.java +++ b/jdk/src/java.base/share/classes/sun/nio/ch/MembershipRegistry.java @@ -84,13 +84,13 @@ class MembershipRegistry { InetAddress group = key.group(); List keys; if (groups == null) { - groups = new HashMap>(); + groups = new HashMap<>(); keys = null; } else { keys = groups.get(group); } if (keys == null) { - keys = new LinkedList(); + keys = new LinkedList<>(); groups.put(group, keys); } keys.add(key); diff --git a/jdk/src/java.base/share/classes/sun/nio/ch/SelectorImpl.java b/jdk/src/java.base/share/classes/sun/nio/ch/SelectorImpl.java index db8ce1fd0e1..1693c0cdec6 100644 --- a/jdk/src/java.base/share/classes/sun/nio/ch/SelectorImpl.java +++ b/jdk/src/java.base/share/classes/sun/nio/ch/SelectorImpl.java @@ -52,8 +52,8 @@ public abstract class SelectorImpl protected SelectorImpl(SelectorProvider sp) { super(sp); - keys = new HashSet(); - selectedKeys = new HashSet(); + keys = new HashSet<>(); + selectedKeys = new HashSet<>(); if (Util.atBugLevel("1.4")) { publicKeys = keys; publicSelectedKeys = selectedKeys; diff --git a/jdk/src/java.base/share/classes/sun/nio/ch/ServerSocketChannelImpl.java b/jdk/src/java.base/share/classes/sun/nio/ch/ServerSocketChannelImpl.java index b5b8b05d36f..0274c2e0753 100644 --- a/jdk/src/java.base/share/classes/sun/nio/ch/ServerSocketChannelImpl.java +++ b/jdk/src/java.base/share/classes/sun/nio/ch/ServerSocketChannelImpl.java @@ -182,7 +182,7 @@ class ServerSocketChannelImpl static final Set> defaultOptions = defaultOptions(); private static Set> defaultOptions() { - HashSet> set = new HashSet>(2); + HashSet> set = new HashSet<>(2); set.add(StandardSocketOptions.SO_RCVBUF); set.add(StandardSocketOptions.SO_REUSEADDR); set.add(StandardSocketOptions.IP_TOS); diff --git a/jdk/src/java.base/share/classes/sun/nio/ch/SocketChannelImpl.java b/jdk/src/java.base/share/classes/sun/nio/ch/SocketChannelImpl.java index a72fe07e4a1..0b3a3828ef3 100644 --- a/jdk/src/java.base/share/classes/sun/nio/ch/SocketChannelImpl.java +++ b/jdk/src/java.base/share/classes/sun/nio/ch/SocketChannelImpl.java @@ -229,7 +229,7 @@ class SocketChannelImpl static final Set> defaultOptions = defaultOptions(); private static Set> defaultOptions() { - HashSet> set = new HashSet>(8); + HashSet> set = new HashSet<>(8); set.add(StandardSocketOptions.SO_SNDBUF); set.add(StandardSocketOptions.SO_RCVBUF); set.add(StandardSocketOptions.SO_KEEPALIVE); diff --git a/jdk/src/java.base/share/classes/sun/nio/cs/CharsetMapping.java b/jdk/src/java.base/share/classes/sun/nio/cs/CharsetMapping.java index c5586f0abe5..2d1358c92c7 100644 --- a/jdk/src/java.base/share/classes/sun/nio/cs/CharsetMapping.java +++ b/jdk/src/java.base/share/classes/sun/nio/cs/CharsetMapping.java @@ -135,7 +135,7 @@ public class CharsetMapping { // init the CharsetMapping object from the .dat binary file public static CharsetMapping get(final InputStream is) { - return AccessController.doPrivileged(new PrivilegedAction() { + return AccessController.doPrivileged(new PrivilegedAction<>() { public CharsetMapping run() { return new CharsetMapping().load(is); } diff --git a/jdk/src/java.base/share/classes/sun/nio/fs/AbstractPoller.java b/jdk/src/java.base/share/classes/sun/nio/fs/AbstractPoller.java index 34d4ea4e3bc..039f5b74c2d 100644 --- a/jdk/src/java.base/share/classes/sun/nio/fs/AbstractPoller.java +++ b/jdk/src/java.base/share/classes/sun/nio/fs/AbstractPoller.java @@ -30,6 +30,7 @@ import java.security.AccessController; import java.security.PrivilegedAction; import java.io.IOException; import java.util.*; +import sun.misc.ManagedLocalsThread; /** * Base implementation of background poller thread used in watch service @@ -47,7 +48,7 @@ abstract class AbstractPoller implements Runnable { private boolean shutdown; protected AbstractPoller() { - this.requestList = new LinkedList(); + this.requestList = new LinkedList<>(); this.shutdown = false; } @@ -56,10 +57,10 @@ abstract class AbstractPoller implements Runnable { */ public void start() { final Runnable thisRunnable = this; - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { @Override public Object run() { - Thread thr = new Thread(thisRunnable); + Thread thr = new ManagedLocalsThread(thisRunnable); thr.setDaemon(true); thr.start(); return null; diff --git a/jdk/src/java.base/share/classes/sun/nio/fs/AbstractWatchKey.java b/jdk/src/java.base/share/classes/sun/nio/fs/AbstractWatchKey.java index 132b6e5d845..710e38fc607 100644 --- a/jdk/src/java.base/share/classes/sun/nio/fs/AbstractWatchKey.java +++ b/jdk/src/java.base/share/classes/sun/nio/fs/AbstractWatchKey.java @@ -70,8 +70,8 @@ abstract class AbstractWatchKey implements WatchKey { this.watcher = watcher; this.dir = dir; this.state = State.READY; - this.events = new ArrayList>(); - this.lastModifyEvents = new HashMap>(); + this.events = new ArrayList<>(); + this.lastModifyEvents = new HashMap<>(); } final AbstractWatchService watcher() { @@ -146,7 +146,7 @@ abstract class AbstractWatchKey implements WatchKey { // non-repeated event Event ev = - new Event((WatchEvent.Kind)kind, context); + new Event<>((WatchEvent.Kind)kind, context); if (isModify) { lastModifyEvents.put(context, ev); } else if (kind == StandardWatchEventKinds.OVERFLOW) { @@ -163,7 +163,7 @@ abstract class AbstractWatchKey implements WatchKey { public final List> pollEvents() { synchronized (this) { List> result = events; - events = new ArrayList>(); + events = new ArrayList<>(); lastModifyEvents.clear(); return result; } diff --git a/jdk/src/java.base/share/classes/sun/nio/fs/Cancellable.java b/jdk/src/java.base/share/classes/sun/nio/fs/Cancellable.java index 0aa6521f19b..648d4089ce8 100644 --- a/jdk/src/java.base/share/classes/sun/nio/fs/Cancellable.java +++ b/jdk/src/java.base/share/classes/sun/nio/fs/Cancellable.java @@ -25,6 +25,7 @@ package sun.nio.fs; +import sun.misc.ManagedLocalsThread; import sun.misc.Unsafe; import java.util.concurrent.ExecutionException; @@ -117,7 +118,7 @@ abstract class Cancellable implements Runnable { * thread by writing into the memory location that it polls cooperatively. */ static void runInterruptibly(Cancellable task) throws ExecutionException { - Thread t = new Thread(task); + Thread t = new ManagedLocalsThread(task); t.start(); boolean cancelledByInterrupt = false; while (t.isAlive()) { diff --git a/jdk/src/java.base/share/classes/sun/nio/fs/PollingWatchService.java b/jdk/src/java.base/share/classes/sun/nio/fs/PollingWatchService.java index d3d9891223d..bc4af73e762 100644 --- a/jdk/src/java.base/share/classes/sun/nio/fs/PollingWatchService.java +++ b/jdk/src/java.base/share/classes/sun/nio/fs/PollingWatchService.java @@ -35,6 +35,7 @@ import java.io.IOException; import java.util.*; import java.util.concurrent.*; import com.sun.nio.file.SensitivityWatchEventModifier; +import sun.misc.ManagedLocalsThread; /** * Simple WatchService implementation that uses periodic tasks to poll @@ -58,7 +59,7 @@ class PollingWatchService .newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { - Thread t = new Thread(r); + Thread t = new ManagedLocalsThread(r); t.setDaemon(true); return t; }}); diff --git a/jdk/src/java.base/share/classes/sun/reflect/ReflectionFactory.java b/jdk/src/java.base/share/classes/sun/reflect/ReflectionFactory.java index 34c1da25908..3d10f9b18c2 100644 --- a/jdk/src/java.base/share/classes/sun/reflect/ReflectionFactory.java +++ b/jdk/src/java.base/share/classes/sun/reflect/ReflectionFactory.java @@ -375,7 +375,7 @@ public class ReflectionFactory { private static void checkInitted() { if (initted) return; AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public Void run() { // Tests to ensure the system properties table is fully // initialized. This is needed because reflection code is diff --git a/jdk/src/java.base/share/classes/sun/reflect/annotation/AnnotationType.java b/jdk/src/java.base/share/classes/sun/reflect/annotation/AnnotationType.java index 669099019f1..7bef3e6541e 100644 --- a/jdk/src/java.base/share/classes/sun/reflect/annotation/AnnotationType.java +++ b/jdk/src/java.base/share/classes/sun/reflect/annotation/AnnotationType.java @@ -106,16 +106,16 @@ public class AnnotationType { throw new IllegalArgumentException("Not an annotation type"); Method[] methods = - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public Method[] run() { // Initialize memberTypes and defaultValues return annotationClass.getDeclaredMethods(); } }); - memberTypes = new HashMap>(methods.length+1, 1.0f); - memberDefaults = new HashMap(0); - members = new HashMap(methods.length+1, 1.0f); + memberTypes = new HashMap<>(methods.length+1, 1.0f); + memberDefaults = new HashMap<>(0); + members = new HashMap<>(methods.length+1, 1.0f); for (Method method : methods) { if (method.getParameterTypes().length != 0) diff --git a/jdk/src/java.base/share/classes/sun/reflect/misc/FieldUtil.java b/jdk/src/java.base/share/classes/sun/reflect/misc/FieldUtil.java index d0cb48f003f..705597c5ecb 100644 --- a/jdk/src/java.base/share/classes/sun/reflect/misc/FieldUtil.java +++ b/jdk/src/java.base/share/classes/sun/reflect/misc/FieldUtil.java @@ -45,9 +45,4 @@ public final class FieldUtil { ReflectUtil.checkPackageAccess(cls); return cls.getFields(); } - - public static Field[] getDeclaredFields(Class cls) { - ReflectUtil.checkPackageAccess(cls); - return cls.getDeclaredFields(); - } } diff --git a/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS7.java b/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS7.java index 19211ae7b0e..52d7b18bcc4 100644 --- a/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS7.java +++ b/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS7.java @@ -530,7 +530,7 @@ public class PKCS7 { // CRLs (optional) if (crls != null && crls.length != 0) { // cast to X509CRLImpl[] since X509CRLImpl implements DerEncoder - Set implCRLs = new HashSet(crls.length); + Set implCRLs = new HashSet<>(crls.length); for (X509CRL crl: crls) { if (crl instanceof X509CRLImpl) implCRLs.add((X509CRLImpl) crl); @@ -590,7 +590,7 @@ public class PKCS7 { public SignerInfo[] verify(byte[] bytes) throws NoSuchAlgorithmException, SignatureException { - Vector intResult = new Vector(); + Vector intResult = new Vector<>(); for (int i = 0; i < signerInfos.length; i++) { SignerInfo signerInfo = verify(signerInfos[i], bytes); diff --git a/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS9Attributes.java b/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS9Attributes.java index 9adcbd8b34e..d8a7ba7ffa8 100644 --- a/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS9Attributes.java +++ b/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS9Attributes.java @@ -85,8 +85,7 @@ public class PKCS9Attributes { DerInputStream in) throws IOException { if (permittedAttributes != null) { this.permittedAttributes = - new Hashtable( - permittedAttributes.length); + new Hashtable<>(permittedAttributes.length); for (int i = 0; i < permittedAttributes.length; i++) this.permittedAttributes.put(permittedAttributes[i], diff --git a/jdk/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java b/jdk/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java index 8650474f1ca..1f310a2d32f 100644 --- a/jdk/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java +++ b/jdk/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java @@ -237,7 +237,7 @@ public class SignerInfo implements DerEncoder { if (userCert == null) return null; - ArrayList certList = new ArrayList(); + ArrayList certList = new ArrayList<>(); certList.add(userCert); X509Certificate[] pkcsCerts = block.getCertificates(); diff --git a/jdk/src/java.base/share/classes/sun/security/pkcs10/PKCS10.java b/jdk/src/java.base/share/classes/sun/security/pkcs10/PKCS10.java index af4e8a4a178..02ed730b9af 100644 --- a/jdk/src/java.base/share/classes/sun/security/pkcs10/PKCS10.java +++ b/jdk/src/java.base/share/classes/sun/security/pkcs10/PKCS10.java @@ -290,8 +290,9 @@ public class PKCS10 { throw new SignatureException("Cert request was not signed"); + byte[] CRLF = new byte[] {'\r', '\n'}; out.println("-----BEGIN NEW CERTIFICATE REQUEST-----"); - out.println(Base64.getMimeEncoder().encodeToString(encoded)); + out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(encoded)); out.println("-----END NEW CERTIFICATE REQUEST-----"); } diff --git a/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java b/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java index 354a644e37e..1f52015392c 100644 --- a/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java +++ b/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java @@ -716,6 +716,11 @@ public final class PKCS12KeyStore extends KeyStoreSpi { entry.protectedPrivKey = key.clone(); if (chain != null) { + // validate cert-chain + if ((chain.length > 1) && (!validateChain(chain))) { + throw new KeyStoreException("Certificate chain is " + + "not valid"); + } entry.chain = chain.clone(); certificateCount += chain.length; @@ -1490,7 +1495,12 @@ public final class PKCS12KeyStore extends KeyStoreSpi { if (!(issuerDN.equals(subjectDN))) return false; } - return true; + + // Check for loops in the chain. If there are repeated certs, + // the Set of certs in the chain will contain fewer certs than + // the chain + Set set = new HashSet<>(Arrays.asList(certChain)); + return set.size() == certChain.length; } @@ -2070,7 +2080,24 @@ public final class PKCS12KeyStore extends KeyStoreSpi { ArrayList chain = new ArrayList(); X509Certificate cert = findMatchedCertificate(entry); + + mainloop: while (cert != null) { + // Check for loops in the certificate chain + if (!chain.isEmpty()) { + for (X509Certificate chainCert : chain) { + if (cert.equals(chainCert)) { + if (debug != null) { + debug.println("Loop detected in " + + "certificate chain. Skip adding " + + "repeated cert to chain. Subject: " + + cert.getSubjectX500Principal() + .toString()); + } + break mainloop; + } + } + } chain.add(cert); X500Principal issuerDN = cert.getIssuerX500Principal(); if (issuerDN.equals(cert.getSubjectX500Principal())) { diff --git a/jdk/src/java.base/share/classes/sun/security/provider/SeedGenerator.java b/jdk/src/java.base/share/classes/sun/security/provider/SeedGenerator.java index 474e20ed433..acf8b645b62 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/SeedGenerator.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/SeedGenerator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -75,6 +75,7 @@ import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Random; +import sun.misc.ManagedLocalsThread; import sun.security.util.Debug; abstract class SeedGenerator { @@ -164,7 +165,7 @@ abstract class SeedGenerator { md.update(b); java.security.AccessController.doPrivileged - (new java.security.PrivilegedAction() { + (new java.security.PrivilegedAction<>() { @Override public Void run() { try { @@ -294,7 +295,7 @@ abstract class SeedGenerator { final ThreadGroup[] finalsg = new ThreadGroup[1]; Thread t = java.security.AccessController.doPrivileged - (new java.security.PrivilegedAction() { + (new java.security.PrivilegedAction<>() { @Override public Thread run() { ThreadGroup parent, group = @@ -304,7 +305,7 @@ abstract class SeedGenerator { } finalsg[0] = new ThreadGroup (group, "SeedGenerator ThreadGroup"); - Thread newT = new Thread(finalsg[0], + Thread newT = new ManagedLocalsThread(finalsg[0], ThreadedSeedGenerator.this, "SeedGenerator Thread"); newT.setPriority(Thread.MIN_PRIORITY); @@ -341,7 +342,7 @@ abstract class SeedGenerator { // Start some noisy threads try { BogusThread bt = new BogusThread(); - Thread t = new Thread + Thread t = new ManagedLocalsThread (seedGroup, bt, "SeedGenerator Thread"); t.start(); } catch (Exception e) { @@ -500,7 +501,7 @@ abstract class SeedGenerator { final URL device = new URL(deviceName); try { seedStream = java.security.AccessController.doPrivileged - (new java.security.PrivilegedExceptionAction() { + (new java.security.PrivilegedExceptionAction<>() { @Override public InputStream run() throws IOException { /* diff --git a/jdk/src/java.base/share/classes/sun/security/provider/X509Factory.java b/jdk/src/java.base/share/classes/sun/security/provider/X509Factory.java index 46b1a3c8d7d..5fa9416e60d 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/X509Factory.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/X509Factory.java @@ -28,6 +28,8 @@ package sun.security.provider; import java.io.*; import java.util.*; import java.security.cert.*; + +import sun.security.util.Pem; import sun.security.x509.X509CertImpl; import sun.security.x509.X509CRLImpl; import sun.security.pkcs.PKCS7; @@ -633,7 +635,7 @@ public class X509Factory extends CertificateFactorySpi { checkHeaderFooter(header.toString(), footer.toString()); - return Base64.getMimeDecoder().decode(new String(data, 0, pos)); + return Pem.decode(new String(data, 0, pos)); } } diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/Builder.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/Builder.java index 84cbe66ee09..e6b5fc05582 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/Builder.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/Builder.java @@ -102,8 +102,8 @@ public abstract class Builder { /** * Verifies whether the input certificate completes the path. - * When building forward, a trust anchor will complete the path. - * When building reverse, the target certificate will complete the path. + * When building in the forward direction, a trust anchor will + * complete the path. * * @param cert the certificate to test * @return a boolean value indicating whether the cert completes the path. diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java index 890d1a825ba..8f6b0a33670 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java @@ -551,10 +551,10 @@ public class DistributionPointFetcher { // set interim reasons mask to the intersection of // reasons in the DP and onlySomeReasons in the IDP boolean[] idpReasonFlags = reasons.getFlags(); - for (int i = 0; i < idpReasonFlags.length; i++) { - if (idpReasonFlags[i] && pointReasonFlags[i]) { - interimReasonsMask[i] = true; - } + for (int i = 0; i < interimReasonsMask.length; i++) { + interimReasonsMask[i] = + (i < idpReasonFlags.length && idpReasonFlags[i]) && + (i < pointReasonFlags.length && pointReasonFlags[i]); } } else { // set interim reasons mask to the value of @@ -568,7 +568,6 @@ public class DistributionPointFetcher { interimReasonsMask = pointReasonFlags.clone(); } else { // set interim reasons mask to the special value all-reasons - interimReasonsMask = new boolean[9]; Arrays.fill(interimReasonsMask, true); } } @@ -577,7 +576,9 @@ public class DistributionPointFetcher { // not included in the reasons mask boolean oneOrMore = false; for (int i = 0; i < interimReasonsMask.length && !oneOrMore; i++) { - if (!reasonsMask[i] && interimReasonsMask[i]) { + if (interimReasonsMask[i] && + !(i < reasonsMask.length && reasonsMask[i])) + { oneOrMore = true; } } @@ -703,11 +704,11 @@ public class DistributionPointFetcher { } // update reasonsMask - for (int i = 0; i < interimReasonsMask.length; i++) { - if (!reasonsMask[i] && interimReasonsMask[i]) { - reasonsMask[i] = true; - } + for (int i = 0; i < reasonsMask.length; i++) { + reasonsMask[i] = reasonsMask[i] || + (i < interimReasonsMask.length && interimReasonsMask[i]); } + return true; } diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/PKIX.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/PKIX.java index 98c88348adf..e33d4a21a5c 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/PKIX.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/PKIX.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * 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,7 +25,6 @@ package sun.security.provider.certpath; import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; import java.security.PublicKey; import java.security.cert.*; import java.security.interfaces.DSAPublicKey; @@ -194,7 +193,6 @@ class PKIX { static class BuilderParams extends ValidatorParams { private PKIXBuilderParameters params; - private boolean buildForward = true; private List stores; private X500Principal targetSubject; @@ -213,10 +211,6 @@ class PKIX { + "targetCertConstraints parameter must be an " + "X509CertSelector"); } - if (params instanceof SunCertPathBuilderParameters) { - buildForward = - ((SunCertPathBuilderParameters)params).getBuildForward(); - } this.params = params; this.targetSubject = getTargetSubject( certStores(), (X509CertSelector)targetCertConstraints()); @@ -230,7 +224,6 @@ class PKIX { return stores; } int maxPathLength() { return params.getMaxPathLength(); } - boolean buildForward() { return buildForward; } PKIXBuilderParameters params() { return params; } X500Principal targetSubject() { return targetSubject; } diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/ReverseBuilder.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/ReverseBuilder.java deleted file mode 100644 index a70945d65f5..00000000000 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/ReverseBuilder.java +++ /dev/null @@ -1,551 +0,0 @@ -/* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.security.provider.certpath; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.security.Principal; -import java.security.cert.CertificateException; -import java.security.cert.CertPathValidatorException; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.security.cert.PKIXBuilderParameters; -import java.security.cert.PKIXCertPathChecker; -import java.security.cert.PKIXParameters; -import java.security.cert.PKIXReason; -import java.security.cert.TrustAnchor; -import java.security.cert.X509Certificate; -import java.security.cert.X509CertSelector; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.LinkedList; -import java.util.Set; - -import javax.security.auth.x500.X500Principal; - -import sun.security.provider.certpath.PKIX.BuilderParams; -import sun.security.util.Debug; -import sun.security.x509.Extension; -import static sun.security.x509.PKIXExtensions.*; -import sun.security.x509.X500Name; -import sun.security.x509.X509CertImpl; -import sun.security.x509.PolicyMappingsExtension; - -/** - * This class represents a reverse builder, which is able to retrieve - * matching certificates from CertStores and verify a particular certificate - * against a ReverseState. - * - * @since 1.4 - * @author Sean Mullan - * @author Yassir Elley - */ - -class ReverseBuilder extends Builder { - - private Debug debug = Debug.getInstance("certpath"); - - private final Set initPolicies; - - /** - * Initialize the builder with the input parameters. - * - * @param params the parameter set used to build a certification path - */ - ReverseBuilder(BuilderParams buildParams) { - super(buildParams); - - Set initialPolicies = buildParams.initialPolicies(); - initPolicies = new HashSet(); - if (initialPolicies.isEmpty()) { - // if no initialPolicies are specified by user, set - // initPolicies to be anyPolicy by default - initPolicies.add(PolicyChecker.ANY_POLICY); - } else { - initPolicies.addAll(initialPolicies); - } - } - - /** - * Retrieves all certs from the specified CertStores that satisfy the - * requirements specified in the parameters and the current - * PKIX state (name constraints, policy constraints, etc). - * - * @param currentState the current state. - * Must be an instance of ReverseState - * @param certStores list of CertStores - */ - @Override - Collection getMatchingCerts - (State currState, List certStores) - throws CertStoreException, CertificateException, IOException - { - ReverseState currentState = (ReverseState) currState; - - if (debug != null) - debug.println("In ReverseBuilder.getMatchingCerts."); - - /* - * The last certificate could be an EE or a CA certificate - * (we may be building a partial certification path or - * establishing trust in a CA). - * - * Try the EE certs before the CA certs. It will be more - * common to build a path to an end entity. - */ - Collection certs = - getMatchingEECerts(currentState, certStores); - certs.addAll(getMatchingCACerts(currentState, certStores)); - - return certs; - } - - /* - * Retrieves all end-entity certificates which satisfy constraints - * and requirements specified in the parameters and PKIX state. - */ - private Collection getMatchingEECerts - (ReverseState currentState, List certStores) - throws CertStoreException, CertificateException, IOException { - - /* - * Compose a CertSelector to filter out - * certs which do not satisfy requirements. - * - * First, retrieve clone of current target cert constraints, and - * then add more selection criteria based on current validation state. - */ - X509CertSelector sel = (X509CertSelector) targetCertConstraints.clone(); - - /* - * Match on issuer (subject of previous cert) - */ - sel.setIssuer(currentState.subjectDN); - - /* - * Match on certificate validity date. - */ - sel.setCertificateValid(buildParams.date()); - - /* - * Policy processing optimizations - */ - if (currentState.explicitPolicy == 0) - sel.setPolicy(getMatchingPolicies()); - - /* - * If previous cert has a subject key identifier extension, - * use it to match on authority key identifier extension. - */ - /*if (currentState.subjKeyId != null) { - AuthorityKeyIdentifierExtension authKeyId = new AuthorityKeyIdentifierExtension( - (KeyIdentifier) currentState.subjKeyId.get(SubjectKeyIdentifierExtension.KEY_ID), - null, null); - sel.setAuthorityKeyIdentifier(authKeyId.getExtensionValue()); - }*/ - - /* - * Require EE certs - */ - sel.setBasicConstraints(-2); - - /* Retrieve matching certs from CertStores */ - HashSet eeCerts = new HashSet<>(); - addMatchingCerts(sel, certStores, eeCerts, true); - - if (debug != null) { - debug.println("ReverseBuilder.getMatchingEECerts got " - + eeCerts.size() + " certs."); - } - return eeCerts; - } - - /* - * Retrieves all CA certificates which satisfy constraints - * and requirements specified in the parameters and PKIX state. - */ - private Collection getMatchingCACerts - (ReverseState currentState, List certStores) - throws CertificateException, CertStoreException, IOException { - - /* - * Compose a CertSelector to filter out - * certs which do not satisfy requirements. - */ - X509CertSelector sel = new X509CertSelector(); - - /* - * Match on issuer (subject of previous cert) - */ - sel.setIssuer(currentState.subjectDN); - - /* - * Match on certificate validity date. - */ - sel.setCertificateValid(buildParams.date()); - - /* - * Match on target subject name (checks that current cert's - * name constraints permit it to certify target). - * (4 is the integer type for DIRECTORY name). - */ - byte[] subject = targetCertConstraints.getSubjectAsBytes(); - if (subject != null) { - sel.addPathToName(4, subject); - } else { - X509Certificate cert = targetCertConstraints.getCertificate(); - if (cert != null) { - sel.addPathToName(4, - cert.getSubjectX500Principal().getEncoded()); - } - } - - /* - * Policy processing optimizations - */ - if (currentState.explicitPolicy == 0) - sel.setPolicy(getMatchingPolicies()); - - /* - * If previous cert has a subject key identifier extension, - * use it to match on authority key identifier extension. - */ - /*if (currentState.subjKeyId != null) { - AuthorityKeyIdentifierExtension authKeyId = new AuthorityKeyIdentifierExtension( - (KeyIdentifier) currentState.subjKeyId.get(SubjectKeyIdentifierExtension.KEY_ID), - null, null); - sel.setAuthorityKeyIdentifier(authKeyId.getExtensionValue()); - }*/ - - /* - * Require CA certs - */ - sel.setBasicConstraints(0); - - /* Retrieve matching certs from CertStores */ - ArrayList reverseCerts = new ArrayList<>(); - addMatchingCerts(sel, certStores, reverseCerts, true); - - /* Sort remaining certs using name constraints */ - Collections.sort(reverseCerts, new PKIXCertComparator()); - - if (debug != null) - debug.println("ReverseBuilder.getMatchingCACerts got " + - reverseCerts.size() + " certs."); - return reverseCerts; - } - - /* - * This inner class compares 2 PKIX certificates according to which - * should be tried first when building a path to the target. For - * now, the algorithm is to look at name constraints in each cert and those - * which constrain the path closer to the target should be - * ranked higher. Later, we may want to consider other components, - * such as key identifiers. - */ - class PKIXCertComparator implements Comparator { - - private Debug debug = Debug.getInstance("certpath"); - - @Override - public int compare(X509Certificate cert1, X509Certificate cert2) { - - /* - * if either cert certifies the target, always - * put at head of list. - */ - X500Principal targetSubject = buildParams.targetSubject(); - if (cert1.getSubjectX500Principal().equals(targetSubject)) { - return -1; - } - if (cert2.getSubjectX500Principal().equals(targetSubject)) { - return 1; - } - - int targetDist1; - int targetDist2; - try { - X500Name targetSubjectName = X500Name.asX500Name(targetSubject); - targetDist1 = Builder.targetDistance( - null, cert1, targetSubjectName); - targetDist2 = Builder.targetDistance( - null, cert2, targetSubjectName); - } catch (IOException e) { - if (debug != null) { - debug.println("IOException in call to Builder.targetDistance"); - e.printStackTrace(); - } - throw new ClassCastException - ("Invalid target subject distinguished name"); - } - - if (targetDist1 == targetDist2) - return 0; - - if (targetDist1 == -1) - return 1; - - if (targetDist1 < targetDist2) - return -1; - - return 1; - } - } - - /** - * Verifies a matching certificate. - * - * This method executes any of the validation steps in the PKIX path validation - * algorithm which were not satisfied via filtering out non-compliant - * certificates with certificate matching rules. - * - * If the last certificate is being verified (the one whose subject - * matches the target subject, then the steps in Section 6.1.4 of the - * Certification Path Validation algorithm are NOT executed, - * regardless of whether or not the last cert is an end-entity - * cert or not. This allows callers to certify CA certs as - * well as EE certs. - * - * @param cert the certificate to be verified - * @param currentState the current state against which the cert is verified - * @param certPathList the certPathList generated thus far - */ - @Override - void verifyCert(X509Certificate cert, State currState, - List certPathList) - throws GeneralSecurityException - { - if (debug != null) { - debug.println("ReverseBuilder.verifyCert(SN: " - + Debug.toHexString(cert.getSerialNumber()) - + "\n Subject: " + cert.getSubjectX500Principal() + ")"); - } - - ReverseState currentState = (ReverseState) currState; - - /* we don't perform any validation of the trusted cert */ - if (currentState.isInitial()) { - return; - } - - // Don't bother to verify untrusted certificate more. - currentState.untrustedChecker.check(cert, - Collections.emptySet()); - - /* - * check for looping - abort a loop if - * ((we encounter the same certificate twice) AND - * ((policyMappingInhibited = true) OR (no policy mapping - * extensions can be found between the occurrences of the same - * certificate))) - * in order to facilitate the check to see if there are - * any policy mapping extensions found between the occurrences - * of the same certificate, we reverse the certpathlist first - */ - if ((certPathList != null) && (!certPathList.isEmpty())) { - List reverseCertList = new ArrayList<>(); - for (X509Certificate c : certPathList) { - reverseCertList.add(0, c); - } - - boolean policyMappingFound = false; - for (X509Certificate cpListCert : reverseCertList) { - X509CertImpl cpListCertImpl = X509CertImpl.toImpl(cpListCert); - PolicyMappingsExtension policyMappingsExt = - cpListCertImpl.getPolicyMappingsExtension(); - if (policyMappingsExt != null) { - policyMappingFound = true; - } - if (debug != null) - debug.println("policyMappingFound = " + policyMappingFound); - if (cert.equals(cpListCert)) { - if ((buildParams.policyMappingInhibited()) || - (!policyMappingFound)){ - if (debug != null) - debug.println("loop detected!!"); - throw new CertPathValidatorException("loop detected"); - } - } - } - } - - /* check if target cert */ - boolean finalCert = cert.getSubjectX500Principal().equals(buildParams.targetSubject()); - - /* check if CA cert */ - boolean caCert = (cert.getBasicConstraints() != -1 ? true : false); - - /* if there are more certs to follow, verify certain constraints */ - if (!finalCert) { - - /* check if CA cert */ - if (!caCert) - throw new CertPathValidatorException("cert is NOT a CA cert"); - - /* If the certificate was not self-issued, verify that - * remainingCerts is greater than zero - */ - if ((currentState.remainingCACerts <= 0) && !X509CertImpl.isSelfIssued(cert)) { - throw new CertPathValidatorException - ("pathLenConstraint violated, path too long", null, - null, -1, PKIXReason.PATH_TOO_LONG); - } - - /* - * Check keyUsage extension (only if CA cert and not final cert) - */ - KeyChecker.verifyCAKeyUsage(cert); - - } else { - - /* - * If final cert, check that it satisfies specified target - * constraints - */ - if (targetCertConstraints.match(cert) == false) { - throw new CertPathValidatorException("target certificate " + - "constraints check failed"); - } - } - - /* - * Check revocation. - */ - if (buildParams.revocationEnabled() && currentState.revChecker != null) { - currentState.revChecker.check(cert, Collections.emptySet()); - } - - /* Check name constraints if this is not a self-issued cert */ - if (finalCert || !X509CertImpl.isSelfIssued(cert)){ - if (currentState.nc != null) { - try { - if (!currentState.nc.verify(cert)){ - throw new CertPathValidatorException - ("name constraints check failed", null, null, -1, - PKIXReason.INVALID_NAME); - } - } catch (IOException ioe) { - throw new CertPathValidatorException(ioe); - } - } - } - - /* - * Check policy - */ - X509CertImpl certImpl = X509CertImpl.toImpl(cert); - currentState.rootNode = PolicyChecker.processPolicies - (currentState.certIndex, initPolicies, - currentState.explicitPolicy, currentState.policyMapping, - currentState.inhibitAnyPolicy, - buildParams.policyQualifiersRejected(), currentState.rootNode, - certImpl, finalCert); - - /* - * Check CRITICAL private extensions - */ - Set unresolvedCritExts = cert.getCriticalExtensionOIDs(); - if (unresolvedCritExts == null) { - unresolvedCritExts = Collections.emptySet(); - } - - /* - * Check that the signature algorithm is not disabled. - */ - currentState.algorithmChecker.check(cert, unresolvedCritExts); - - for (PKIXCertPathChecker checker : currentState.userCheckers) { - checker.check(cert, unresolvedCritExts); - } - - /* - * Look at the remaining extensions and remove any ones we have - * already checked. If there are any left, throw an exception! - */ - if (!unresolvedCritExts.isEmpty()) { - unresolvedCritExts.remove(BasicConstraints_Id.toString()); - unresolvedCritExts.remove(NameConstraints_Id.toString()); - unresolvedCritExts.remove(CertificatePolicies_Id.toString()); - unresolvedCritExts.remove(PolicyMappings_Id.toString()); - unresolvedCritExts.remove(PolicyConstraints_Id.toString()); - unresolvedCritExts.remove(InhibitAnyPolicy_Id.toString()); - unresolvedCritExts.remove(SubjectAlternativeName_Id.toString()); - unresolvedCritExts.remove(KeyUsage_Id.toString()); - unresolvedCritExts.remove(ExtendedKeyUsage_Id.toString()); - - if (!unresolvedCritExts.isEmpty()) - throw new CertPathValidatorException - ("Unrecognized critical extension(s)", null, null, -1, - PKIXReason.UNRECOGNIZED_CRIT_EXT); - } - - /* - * Check signature. - */ - if (buildParams.sigProvider() != null) { - cert.verify(currentState.pubKey, buildParams.sigProvider()); - } else { - cert.verify(currentState.pubKey); - } - } - - /** - * Verifies whether the input certificate completes the path. - * This checks whether the cert is the target certificate. - * - * @param cert the certificate to test - * @return a boolean value indicating whether the cert completes the path. - */ - @Override - boolean isPathCompleted(X509Certificate cert) { - return cert.getSubjectX500Principal().equals(buildParams.targetSubject()); - } - - /** Adds the certificate to the certPathList - * - * @param cert the certificate to be added - * @param certPathList the certification path list - */ - @Override - void addCertToPath(X509Certificate cert, - LinkedList certPathList) { - certPathList.addLast(cert); - } - - /** Removes final certificate from the certPathList - * - * @param certPathList the certification path list - */ - @Override - void removeFinalCertFromPath(LinkedList certPathList) { - certPathList.removeLast(); - } -} diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/ReverseState.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/ReverseState.java deleted file mode 100644 index c51500308ae..00000000000 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/ReverseState.java +++ /dev/null @@ -1,406 +0,0 @@ -/* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.security.provider.certpath; - -import java.io.IOException; -import java.security.PublicKey; -import java.security.cert.CertificateException; -import java.security.cert.CertPathValidatorException; -import java.security.cert.PKIXCertPathChecker; -import java.security.cert.PKIXRevocationChecker; -import java.security.cert.TrustAnchor; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; -import javax.security.auth.x500.X500Principal; - -import sun.security.provider.certpath.PKIX.BuilderParams; -import sun.security.util.Debug; -import sun.security.x509.NameConstraintsExtension; -import sun.security.x509.SubjectKeyIdentifierExtension; -import sun.security.x509.X509CertImpl; - -/** - * A specification of a reverse PKIX validation state - * which is initialized by each build and updated each time a - * certificate is added to the current path. - * @since 1.4 - * @author Sean Mullan - * @author Yassir Elley - */ - -class ReverseState implements State { - - private static final Debug debug = Debug.getInstance("certpath"); - - /* The subject DN of the last cert in the path */ - X500Principal subjectDN; - - /* The subject public key of the last cert */ - PublicKey pubKey; - - /* The subject key identifier extension (if any) of the last cert */ - SubjectKeyIdentifierExtension subjKeyId; - - /* The PKIX constrained/excluded subtrees state variable */ - NameConstraintsExtension nc; - - /* The PKIX explicit policy, policy mapping, and inhibit_any-policy - state variables */ - int explicitPolicy; - int policyMapping; - int inhibitAnyPolicy; - int certIndex; - PolicyNodeImpl rootNode; - - /* The number of remaining CA certs which may follow in the path. - * -1: previous cert was an EE cert - * 0: only EE certs may follow. - * >0 and userCheckers; - - /* Flag indicating if state is initial (path is just starting) */ - private boolean init = true; - - /* the checker used for revocation status */ - RevocationChecker revChecker; - - /* the algorithm checker */ - AlgorithmChecker algorithmChecker; - - /* the untrusted certificates checker */ - UntrustedChecker untrustedChecker; - - /* the trust anchor used to validate the path */ - TrustAnchor trustAnchor; - - /* Flag indicating if current cert can vouch for the CRL for - * the next cert - */ - boolean crlSign = true; - - /** - * Returns a boolean flag indicating if the state is initial - * (just starting) - * - * @return boolean flag indicating if the state is initial (just starting) - */ - @Override - public boolean isInitial() { - return init; - } - - /** - * Display state for debugging purposes - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("State ["); - sb.append("\n subjectDN of last cert: ").append(subjectDN); - sb.append("\n subjectKeyIdentifier: ").append - (String.valueOf(subjKeyId)); - sb.append("\n nameConstraints: ").append(String.valueOf(nc)); - sb.append("\n certIndex: ").append(certIndex); - sb.append("\n explicitPolicy: ").append(explicitPolicy); - sb.append("\n policyMapping: ").append(policyMapping); - sb.append("\n inhibitAnyPolicy: ").append(inhibitAnyPolicy); - sb.append("\n rootNode: ").append(rootNode); - sb.append("\n remainingCACerts: ").append(remainingCACerts); - sb.append("\n crlSign: ").append(crlSign); - sb.append("\n init: ").append(init); - sb.append("\n]\n"); - return sb.toString(); - } - - /** - * Initialize the state. - * - * @param buildParams builder parameters - */ - public void initState(BuilderParams buildParams) - throws CertPathValidatorException - { - /* - * Initialize number of remainingCACerts. - * Note that -1 maxPathLen implies unlimited. - * 0 implies only an EE cert is acceptable. - */ - int maxPathLen = buildParams.maxPathLength(); - remainingCACerts = (maxPathLen == -1) ? Integer.MAX_VALUE - : maxPathLen; - - /* Initialize explicit policy state variable */ - if (buildParams.explicitPolicyRequired()) { - explicitPolicy = 0; - } else { - // unconstrained if maxPathLen is -1, - // otherwise, we want to initialize this to the value of the - // longest possible path + 1 (i.e. maxpathlen + finalcert + 1) - explicitPolicy = (maxPathLen == -1) ? maxPathLen : maxPathLen + 2; - } - - /* Initialize policy mapping state variable */ - if (buildParams.policyMappingInhibited()) { - policyMapping = 0; - } else { - policyMapping = (maxPathLen == -1) ? maxPathLen : maxPathLen + 2; - } - - /* Initialize inhibit any policy state variable */ - if (buildParams.anyPolicyInhibited()) { - inhibitAnyPolicy = 0; - } else { - inhibitAnyPolicy = (maxPathLen == -1) ? maxPathLen : maxPathLen + 2; - } - - /* Initialize certIndex */ - certIndex = 1; - - /* Initialize policy tree */ - Set initExpPolSet = new HashSet<>(1); - initExpPolSet.add(PolicyChecker.ANY_POLICY); - - rootNode = new PolicyNodeImpl(null, PolicyChecker.ANY_POLICY, null, - false, initExpPolSet, false); - - /* - * Initialize each user-defined checker - * Shallow copy the checkers - */ - userCheckers = new ArrayList<>(buildParams.certPathCheckers()); - /* initialize each checker (just in case) */ - for (PKIXCertPathChecker checker : userCheckers) { - checker.init(false); - } - - /* Start by trusting the cert to sign CRLs */ - crlSign = true; - - init = true; - } - - /** - * Update the state with the specified trust anchor. - * - * @param anchor the most-trusted CA - * @param buildParams builder parameters - */ - public void updateState(TrustAnchor anchor, BuilderParams buildParams) - throws CertificateException, IOException, CertPathValidatorException - { - trustAnchor = anchor; - X509Certificate trustedCert = anchor.getTrustedCert(); - if (trustedCert != null) { - updateState(trustedCert); - } else { - X500Principal caName = anchor.getCA(); - updateState(anchor.getCAPublicKey(), caName); - } - - // The user specified AlgorithmChecker and RevocationChecker may not be - // able to set the trust anchor until now. - boolean revCheckerAdded = false; - for (PKIXCertPathChecker checker : userCheckers) { - if (checker instanceof AlgorithmChecker) { - ((AlgorithmChecker)checker).trySetTrustAnchor(anchor); - } else if (checker instanceof PKIXRevocationChecker) { - if (revCheckerAdded) { - throw new CertPathValidatorException( - "Only one PKIXRevocationChecker can be specified"); - } - // if it's our own, initialize it - if (checker instanceof RevocationChecker) { - ((RevocationChecker)checker).init(anchor, buildParams); - } - ((PKIXRevocationChecker)checker).init(false); - revCheckerAdded = true; - } - } - - // only create a RevocationChecker if revocation is enabled and - // a PKIXRevocationChecker has not already been added - if (buildParams.revocationEnabled() && !revCheckerAdded) { - revChecker = new RevocationChecker(anchor, buildParams); - revChecker.init(false); - } - - init = false; - } - - /** - * Update the state. This method is used when the most-trusted CA is - * a trusted public-key and caName, instead of a trusted cert. - * - * @param pubKey the public key of the trusted CA - * @param subjectDN the subject distinguished name of the trusted CA - */ - private void updateState(PublicKey pubKey, X500Principal subjectDN) { - - /* update subject DN */ - this.subjectDN = subjectDN; - - /* update subject public key */ - this.pubKey = pubKey; - } - - /** - * Update the state with the next certificate added to the path. - * - * @param cert the certificate which is used to update the state - */ - public void updateState(X509Certificate cert) - throws CertificateException, IOException, CertPathValidatorException { - - if (cert == null) { - return; - } - - /* update subject DN */ - subjectDN = cert.getSubjectX500Principal(); - - /* check for key needing to inherit alg parameters */ - X509CertImpl icert = X509CertImpl.toImpl(cert); - PublicKey newKey = cert.getPublicKey(); - if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { - newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); - } - - /* update subject public key */ - pubKey = newKey; - - /* - * if this is a trusted cert (init == true), then we - * don't update any of the remaining fields - */ - if (init) { - init = false; - return; - } - - /* update subject key identifier */ - subjKeyId = icert.getSubjectKeyIdentifierExtension(); - - /* update crlSign */ - crlSign = RevocationChecker.certCanSignCrl(cert); - - /* update current name constraints */ - if (nc != null) { - nc.merge(icert.getNameConstraintsExtension()); - } else { - nc = icert.getNameConstraintsExtension(); - if (nc != null) { - // Make sure we do a clone here, because we're probably - // going to modify this object later and we don't want to - // be sharing it with a Certificate object! - nc = (NameConstraintsExtension) nc.clone(); - } - } - - /* update policy state variables */ - explicitPolicy = - PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); - policyMapping = - PolicyChecker.mergePolicyMapping(policyMapping, icert); - inhibitAnyPolicy = - PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); - certIndex++; - - /* - * Update remaining CA certs - */ - remainingCACerts = - ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); - - init = false; - } - - /** - * Returns a boolean flag indicating if a key lacking necessary key - * algorithm parameters has been encountered. - * - * @return boolean flag indicating if key lacking parameters encountered. - */ - @Override - public boolean keyParamsNeeded() { - /* when building in reverse, we immediately get parameters needed - * or else throw an exception - */ - return false; - } - - /* - * Clone current state. The state is cloned as each cert is - * added to the path. This is necessary if backtracking occurs, - * and a prior state needs to be restored. - * - * Note that this is a SMART clone. Not all fields are fully copied, - * because some of them (e.g., subjKeyId) will - * not have their contents modified by subsequent calls to updateState. - */ - @Override - @SuppressWarnings("unchecked") // Safe casts assuming clone() works correctly - public Object clone() { - try { - ReverseState clonedState = (ReverseState) super.clone(); - - /* clone checkers, if cloneable */ - clonedState.userCheckers = - (ArrayList)userCheckers.clone(); - ListIterator li = - clonedState.userCheckers.listIterator(); - while (li.hasNext()) { - PKIXCertPathChecker checker = li.next(); - if (checker instanceof Cloneable) { - li.set((PKIXCertPathChecker)checker.clone()); - } - } - - /* make copy of name constraints */ - if (nc != null) { - clonedState.nc = (NameConstraintsExtension) nc.clone(); - } - - /* make copy of policy tree */ - if (rootNode != null) { - clonedState.rootNode = rootNode.copyTree(); - } - - return clonedState; - } catch (CloneNotSupportedException e) { - throw new InternalError(e.toString(), e); - } - } -} diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java index 161f565df56..a0c058e795e 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java @@ -35,8 +35,6 @@ import java.security.cert.PKIXReason; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.LinkedList; import java.util.Set; @@ -47,8 +45,7 @@ import static sun.security.x509.PKIXExtensions.*; import sun.security.util.Debug; /** - * This class is able to build certification paths in either the forward - * or reverse directions. + * This class builds certification paths in the forward direction. * *

                                If successful, it returns a certification path which has successfully * satisfied all the constraints and requirements specified in the @@ -102,10 +99,8 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi { /** * Attempts to build a certification path using the Sun build * algorithm from a trusted anchor(s) to a target subject, which must both - * be specified in the input parameter set. By default, this method will - * attempt to build in the forward direction. In order to build in the - * reverse direction, the caller needs to pass in an instance of - * SunCertPathBuilderParameters with the buildForward flag set to false. + * be specified in the input parameter set. This method will + * attempt to build in the forward direction: from the target to the CA. * *

                                The certification path that is constructed is validated * according to the PKIX specification. @@ -162,11 +157,7 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi { policyTreeResult = null; LinkedList certPathList = new LinkedList<>(); try { - if (buildParams.buildForward()) { - buildForward(adjList, certPathList, searchAllCertStores); - } else { - buildReverse(adjList, certPathList); - } + buildForward(adjList, certPathList, searchAllCertStores); } catch (GeneralSecurityException | IOException e) { if (debug != null) { debug.println("SunCertPathBuilder.engineBuild() exception in " @@ -209,81 +200,6 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi { return null; } - /* - * Private build reverse method. - */ - private void buildReverse(List> adjacencyList, - LinkedList certPathList) - throws GeneralSecurityException, IOException - { - if (debug != null) { - debug.println("SunCertPathBuilder.buildReverse()..."); - debug.println("SunCertPathBuilder.buildReverse() InitialPolicies: " - + buildParams.initialPolicies()); - } - - ReverseState currentState = new ReverseState(); - /* Initialize adjacency list */ - adjacencyList.clear(); - adjacencyList.add(new LinkedList()); - - /* - * Perform a search using each trust anchor, until a valid - * path is found - */ - Iterator iter = buildParams.trustAnchors().iterator(); - while (iter.hasNext()) { - TrustAnchor anchor = iter.next(); - - /* check if anchor satisfies target constraints */ - if (anchorIsTarget(anchor, buildParams.targetCertConstraints())) { - this.trustAnchor = anchor; - this.pathCompleted = true; - this.finalPublicKey = anchor.getTrustedCert().getPublicKey(); - break; - } - - // skip anchor if it contains a DSA key with no DSA params - X509Certificate trustedCert = anchor.getTrustedCert(); - PublicKey pubKey = trustedCert != null ? trustedCert.getPublicKey() - : anchor.getCAPublicKey(); - - if (PKIX.isDSAPublicKeyWithoutParams(pubKey)) { - continue; - } - - /* Initialize current state */ - currentState.initState(buildParams); - currentState.updateState(anchor, buildParams); - - currentState.algorithmChecker = new AlgorithmChecker(anchor); - currentState.untrustedChecker = new UntrustedChecker(); - try { - depthFirstSearchReverse(null, currentState, - new ReverseBuilder(buildParams), - adjacencyList, certPathList); - } catch (GeneralSecurityException | IOException e) { - // continue on error if more anchors to try - if (iter.hasNext()) - continue; - else - throw e; - } - - // break out of loop if search is successful - if (pathCompleted) { - break; - } - } - - if (debug != null) { - debug.println("SunCertPathBuilder.buildReverse() returned from " - + "depthFirstSearchReverse()"); - debug.println("SunCertPathBuilder.buildReverse() " - + "certPathList.size: " + certPathList.size()); - } - } - /* * Private build forward method. */ @@ -631,147 +547,6 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi { } } - /* - * This method performs a depth first search for a certification - * path while building reverse which meets the requirements set in - * the parameters object. - * It uses an adjacency list to store all certificates which were - * tried (i.e. at one time added to the path - they may not end up in - * the final path if backtracking occurs). This information can - * be used later to debug or demo the build. - * - * See "Data Structure and Algorithms, by Aho, Hopcroft, and Ullman" - * for an explanation of the DFS algorithm. - * - * @param dN the distinguished name being currently searched for certs - * @param currentState the current PKIX validation state - */ - private void depthFirstSearchReverse(X500Principal dN, - ReverseState currentState, - ReverseBuilder builder, - List> adjList, - LinkedList cpList) - throws GeneralSecurityException, IOException - { - if (debug != null) - debug.println("SunCertPathBuilder.depthFirstSearchReverse(" + dN - + ", " + currentState.toString() + ")"); - - /* - * Find all the certificates issued by dN which - * satisfy the PKIX certification path constraints. - */ - Collection certs = - builder.getMatchingCerts(currentState, buildParams.certStores()); - List vertices = addVertices(certs, adjList); - if (debug != null) - debug.println("SunCertPathBuilder.depthFirstSearchReverse(): " - + "certs.size=" + vertices.size()); - - /* - * For each cert in the collection, verify anything - * that hasn't been checked yet (signature, revocation, etc) - * and check for loops. Call depthFirstSearchReverse() - * recursively for each good cert. - */ - for (Vertex vertex : vertices) { - /** - * Restore state to currentState each time through the loop. - * This is important because some of the user-defined - * checkers modify the state, which MUST be restored if - * the cert eventually fails to lead to the target and - * the next matching cert is tried. - */ - ReverseState nextState = (ReverseState) currentState.clone(); - X509Certificate cert = vertex.getCertificate(); - try { - builder.verifyCert(cert, nextState, cpList); - } catch (GeneralSecurityException gse) { - if (debug != null) - debug.println("SunCertPathBuilder.depthFirstSearchReverse()" - + ": validation failed: " + gse); - vertex.setThrowable(gse); - continue; - } - - /* - * Certificate is good, add it to the path (if it isn't a - * self-signed cert) and update state - */ - if (!currentState.isInitial()) - builder.addCertToPath(cert, cpList); - // save trust anchor - this.trustAnchor = currentState.trustAnchor; - - /* - * Check if path is completed, return ASAP if so. - */ - if (builder.isPathCompleted(cert)) { - if (debug != null) - debug.println("SunCertPathBuilder.depthFirstSearchReverse()" - + ": path completed!"); - pathCompleted = true; - - PolicyNodeImpl rootNode = nextState.rootNode; - - if (rootNode == null) - policyTreeResult = null; - else { - policyTreeResult = rootNode.copyTree(); - ((PolicyNodeImpl)policyTreeResult).setImmutable(); - } - - /* - * Extract and save the final target public key - */ - finalPublicKey = cert.getPublicKey(); - if (PKIX.isDSAPublicKeyWithoutParams(finalPublicKey)) { - finalPublicKey = - BasicChecker.makeInheritedParamsKey - (finalPublicKey, currentState.pubKey); - } - - return; - } - - /* Update the PKIX state */ - nextState.updateState(cert); - - /* - * Append an entry for cert in adjacency list and - * set index for current vertex. - */ - adjList.add(new LinkedList()); - vertex.setIndex(adjList.size() - 1); - - /* recursively search for matching certs at next dN */ - depthFirstSearchReverse(cert.getSubjectX500Principal(), nextState, - builder, adjList, cpList); - - /* - * If path has been completed, return ASAP! - */ - if (pathCompleted) { - return; - } else { - /* - * If we get here, it means we have searched all possible - * certs issued by the dN w/o finding any matching certs. This - * means we have to backtrack to the previous cert in the path - * and try some other paths. - */ - if (debug != null) - debug.println("SunCertPathBuilder.depthFirstSearchReverse()" - + ": backtracking"); - if (!currentState.isInitial()) - builder.removeFinalCertFromPath(cpList); - } - } - if (debug != null) - debug.println("SunCertPathBuilder.depthFirstSearchReverse() all " - + "certs in this adjacency list checked"); - } - /* * Adds a collection of matching certificates to the * adjacency list. diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/SunCertPathBuilderParameters.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/SunCertPathBuilderParameters.java deleted file mode 100644 index 186e2527328..00000000000 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/SunCertPathBuilderParameters.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.security.provider.certpath; - -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.cert.*; -import java.util.Set; - -/** - * This class specifies the set of parameters used as input for the Sun - * certification path build algorithm. It is identical to PKIXBuilderParameters - * with the addition of a buildForward parameter which allows - * the caller to specify whether or not the path should be constructed in - * the forward direction. - * - * The default for the buildForward parameter is - * true, which means that the build algorithm should construct paths - * from the target subject back to the trusted anchor. - * - * @since 1.4 - * @author Sean Mullan - * @author Yassir Elley - */ -public class SunCertPathBuilderParameters extends PKIXBuilderParameters { - - private boolean buildForward = true; - - /** - * Creates an instance of SunCertPathBuilderParameters with the - * specified parameter values. - * - * @param trustAnchors a Set of TrustAnchors - * @param targetConstraints a CertSelector specifying the - * constraints on the target certificate - * @throws InvalidAlgorithmParameterException if the specified - * Set is empty (trustAnchors.isEmpty() == true) - * @throws NullPointerException if the specified Set is - * null - * @throws ClassCastException if any of the elements in the Set - * are not of type java.security.cert.TrustAnchor - */ - public SunCertPathBuilderParameters(Set trustAnchors, - CertSelector targetConstraints) throws InvalidAlgorithmParameterException - { - super(trustAnchors, targetConstraints); - setBuildForward(true); - } - - /** - * Creates an instance of SunCertPathBuilderParameters that - * uses the specified KeyStore to populate the set - * of most-trusted CA certificates. - * - * @param keystore A keystore from which the set of most-trusted - * CA certificates will be populated. - * @param targetConstraints a CertSelector specifying the - * constraints on the target certificate - * @throws KeyStoreException if the keystore has not been initialized. - * @throws InvalidAlgorithmParameterException if the keystore does - * not contain at least one trusted certificate entry - * @throws NullPointerException if the keystore is null - */ - public SunCertPathBuilderParameters(KeyStore keystore, - CertSelector targetConstraints) - throws KeyStoreException, InvalidAlgorithmParameterException - { - super(keystore, targetConstraints); - setBuildForward(true); - } - - /** - * Returns the value of the buildForward flag. - * - * @return the value of the buildForward flag - */ - public boolean getBuildForward() { - return this.buildForward; - } - - /** - * Sets the value of the buildForward flag. If true, paths - * are built from the target subject to the trusted anchor. - * If false, paths are built from the trusted anchor to the - * target subject. The default value if not specified is true. - * - * @param buildForward the value of the buildForward flag - */ - public void setBuildForward(boolean buildForward) { - this.buildForward = buildForward; - } - - /** - * Returns a formatted string describing the parameters. - * - * @return a formatted string describing the parameters. - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[\n"); - sb.append(super.toString()); - sb.append(" Build Forward Flag: " + String.valueOf(buildForward) + "\n"); - sb.append("]\n"); - return sb.toString(); - } -} diff --git a/jdk/src/java.base/share/classes/sun/security/rsa/RSACore.java b/jdk/src/java.base/share/classes/sun/security/rsa/RSACore.java index 81b4e3f986d..7e933e5b758 100644 --- a/jdk/src/java.base/share/classes/sun/security/rsa/RSACore.java +++ b/jdk/src/java.base/share/classes/sun/security/rsa/RSACore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -102,12 +102,24 @@ public final class RSACore { /** * Perform an RSA private key operation. Uses CRT if the key is a - * CRT key. + * CRT key with additional verification check after the signature + * is computed. */ + @Deprecated public static byte[] rsa(byte[] msg, RSAPrivateKey key) throws BadPaddingException { + return rsa(msg, key, true); + } + + /** + * Perform an RSA private key operation. Uses CRT if the key is a + * CRT key. Set 'verify' to true if this function is used for + * generating a signature. + */ + public static byte[] rsa(byte[] msg, RSAPrivateKey key, boolean verify) + throws BadPaddingException { if (key instanceof RSAPrivateCrtKey) { - return crtCrypt(msg, (RSAPrivateCrtKey)key); + return crtCrypt(msg, (RSAPrivateCrtKey)key, verify); } else { return priCrypt(msg, key.getModulus(), key.getPrivateExponent()); } @@ -148,10 +160,11 @@ public final class RSACore { * RSA private key operations with CRT. Algorithm and variable naming * are taken from PKCS#1 v2.1, section 5.1.2. */ - private static byte[] crtCrypt(byte[] msg, RSAPrivateCrtKey key) - throws BadPaddingException { + private static byte[] crtCrypt(byte[] msg, RSAPrivateCrtKey key, + boolean verify) throws BadPaddingException { BigInteger n = key.getModulus(); - BigInteger c = parseMsg(msg, n); + BigInteger c0 = parseMsg(msg, n); + BigInteger c = c0; BigInteger p = key.getPrimeP(); BigInteger q = key.getPrimeQ(); BigInteger dP = key.getPrimeExponentP(); @@ -184,6 +197,9 @@ public final class RSACore { if (ENABLE_BLINDING) { m = m.multiply(brp.v).mod(n); } + if (verify && !c0.equals(m.modPow(e, n))) { + throw new BadPaddingException("RSA private key operation failed"); + } return toByteArray(m, getByteLength(n)); } diff --git a/jdk/src/java.base/share/classes/sun/security/rsa/RSASignature.java b/jdk/src/java.base/share/classes/sun/security/rsa/RSASignature.java index 959700f22cd..d5ba1f82621 100644 --- a/jdk/src/java.base/share/classes/sun/security/rsa/RSASignature.java +++ b/jdk/src/java.base/share/classes/sun/security/rsa/RSASignature.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -173,7 +173,7 @@ public abstract class RSASignature extends SignatureSpi { try { byte[] encoded = encodeSignature(digestOID, digest); byte[] padded = padding.pad(encoded); - byte[] encrypted = RSACore.rsa(padded, privateKey); + byte[] encrypted = RSACore.rsa(padded, privateKey, true); return encrypted; } catch (GeneralSecurityException e) { throw new SignatureException("Could not sign data", e); diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java b/jdk/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java index cb4f54eb125..ea4d2a404fc 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java @@ -293,7 +293,7 @@ final class ClientHandshaker extends Handshaker { case K_ECDH_RSA: throw new SSLProtocolException( "Protocol violation: server sent a server key exchange" - + "message for key exchange " + keyExchange); + + " message for key exchange " + keyExchange); case K_KRB5: case K_KRB5_EXPORT: throw new SSLProtocolException( diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java b/jdk/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java index 8cf95a81eed..104d40ddb83 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/SSLSocketImpl.java @@ -39,6 +39,7 @@ import java.util.concurrent.locks.ReentrantLock; import javax.crypto.BadPaddingException; import javax.net.ssl.*; +import sun.misc.ManagedLocalsThread; /** * Implementation of an SSL socket. This is a normal connection type @@ -1078,8 +1079,10 @@ final public class SSLSocketImpl extends BaseSSLSocketImpl { HandshakeCompletedEvent event = new HandshakeCompletedEvent(this, sess); - Thread t = new NotifyHandshakeThread( - handshakeListeners.entrySet(), event); + Thread t = new ManagedLocalsThread( + new NotifyHandshake( + handshakeListeners.entrySet(), event), + "HandshakeCompletedNotify-Thread"); t.start(); } } @@ -2575,17 +2578,16 @@ final public class SSLSocketImpl extends BaseSSLSocketImpl { // events. This ensures that the notifications don't block the // protocol state machine. // - private static class NotifyHandshakeThread extends Thread { + private static class NotifyHandshake implements Runnable { private Set> targets; // who gets notified private HandshakeCompletedEvent event; // the notification - NotifyHandshakeThread( + NotifyHandshake( Set> entrySet, HandshakeCompletedEvent e) { - super("HandshakeCompletedNotify-Thread"); targets = new HashSet<>(entrySet); // clone the entry set event = e; } diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/SunJSSE.java b/jdk/src/java.base/share/classes/sun/security/ssl/SunJSSE.java index cfd8e609ae4..7b1a67b4d7d 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/SunJSSE.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/SunJSSE.java @@ -148,7 +148,7 @@ public abstract class SunJSSE extends java.security.Provider { } private void registerAlgorithms(final boolean isfips) { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { @Override public Object run() { doRegister(isfips); diff --git a/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java b/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java index faf8d58dae0..c1e58b5714f 100644 --- a/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java +++ b/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java @@ -80,6 +80,7 @@ import sun.security.pkcs.PKCS9Attribute; import sun.security.tools.KeyStoreUtil; import sun.security.tools.PathList; import sun.security.util.DerValue; +import sun.security.util.Pem; import sun.security.x509.*; import static java.security.KeyStore.*; @@ -100,6 +101,8 @@ import static sun.security.tools.keytool.Main.Option.*; */ public final class Main { + private static final byte[] CRLF = new byte[] {'\r', '\n'}; + private boolean debug = false; private Command command = null; private String sigAlgName = null; @@ -1266,7 +1269,7 @@ public final class Main { sb.append(s); } } - byte[] rawReq = Base64.getMimeDecoder().decode(new String(sb)); + byte[] rawReq = Pem.decode(new String(sb)); PKCS10 req = new PKCS10(rawReq); info.set(X509CertInfo.KEY, new CertificateX509Key(req.getSubjectPublicKeyInfo())); @@ -1343,7 +1346,7 @@ public final class Main { crl.sign(privateKey, sigAlgName); if (rfc) { out.println("-----BEGIN X509 CRL-----"); - out.println(Base64.getMimeEncoder().encodeToString(crl.getEncodedInternal())); + out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(crl.getEncodedInternal())); out.println("-----END X509 CRL-----"); } else { out.write(crl.getEncodedInternal()); @@ -2304,7 +2307,7 @@ public final class Main { if (rfc) { X509CRL xcrl = (X509CRL)crl; out.println("-----BEGIN X509 CRL-----"); - out.println(Base64.getMimeEncoder().encodeToString(xcrl.getEncoded())); + out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(xcrl.getEncoded())); out.println("-----END X509 CRL-----"); } else { out.println(crl.toString()); @@ -2331,7 +2334,7 @@ public final class Main { sb.append(s); } } - PKCS10 req = new PKCS10(Base64.getMimeDecoder().decode(new String(sb))); + PKCS10 req = new PKCS10(Pem.decode(new String(sb))); PublicKey pkey = req.getSubjectPublicKeyInfo(); out.printf(rb.getString("PKCS.10.Certificate.Request.Version.1.0.Subject.s.Public.Key.s.format.s.key."), @@ -3115,7 +3118,7 @@ public final class Main { { if (rfc) { out.println(X509Factory.BEGIN_CERT); - out.println(Base64.getMimeEncoder().encodeToString(cert.getEncoded())); + out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(cert.getEncoded())); out.println(X509Factory.END_CERT); } else { out.write(cert.getEncoded()); // binary diff --git a/jdk/src/java.base/share/classes/sun/security/util/DerInputStream.java b/jdk/src/java.base/share/classes/sun/security/util/DerInputStream.java index 8d04d5ab9ed..264bfd0e9c7 100644 --- a/jdk/src/java.base/share/classes/sun/security/util/DerInputStream.java +++ b/jdk/src/java.base/share/classes/sun/security/util/DerInputStream.java @@ -394,7 +394,7 @@ public class DerInputStream { /* * Pull values out of the stream. */ - Vector vec = new Vector(startLen); + Vector vec = new Vector<>(startLen); DerValue value; do { diff --git a/jdk/src/java.base/share/classes/sun/security/util/ManifestDigester.java b/jdk/src/java.base/share/classes/sun/security/util/ManifestDigester.java index fc9ccd3d552..5314e69a14e 100644 --- a/jdk/src/java.base/share/classes/sun/security/util/ManifestDigester.java +++ b/jdk/src/java.base/share/classes/sun/security/util/ManifestDigester.java @@ -110,7 +110,7 @@ public class ManifestDigester { public ManifestDigester(byte bytes[]) { rawBytes = bytes; - entries = new HashMap(); + entries = new HashMap<>(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); diff --git a/jdk/src/java.base/share/classes/sun/security/util/ManifestEntryVerifier.java b/jdk/src/java.base/share/classes/sun/security/util/ManifestEntryVerifier.java index 39f356eec0f..6fcc26143e2 100644 --- a/jdk/src/java.base/share/classes/sun/security/util/ManifestEntryVerifier.java +++ b/jdk/src/java.base/share/classes/sun/security/util/ManifestEntryVerifier.java @@ -77,9 +77,9 @@ public class ManifestEntryVerifier { */ public ManifestEntryVerifier(Manifest man) { - createdDigests = new HashMap(11); - digests = new ArrayList(); - manifestHashes = new ArrayList(); + createdDigests = new HashMap<>(11); + digests = new ArrayList<>(); + manifestHashes = new ArrayList<>(); this.man = man; } diff --git a/jdk/src/java.base/share/classes/sun/security/util/Pem.java b/jdk/src/java.base/share/classes/sun/security/util/Pem.java new file mode 100644 index 00000000000..7e7a0e6d5fb --- /dev/null +++ b/jdk/src/java.base/share/classes/sun/security/util/Pem.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.security.util; + +import java.io.IOException; +import java.util.Base64; + +/** + * The Length interface defines the length of an object + */ +public class Pem { + + /** + * Decodes a PEM-encoded block. + * + * @param input the input string, according to RFC 1421, can only contain + * characters in the base-64 alphabet and whitespaces. + * @return the decoded bytes + * @throws java.io.IOException if input is invalid + */ + public static byte[] decode(String input) throws IOException { + byte[] src = input.replaceAll("\\s+", "").getBytes(); + try { + return Base64.getDecoder().decode(src); + } catch (IllegalArgumentException e) { + throw new IOException(e); + } + } +} diff --git a/jdk/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java b/jdk/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java index 0d1e66287c9..51b296544b2 100644 --- a/jdk/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java +++ b/jdk/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java @@ -203,7 +203,7 @@ public class SignatureFileVerifier { private MessageDigest getDigest(String algorithm) { if (createdDigests == null) - createdDigests = new HashMap(); + createdDigests = new HashMap<>(); MessageDigest digest = createdDigests.get(algorithm); @@ -523,7 +523,7 @@ public class SignatureFileVerifier { ArrayList chain = info.getCertificateChain(block); CertPath certChain = certificateFactory.generateCertPath(chain); if (signers == null) { - signers = new ArrayList(); + signers = new ArrayList<>(); } // Append the new code signer signers.add(new CodeSigner(certChain, info.getTimestamp())); diff --git a/jdk/src/java.base/share/classes/sun/security/validator/EndEntityChecker.java b/jdk/src/java.base/share/classes/sun/security/validator/EndEntityChecker.java index 4ca79f086b1..0ecdaa18b54 100644 --- a/jdk/src/java.base/share/classes/sun/security/validator/EndEntityChecker.java +++ b/jdk/src/java.base/share/classes/sun/security/validator/EndEntityChecker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -132,26 +132,33 @@ class EndEntityChecker { return new EndEntityChecker(type, variant); } - void check(X509Certificate cert, Object parameter) - throws CertificateException { + void check(X509Certificate cert, Object parameter, + boolean checkUnresolvedCritExts) throws CertificateException { if (variant.equals(Validator.VAR_GENERIC)) { - // no checks - return; - } else if (variant.equals(Validator.VAR_TLS_SERVER)) { - checkTLSServer(cert, (String)parameter); + return; // no checks + } + + Set exts = getCriticalExtensions(cert); + if (variant.equals(Validator.VAR_TLS_SERVER)) { + checkTLSServer(cert, (String)parameter, exts); } else if (variant.equals(Validator.VAR_TLS_CLIENT)) { - checkTLSClient(cert); + checkTLSClient(cert, exts); } else if (variant.equals(Validator.VAR_CODE_SIGNING)) { - checkCodeSigning(cert); + checkCodeSigning(cert, exts); } else if (variant.equals(Validator.VAR_JCE_SIGNING)) { - checkCodeSigning(cert); + checkCodeSigning(cert, exts); } else if (variant.equals(Validator.VAR_PLUGIN_CODE_SIGNING)) { - checkCodeSigning(cert); + checkCodeSigning(cert, exts); } else if (variant.equals(Validator.VAR_TSA_SERVER)) { - checkTSAServer(cert); + checkTSAServer(cert, exts); } else { throw new CertificateException("Unknown variant: " + variant); } + + // if neither VAR_GENERIC variant nor unknown variant + if (checkUnresolvedCritExts) { + checkRemainingExtensions(exts); + } } /** @@ -219,10 +226,8 @@ class EndEntityChecker { * authentication. * @throws CertificateException if not. */ - private void checkTLSClient(X509Certificate cert) + private void checkTLSClient(X509Certificate cert, Set exts) throws CertificateException { - Set exts = getCriticalExtensions(cert); - if (checkKeyUsage(cert, KU_SIGNATURE) == false) { throw new ValidatorException ("KeyUsage does not allow digital signatures", @@ -245,8 +250,6 @@ class EndEntityChecker { exts.remove(SimpleValidator.OID_KEY_USAGE); exts.remove(SimpleValidator.OID_EXTENDED_KEY_USAGE); exts.remove(SimpleValidator.OID_NETSCAPE_CERT_TYPE); - - checkRemainingExtensions(exts); } /** @@ -255,10 +258,8 @@ class EndEntityChecker { * specification for details. * @throws CertificateException if not. */ - private void checkTLSServer(X509Certificate cert, String parameter) - throws CertificateException { - Set exts = getCriticalExtensions(cert); - + private void checkTLSServer(X509Certificate cert, String parameter, + Set exts) throws CertificateException { if (KU_SERVER_ENCRYPTION.contains(parameter)) { if (checkKeyUsage(cert, KU_KEY_ENCIPHERMENT) == false) { throw new ValidatorException @@ -303,18 +304,14 @@ class EndEntityChecker { exts.remove(SimpleValidator.OID_KEY_USAGE); exts.remove(SimpleValidator.OID_EXTENDED_KEY_USAGE); exts.remove(SimpleValidator.OID_NETSCAPE_CERT_TYPE); - - checkRemainingExtensions(exts); } /** * Check whether this certificate can be used for code signing. * @throws CertificateException if not. */ - private void checkCodeSigning(X509Certificate cert) + private void checkCodeSigning(X509Certificate cert, Set exts) throws CertificateException { - Set exts = getCriticalExtensions(cert); - if (checkKeyUsage(cert, KU_SIGNATURE) == false) { throw new ValidatorException ("KeyUsage does not allow digital signatures", @@ -341,8 +338,6 @@ class EndEntityChecker { // remove extensions we checked exts.remove(SimpleValidator.OID_KEY_USAGE); exts.remove(SimpleValidator.OID_EXTENDED_KEY_USAGE); - - checkRemainingExtensions(exts); } /** @@ -350,10 +345,8 @@ class EndEntityChecker { * server (see RFC 3161, section 2.3). * @throws CertificateException if not. */ - private void checkTSAServer(X509Certificate cert) + private void checkTSAServer(X509Certificate cert, Set exts) throws CertificateException { - Set exts = getCriticalExtensions(cert); - if (checkKeyUsage(cert, KU_SIGNATURE) == false) { throw new ValidatorException ("KeyUsage does not allow digital signatures", @@ -376,7 +369,5 @@ class EndEntityChecker { // remove extensions we checked exts.remove(SimpleValidator.OID_KEY_USAGE); exts.remove(SimpleValidator.OID_EXTENDED_KEY_USAGE); - - checkRemainingExtensions(exts); } } diff --git a/jdk/src/java.base/share/classes/sun/security/validator/Validator.java b/jdk/src/java.base/share/classes/sun/security/validator/Validator.java index 863566c7357..dd880a7b2dd 100644 --- a/jdk/src/java.base/share/classes/sun/security/validator/Validator.java +++ b/jdk/src/java.base/share/classes/sun/security/validator/Validator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -143,6 +143,7 @@ public abstract class Validator { */ public final static String VAR_PLUGIN_CODE_SIGNING = "plugin code signing"; + private final String type; final EndEntityChecker endEntityChecker; final String variant; @@ -154,6 +155,7 @@ public abstract class Validator { volatile Date validationDate; Validator(String type, String variant) { + this.type = type; this.variant = variant; endEntityChecker = EndEntityChecker.getInstance(type, variant); } @@ -261,7 +263,16 @@ public abstract class Validator { // omit EE extension check if EE cert is also trust anchor if (chain.length > 1) { - endEntityChecker.check(chain[0], parameter); + // EndEntityChecker does not need to check unresolved critical + // extensions when validating with a TYPE_PKIX Validator. + // A TYPE_PKIX Validator will already have run checks on all + // certs' extensions, including checks by any PKIXCertPathCheckers + // included in the PKIXParameters, so the extra checks would be + // redundant. + boolean checkUnresolvedCritExts = + (type == TYPE_PKIX) ? false : true; + endEntityChecker.check(chain[0], parameter, + checkUnresolvedCritExts); } return chain; diff --git a/jdk/src/java.base/share/classes/sun/security/x509/AVA.java b/jdk/src/java.base/share/classes/sun/security/x509/AVA.java index fd3a3544592..d1f94fb23a4 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/AVA.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/AVA.java @@ -307,7 +307,7 @@ public class AVA implements DerEncoder { // doublequote. int c = readChar(in, "Quoted string did not end in quote"); - List embeddedHex = new ArrayList(); + List embeddedHex = new ArrayList<>(); boolean isPrintableString = true; while (c != '"') { if (c == '\\') { diff --git a/jdk/src/java.base/share/classes/sun/security/x509/AlgorithmId.java b/jdk/src/java.base/share/classes/sun/security/x509/AlgorithmId.java index 68068e6f3f1..294888bfaf4 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/AlgorithmId.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/AlgorithmId.java @@ -571,7 +571,7 @@ public class AlgorithmId implements Serializable, DerEncoder { break; } if (oidTable == null) { - oidTable = new HashMap(); + oidTable = new HashMap<>(); } oidString = alias.substring(index); String stdAlgName = provs[i].getProperty(alias); @@ -588,7 +588,7 @@ public class AlgorithmId implements Serializable, DerEncoder { } if (oidTable == null) { - oidTable = new HashMap(1); + oidTable = new HashMap<>(1); } initOidTable = true; } @@ -887,7 +887,7 @@ public class AlgorithmId implements Serializable, DerEncoder { */ sha1WithDSA_oid = ObjectIdentifier.newInternal(dsaWithSHA1_PKIX_data); - nameTable = new HashMap(); + nameTable = new HashMap<>(); nameTable.put(MD5_oid, "MD5"); nameTable.put(MD2_oid, "MD2"); nameTable.put(SHA_oid, "SHA-1"); diff --git a/jdk/src/java.base/share/classes/sun/security/x509/CertificatePolicySet.java b/jdk/src/java.base/share/classes/sun/security/x509/CertificatePolicySet.java index 1bb3aa8de0d..89527d657bd 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/CertificatePolicySet.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/CertificatePolicySet.java @@ -58,7 +58,7 @@ public class CertificatePolicySet { * @exception IOException on decoding errors. */ public CertificatePolicySet(DerInputStream in) throws IOException { - ids = new Vector(); + ids = new Vector<>(); DerValue[] seq = in.getSequence(5); for (int i = 0; i < seq.length; i++) { diff --git a/jdk/src/java.base/share/classes/sun/security/x509/GeneralSubtrees.java b/jdk/src/java.base/share/classes/sun/security/x509/GeneralSubtrees.java index 9c5e6212c1a..2d6e3a1df21 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/GeneralSubtrees.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/GeneralSubtrees.java @@ -59,11 +59,11 @@ public class GeneralSubtrees implements Cloneable { * The default constructor for the class. */ public GeneralSubtrees() { - trees = new ArrayList(); + trees = new ArrayList<>(); } private GeneralSubtrees(GeneralSubtrees source) { - trees = new ArrayList(source.trees); + trees = new ArrayList<>(source.trees); } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/KeyUsageExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/KeyUsageExtension.java index 0f1242d63d9..f02d8eeb636 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/KeyUsageExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/KeyUsageExtension.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -83,7 +83,8 @@ implements CertAttrSet { * @param position the position in the bit string to check. */ private boolean isSet(int position) { - return bitString[position]; + return (position < bitString.length) && + bitString[position]; } /** @@ -275,41 +276,40 @@ implements CertAttrSet { * Returns a printable representation of the KeyUsage. */ public String toString() { - String s = super.toString() + "KeyUsage [\n"; + StringBuilder sb = new StringBuilder(); + sb.append(super.toString()); + sb.append("KeyUsage [\n"); - try { - if (isSet(0)) { - s += " DigitalSignature\n"; - } - if (isSet(1)) { - s += " Non_repudiation\n"; - } - if (isSet(2)) { - s += " Key_Encipherment\n"; - } - if (isSet(3)) { - s += " Data_Encipherment\n"; - } - if (isSet(4)) { - s += " Key_Agreement\n"; - } - if (isSet(5)) { - s += " Key_CertSign\n"; - } - if (isSet(6)) { - s += " Crl_Sign\n"; - } - if (isSet(7)) { - s += " Encipher_Only\n"; - } - if (isSet(8)) { - s += " Decipher_Only\n"; - } - } catch (ArrayIndexOutOfBoundsException ex) {} + if (isSet(0)) { + sb.append(" DigitalSignature\n"); + } + if (isSet(1)) { + sb.append(" Non_repudiation\n"); + } + if (isSet(2)) { + sb.append(" Key_Encipherment\n"); + } + if (isSet(3)) { + sb.append(" Data_Encipherment\n"); + } + if (isSet(4)) { + sb.append(" Key_Agreement\n"); + } + if (isSet(5)) { + sb.append(" Key_CertSign\n"); + } + if (isSet(6)) { + sb.append(" Crl_Sign\n"); + } + if (isSet(7)) { + sb.append(" Encipher_Only\n"); + } + if (isSet(8)) { + sb.append(" Decipher_Only\n"); + } + sb.append("]\n"); - s += "]\n"; - - return (s); + return sb.toString(); } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/NetscapeCertTypeExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/NetscapeCertTypeExtension.java index d6d4efd34cf..735efddfc3a 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/NetscapeCertTypeExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/NetscapeCertTypeExtension.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -136,7 +136,8 @@ implements CertAttrSet { * @param position the position in the bit string to check. */ private boolean isSet(int position) { - return bitString[position]; + return (position < bitString.length) && + bitString[position]; } /** @@ -236,27 +237,34 @@ implements CertAttrSet { * Returns a printable representation of the NetscapeCertType. */ public String toString() { - String s = super.toString() + "NetscapeCertType [\n"; + StringBuilder sb = new StringBuilder(); + sb.append(super.toString()); + sb.append("NetscapeCertType [\n"); - try { - if (isSet(getPosition(SSL_CLIENT))) - s += " SSL client\n"; - if (isSet(getPosition(SSL_SERVER))) - s += " SSL server\n"; - if (isSet(getPosition(S_MIME))) - s += " S/MIME\n"; - if (isSet(getPosition(OBJECT_SIGNING))) - s += " Object Signing\n"; - if (isSet(getPosition(SSL_CA))) - s += " SSL CA\n"; - if (isSet(getPosition(S_MIME_CA))) - s += " S/MIME CA\n"; - if (isSet(getPosition(OBJECT_SIGNING_CA))) - s += " Object Signing CA" ; - } catch (Exception e) { } + if (isSet(0)) { + sb.append(" SSL client\n"); + } + if (isSet(1)) { + sb.append(" SSL server\n"); + } + if (isSet(2)) { + sb.append(" S/MIME\n"); + } + if (isSet(3)) { + sb.append(" Object Signing\n"); + } + if (isSet(5)) { + sb.append(" SSL CA\n"); + } + if (isSet(6)) { + sb.append(" S/MIME CA\n"); + } + if (isSet(7)) { + sb.append(" Object Signing CA"); + } - s += "]\n"; - return (s); + sb.append("]\n"); + return sb.toString(); } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/RDN.java b/jdk/src/java.base/share/classes/sun/security/x509/RDN.java index 940c977cc1d..4a59176c3e1 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/RDN.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/RDN.java @@ -102,7 +102,7 @@ public class RDN { int quoteCount = 0; int searchOffset = 0; int avaOffset = 0; - List avaVec = new ArrayList(3); + List avaVec = new ArrayList<>(3); int nextPlus = name.indexOf('+'); while (nextPlus >= 0) { quoteCount += X500Name.countQuotes(name, searchOffset, nextPlus); @@ -182,7 +182,7 @@ public class RDN { } int searchOffset = 0; int avaOffset = 0; - List avaVec = new ArrayList(3); + List avaVec = new ArrayList<>(3); int nextPlus = name.indexOf('+'); while (nextPlus >= 0) { /* @@ -453,7 +453,7 @@ public class RDN { } else { // order the string type AVA's alphabetically, // followed by the oid type AVA's numerically - List avaList = new ArrayList(assertion.length); + List avaList = new ArrayList<>(assertion.length); for (int i = 0; i < assertion.length; i++) { avaList.add(assertion[i]); } diff --git a/jdk/src/java.base/share/classes/sun/security/x509/ReasonFlags.java b/jdk/src/java.base/share/classes/sun/security/x509/ReasonFlags.java index 4549ad4544f..6a42046205c 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/ReasonFlags.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/ReasonFlags.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -99,7 +99,8 @@ public class ReasonFlags { * @param position the position in the bit string to check. */ private boolean isSet(int position) { - return bitString[position]; + return (position < bitString.length) && + bitString[position]; } /** @@ -199,23 +200,38 @@ public class ReasonFlags { * Returns a printable representation of the ReasonFlags. */ public String toString() { - String s = "Reason Flags [\n"; + StringBuilder sb = new StringBuilder("Reason Flags [\n"); - try { - if (isSet(0)) s += " Unused\n"; - if (isSet(1)) s += " Key Compromise\n"; - if (isSet(2)) s += " CA Compromise\n"; - if (isSet(3)) s += " Affiliation_Changed\n"; - if (isSet(4)) s += " Superseded\n"; - if (isSet(5)) s += " Cessation Of Operation\n"; - if (isSet(6)) s += " Certificate Hold\n"; - if (isSet(7)) s += " Privilege Withdrawn\n"; - if (isSet(8)) s += " AA Compromise\n"; - } catch (ArrayIndexOutOfBoundsException ex) {} + if (isSet(0)) { + sb.append(" Unused\n"); + } + if (isSet(1)) { + sb.append(" Key Compromise\n"); + } + if (isSet(2)) { + sb.append(" CA Compromise\n"); + } + if (isSet(3)) { + sb.append(" Affiliation_Changed\n"); + } + if (isSet(4)) { + sb.append(" Superseded\n"); + } + if (isSet(5)) { + sb.append(" Cessation Of Operation\n"); + } + if (isSet(6)) { + sb.append(" Certificate Hold\n"); + } + if (isSet(7)) { + sb.append(" Privilege Withdrawn\n"); + } + if (isSet(8)) { + sb.append(" AA Compromise\n"); + } + sb.append("]\n"); - s += "]\n"; - - return (s); + return sb.toString(); } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/X500Name.java b/jdk/src/java.base/share/classes/sun/security/x509/X500Name.java index 1b786063172..2b35f7a63af 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/X500Name.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/X500Name.java @@ -342,7 +342,7 @@ public class X500Name implements GeneralNameInterface, Principal { public List allAvas() { List list = allAvaList; if (list == null) { - list = new ArrayList(); + list = new ArrayList<>(); for (int i = 0; i < names.length; i++) { list.addAll(names[i].avas()); } @@ -1382,7 +1382,7 @@ public class X500Name implements GeneralNameInterface, Principal { */ static { PrivilegedExceptionAction pa = - new PrivilegedExceptionAction() { + new PrivilegedExceptionAction<>() { public Object[] run() throws Exception { Class pClass = X500Principal.class; Class[] args = new Class[] { X500Name.class }; diff --git a/jdk/src/java.base/share/classes/sun/security/x509/X509CertImpl.java b/jdk/src/java.base/share/classes/sun/security/x509/X509CertImpl.java index aa24360f46f..201e10a6cfe 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/X509CertImpl.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/X509CertImpl.java @@ -271,7 +271,7 @@ public class X509CertImpl extends X509Certificate implements DerEncoder { der = new DerValue(decstream.toByteArray()); break; } else { - decstream.write(Base64.getMimeDecoder().decode(line)); + decstream.write(Pem.decode(line)); } } } catch (IOException ioe2) { diff --git a/jdk/src/java.base/share/classes/sun/util/PreHashedMap.java b/jdk/src/java.base/share/classes/sun/util/PreHashedMap.java index d0a8ed90597..9c83984e099 100644 --- a/jdk/src/java.base/share/classes/sun/util/PreHashedMap.java +++ b/jdk/src/java.base/share/classes/sun/util/PreHashedMap.java @@ -166,14 +166,14 @@ public abstract class PreHashedMap } public Set keySet() { - return new AbstractSet () { + return new AbstractSet<> () { public int size() { return size; } public Iterator iterator() { - return new Iterator() { + return new Iterator<>() { private int i = -1; Object[] a = null; String cur = null; diff --git a/jdk/src/java.base/share/classes/sun/util/calendar/ZoneInfoFile.java b/jdk/src/java.base/share/classes/sun/util/calendar/ZoneInfoFile.java index 78d9f3ed6cb..61efb543d51 100644 --- a/jdk/src/java.base/share/classes/sun/util/calendar/ZoneInfoFile.java +++ b/jdk/src/java.base/share/classes/sun/util/calendar/ZoneInfoFile.java @@ -625,6 +625,15 @@ public final class ZoneInfoFile { params[2] = 5; params[3] = 86400000; } + // Additional check for startDayOfWeek=6 and starTime=86400000 + // is needed for Asia/Amman; Asia/Gasa and Asia/Hebron + if (params[2] == 7 && params[3] == 0 && + (zoneId.equals("Asia/Amman") || + zoneId.equals("Asia/Gaza") || + zoneId.equals("Asia/Hebron"))) { + params[2] = 6; // Friday + params[3] = 86400000; // 24h + } //endDayOfWeek and endTime workaround if (params[7] == 6 && params[8] == 0 && (zoneId.equals("Africa/Cairo"))) { diff --git a/jdk/src/java.base/share/classes/sun/util/locale/provider/AuxLocaleProviderAdapter.java b/jdk/src/java.base/share/classes/sun/util/locale/provider/AuxLocaleProviderAdapter.java index 7ddcd0e3c61..6b374b998ca 100644 --- a/jdk/src/java.base/share/classes/sun/util/locale/provider/AuxLocaleProviderAdapter.java +++ b/jdk/src/java.base/share/classes/sun/util/locale/provider/AuxLocaleProviderAdapter.java @@ -25,6 +25,8 @@ package sun.util.locale.provider; +import java.security.AccessController; +import java.security.PrivilegedAction; import java.text.spi.BreakIteratorProvider; import java.text.spi.CollatorProvider; import java.text.spi.DateFormatProvider; @@ -177,7 +179,9 @@ public abstract class AuxLocaleProviderAdapter extends LocaleProviderAdapter { * A dummy locale service provider that indicates there is no * provider available */ - private static final NullProvider NULL_PROVIDER = new NullProvider(); + private static final NullProvider NULL_PROVIDER = AccessController.doPrivileged( + (PrivilegedAction) () -> new NullProvider()); + private static class NullProvider extends LocaleServiceProvider { @Override public Locale[] getAvailableLocales() { diff --git a/jdk/src/java.base/share/classes/sun/util/locale/provider/JRELocaleProviderAdapter.java b/jdk/src/java.base/share/classes/sun/util/locale/provider/JRELocaleProviderAdapter.java index efde2013320..3d8e4f6d27c 100644 --- a/jdk/src/java.base/share/classes/sun/util/locale/provider/JRELocaleProviderAdapter.java +++ b/jdk/src/java.base/share/classes/sun/util/locale/provider/JRELocaleProviderAdapter.java @@ -26,7 +26,7 @@ package sun.util.locale.provider; import java.security.AccessController; -import java.security.PrivilegedActionException; +import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.text.spi.BreakIteratorProvider; import java.text.spi.CollatorProvider; @@ -133,8 +133,12 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R @Override public BreakIteratorProvider getBreakIteratorProvider() { if (breakIteratorProvider == null) { - BreakIteratorProvider provider = new BreakIteratorProviderImpl(getAdapterType(), - getLanguageTagSet("FormatData")); + BreakIteratorProvider provider = AccessController.doPrivileged( + (PrivilegedAction) () -> + new BreakIteratorProviderImpl( + getAdapterType(), + getLanguageTagSet("FormatData"))); + synchronized (this) { if (breakIteratorProvider == null) { breakIteratorProvider = provider; @@ -147,8 +151,12 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R @Override public CollatorProvider getCollatorProvider() { if (collatorProvider == null) { - CollatorProvider provider = new CollatorProviderImpl(getAdapterType(), - getLanguageTagSet("CollationData")); + CollatorProvider provider = AccessController.doPrivileged( + (PrivilegedAction) () -> + new CollatorProviderImpl( + getAdapterType(), + getLanguageTagSet("CollationData"))); + synchronized (this) { if (collatorProvider == null) { collatorProvider = provider; @@ -161,8 +169,12 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R @Override public DateFormatProvider getDateFormatProvider() { if (dateFormatProvider == null) { - DateFormatProvider provider = new DateFormatProviderImpl(getAdapterType(), - getLanguageTagSet("FormatData")); + DateFormatProvider provider = AccessController.doPrivileged( + (PrivilegedAction) () -> + new DateFormatProviderImpl( + getAdapterType(), + getLanguageTagSet("FormatData"))); + synchronized (this) { if (dateFormatProvider == null) { dateFormatProvider = provider; @@ -175,8 +187,12 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R @Override public DateFormatSymbolsProvider getDateFormatSymbolsProvider() { if (dateFormatSymbolsProvider == null) { - DateFormatSymbolsProvider provider = new DateFormatSymbolsProviderImpl(getAdapterType(), - getLanguageTagSet("FormatData")); + DateFormatSymbolsProvider provider = AccessController.doPrivileged( + (PrivilegedAction) () -> + new DateFormatSymbolsProviderImpl( + getAdapterType(), + getLanguageTagSet("FormatData"))); + synchronized (this) { if (dateFormatSymbolsProvider == null) { dateFormatSymbolsProvider = provider; @@ -189,7 +205,12 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R @Override public DecimalFormatSymbolsProvider getDecimalFormatSymbolsProvider() { if (decimalFormatSymbolsProvider == null) { - DecimalFormatSymbolsProvider provider = new DecimalFormatSymbolsProviderImpl(getAdapterType(), getLanguageTagSet("FormatData")); + DecimalFormatSymbolsProvider provider = AccessController.doPrivileged( + (PrivilegedAction) () -> + new DecimalFormatSymbolsProviderImpl( + getAdapterType(), + getLanguageTagSet("FormatData"))); + synchronized (this) { if (decimalFormatSymbolsProvider == null) { decimalFormatSymbolsProvider = provider; @@ -202,8 +223,12 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R @Override public NumberFormatProvider getNumberFormatProvider() { if (numberFormatProvider == null) { - NumberFormatProvider provider = new NumberFormatProviderImpl(getAdapterType(), - getLanguageTagSet("FormatData")); + NumberFormatProvider provider = AccessController.doPrivileged( + (PrivilegedAction) () -> + new NumberFormatProviderImpl( + getAdapterType(), + getLanguageTagSet("FormatData"))); + synchronized (this) { if (numberFormatProvider == null) { numberFormatProvider = provider; @@ -219,8 +244,12 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R @Override public CurrencyNameProvider getCurrencyNameProvider() { if (currencyNameProvider == null) { - CurrencyNameProvider provider = new CurrencyNameProviderImpl(getAdapterType(), - getLanguageTagSet("CurrencyNames")); + CurrencyNameProvider provider = AccessController.doPrivileged( + (PrivilegedAction) () -> + new CurrencyNameProviderImpl( + getAdapterType(), + getLanguageTagSet("CurrencyNames"))); + synchronized (this) { if (currencyNameProvider == null) { currencyNameProvider = provider; @@ -233,8 +262,12 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R @Override public LocaleNameProvider getLocaleNameProvider() { if (localeNameProvider == null) { - LocaleNameProvider provider = new LocaleNameProviderImpl(getAdapterType(), - getLanguageTagSet("LocaleNames")); + LocaleNameProvider provider = AccessController.doPrivileged( + (PrivilegedAction) () -> + new LocaleNameProviderImpl( + getAdapterType(), + getLanguageTagSet("LocaleNames"))); + synchronized (this) { if (localeNameProvider == null) { localeNameProvider = provider; @@ -247,8 +280,12 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R @Override public TimeZoneNameProvider getTimeZoneNameProvider() { if (timeZoneNameProvider == null) { - TimeZoneNameProvider provider = new TimeZoneNameProviderImpl(getAdapterType(), - getLanguageTagSet("TimeZoneNames")); + TimeZoneNameProvider provider = AccessController.doPrivileged( + (PrivilegedAction) () -> + new TimeZoneNameProviderImpl( + getAdapterType(), + getLanguageTagSet("TimeZoneNames"))); + synchronized (this) { if (timeZoneNameProvider == null) { timeZoneNameProvider = provider; @@ -261,9 +298,12 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R @Override public CalendarDataProvider getCalendarDataProvider() { if (calendarDataProvider == null) { - CalendarDataProvider provider; - provider = new CalendarDataProviderImpl(getAdapterType(), - getLanguageTagSet("CalendarData")); + CalendarDataProvider provider = AccessController.doPrivileged( + (PrivilegedAction) () -> + new CalendarDataProviderImpl( + getAdapterType(), + getLanguageTagSet("CalendarData"))); + synchronized (this) { if (calendarDataProvider == null) { calendarDataProvider = provider; @@ -276,9 +316,12 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R @Override public CalendarNameProvider getCalendarNameProvider() { if (calendarNameProvider == null) { - CalendarNameProvider provider; - provider = new CalendarNameProviderImpl(getAdapterType(), - getLanguageTagSet("FormatData")); + CalendarNameProvider provider = AccessController.doPrivileged( + (PrivilegedAction) () -> + new CalendarNameProviderImpl( + getAdapterType(), + getLanguageTagSet("FormatData"))); + synchronized (this) { if (calendarNameProvider == null) { calendarNameProvider = provider; @@ -294,8 +337,12 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R @Override public CalendarProvider getCalendarProvider() { if (calendarProvider == null) { - CalendarProvider provider = new CalendarProviderImpl(getAdapterType(), - getLanguageTagSet("CalendarData")); + CalendarProvider provider = AccessController.doPrivileged( + (PrivilegedAction) () -> + new CalendarProviderImpl( + getAdapterType(), + getLanguageTagSet("CalendarData"))); + synchronized (this) { if (calendarProvider == null) { calendarProvider = provider; @@ -319,6 +366,7 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R } // ResourceBundleBasedAdapter method implementation + @Override public LocaleData getLocaleData() { if (localeData == null) { @@ -449,4 +497,4 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R } return locales; } - } +} diff --git a/jdk/src/java.base/share/classes/sun/util/locale/provider/LocaleResources.java b/jdk/src/java.base/share/classes/sun/util/locale/provider/LocaleResources.java index d89a8856bea..5622078fbeb 100644 --- a/jdk/src/java.base/share/classes/sun/util/locale/provider/LocaleResources.java +++ b/jdk/src/java.base/share/classes/sun/util/locale/provider/LocaleResources.java @@ -47,6 +47,7 @@ import java.util.Calendar; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -250,17 +251,17 @@ public class LocaleResources { return (String) localeName; } - String[] getTimeZoneNames(String key, int size) { + String[] getTimeZoneNames(String key) { String[] names = null; - String cacheKey = TIME_ZONE_NAMES + size + '.' + key; + String cacheKey = TIME_ZONE_NAMES + '.' + key; removeEmptyReferences(); ResourceReference data = cache.get(cacheKey); - if (data == null || ((names = (String[]) data.get()) == null)) { + if (Objects.isNull(data) || Objects.isNull((names = (String[]) data.get()))) { TimeZoneNamesBundle tznb = localeData.getTimeZoneNames(locale); if (tznb.containsKey(key)) { - names = tznb.getStringArray(key, size); + names = tznb.getStringArray(key); cache.put(cacheKey, new ResourceReference(cacheKey, (Object) names, referenceQueue)); } diff --git a/jdk/src/java.base/share/classes/sun/util/locale/provider/TimeZoneNameProviderImpl.java b/jdk/src/java.base/share/classes/sun/util/locale/provider/TimeZoneNameProviderImpl.java index 105af9cb8f7..cf609658e01 100644 --- a/jdk/src/java.base/share/classes/sun/util/locale/provider/TimeZoneNameProviderImpl.java +++ b/jdk/src/java.base/share/classes/sun/util/locale/provider/TimeZoneNameProviderImpl.java @@ -26,6 +26,7 @@ package sun.util.locale.provider; import java.util.Locale; +import java.util.Objects; import java.util.Set; import java.util.TimeZone; import java.util.spi.TimeZoneNameProvider; @@ -95,8 +96,9 @@ public class TimeZoneNameProviderImpl extends TimeZoneNameProvider { */ @Override public String getDisplayName(String id, boolean daylight, int style, Locale locale) { - String[] names = getDisplayNameArray(id, 5, locale); - if (names != null) { + String[] names = getDisplayNameArray(id, locale); + if (Objects.nonNull(names)) { + assert names.length >= 7; int index = daylight ? 3 : 1; if (style == TimeZone.SHORT) { index++; @@ -108,18 +110,18 @@ public class TimeZoneNameProviderImpl extends TimeZoneNameProvider { @Override public String getGenericDisplayName(String id, int style, Locale locale) { - String[] names = getDisplayNameArray(id, 7, locale); - if (names != null && names.length >= 7) { + String[] names = getDisplayNameArray(id, locale); + if (Objects.nonNull(names)) { + assert names.length >= 7; return names[(style == TimeZone.LONG) ? 5 : 6]; } return null; } - private String[] getDisplayNameArray(String id, int n, Locale locale) { - if (id == null || locale == null) { - throw new NullPointerException(); - } - return LocaleProviderAdapter.forType(type).getLocaleResources(locale).getTimeZoneNames(id, n); + private String[] getDisplayNameArray(String id, Locale locale) { + Objects.requireNonNull(id); + Objects.requireNonNull(locale); + return LocaleProviderAdapter.forType(type).getLocaleResources(locale).getTimeZoneNames(id); } /** diff --git a/jdk/src/java.base/share/classes/sun/util/locale/provider/TimeZoneNameUtility.java b/jdk/src/java.base/share/classes/sun/util/locale/provider/TimeZoneNameUtility.java index c99978082b4..688fb2ed21b 100644 --- a/jdk/src/java.base/share/classes/sun/util/locale/provider/TimeZoneNameUtility.java +++ b/jdk/src/java.base/share/classes/sun/util/locale/provider/TimeZoneNameUtility.java @@ -30,6 +30,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.spi.TimeZoneNameProvider; @@ -100,9 +101,9 @@ public final class TimeZoneNameUtility { * Retrieve display names for a time zone ID. */ public static String[] retrieveDisplayNames(String id, Locale locale) { - if (id == null || locale == null) { - throw new NullPointerException(); - } + Objects.requireNonNull(id); + Objects.requireNonNull(locale); + return retrieveDisplayNamesImpl(id, locale); } @@ -115,9 +116,12 @@ public final class TimeZoneNameUtility { * @return the requested generic time zone display name, or null if not found. */ public static String retrieveGenericDisplayName(String id, int style, Locale locale) { - LocaleServiceProviderPool pool = - LocaleServiceProviderPool.getPool(TimeZoneNameProvider.class); - return pool.getLocalizedObject(TimeZoneNameGetter.INSTANCE, locale, "generic", style, id); + String[] names = retrieveDisplayNamesImpl(id, locale); + if (Objects.nonNull(names)) { + return names[6 - style]; + } else { + return null; + } } /** @@ -130,140 +134,53 @@ public final class TimeZoneNameUtility { * @return the requested time zone name, or null if not found. */ public static String retrieveDisplayName(String id, boolean daylight, int style, Locale locale) { - LocaleServiceProviderPool pool = - LocaleServiceProviderPool.getPool(TimeZoneNameProvider.class); - return pool.getLocalizedObject(TimeZoneNameGetter.INSTANCE, locale, daylight ? "dst" : "std", style, id); + String[] names = retrieveDisplayNamesImpl(id, locale); + if (Objects.nonNull(names)) { + return names[(daylight ? 4 : 2) - style]; + } else { + return null; + } } private static String[] retrieveDisplayNamesImpl(String id, Locale locale) { LocaleServiceProviderPool pool = LocaleServiceProviderPool.getPool(TimeZoneNameProvider.class); + String[] names; + Map perLocale = null; SoftReference> ref = cachedDisplayNames.get(id); - if (ref != null) { - Map perLocale = ref.get(); - if (perLocale != null) { - String[] names = perLocale.get(locale); - if (names != null) { + if (Objects.nonNull(ref)) { + perLocale = ref.get(); + if (Objects.nonNull(perLocale)) { + names = perLocale.get(locale); + if (Objects.nonNull(names)) { return names; } - names = pool.getLocalizedObject(TimeZoneNameArrayGetter.INSTANCE, locale, id); - if (names != null) { - perLocale.put(locale, names); - } - return names; } } - String[] names = pool.getLocalizedObject(TimeZoneNameArrayGetter.INSTANCE, locale, id); - if (names != null) { - Map perLocale = new ConcurrentHashMap<>(); - perLocale.put(locale, names); - ref = new SoftReference<>(perLocale); - cachedDisplayNames.put(id, ref); + // build names array + names = new String[7]; + names[0] = id; + for (int i = 1; i <= 6; i ++) { + names[i] = pool.getLocalizedObject(TimeZoneNameGetter.INSTANCE, locale, + i<5 ? (i<3 ? "std" : "dst") : "generic", i%2, id); } + + if (Objects.isNull(perLocale)) { + perLocale = new ConcurrentHashMap<>(); + } + perLocale.put(locale, names); + ref = new SoftReference<>(perLocale); + cachedDisplayNames.put(id, ref); return names; } + /** * Obtains a localized time zone strings from a TimeZoneNameProvider * implementation. */ - private static class TimeZoneNameArrayGetter - implements LocaleServiceProviderPool.LocalizedObjectGetter{ - private static final TimeZoneNameArrayGetter INSTANCE = - new TimeZoneNameArrayGetter(); - - @Override - public String[] getObject(TimeZoneNameProvider timeZoneNameProvider, - Locale locale, - String requestID, - Object... params) { - assert params.length == 0; - - // First, try to get names with the request ID - String[] names = buildZoneStrings(timeZoneNameProvider, locale, requestID); - - if (names == null) { - Map aliases = ZoneInfo.getAliasTable(); - - if (aliases != null) { - // Check whether this id is an alias, if so, - // look for the standard id. - String canonicalID = aliases.get(requestID); - if (canonicalID != null) { - names = buildZoneStrings(timeZoneNameProvider, locale, canonicalID); - } - if (names == null) { - // There may be a case that a standard id has become an - // alias. so, check the aliases backward. - names = examineAliases(timeZoneNameProvider, locale, - canonicalID == null ? requestID : canonicalID, aliases); - } - } - } - - if (names != null) { - names[0] = requestID; - } - - return names; - } - - private static String[] examineAliases(TimeZoneNameProvider tznp, Locale locale, - String id, - Map aliases) { - if (aliases.containsValue(id)) { - for (Map.Entry entry : aliases.entrySet()) { - if (entry.getValue().equals(id)) { - String alias = entry.getKey(); - String[] names = buildZoneStrings(tznp, locale, alias); - if (names != null) { - return names; - } - names = examineAliases(tznp, locale, alias, aliases); - if (names != null) { - return names; - } - } - } - } - - return null; - } - - private static String[] buildZoneStrings(TimeZoneNameProvider tznp, - Locale locale, String id) { - String[] names = new String[5]; - - for (int i = 1; i <= 4; i ++) { - names[i] = tznp.getDisplayName(id, i>=3, i%2, locale); - - if (names[i] == null) { - switch (i) { - case 1: - // this id seems not localized by this provider - return null; - case 2: - case 4: - // If the display name for SHORT is not supplied, - // copy the LONG name. - names[i] = names[i-1]; - break; - case 3: - // If the display name for DST is not supplied, - // copy the "standard" name. - names[3] = names[1]; - break; - } - } - } - - return names; - } - } - private static class TimeZoneNameGetter implements LocaleServiceProviderPool.LocalizedObjectGetter { @@ -299,18 +216,16 @@ public final class TimeZoneNameUtility { private static String examineAliases(TimeZoneNameProvider tznp, Locale locale, String requestID, String tzid, int style, Map aliases) { - if (aliases.containsValue(tzid)) { - for (Map.Entry entry : aliases.entrySet()) { - if (entry.getValue().equals(tzid)) { - String alias = entry.getKey(); - String name = getName(tznp, locale, requestID, style, alias); - if (name != null) { - return name; - } - name = examineAliases(tznp, locale, requestID, alias, style, aliases); - if (name != null) { - return name; - } + for (Map.Entry entry : aliases.entrySet()) { + if (entry.getValue().equals(tzid)) { + String alias = entry.getKey(); + String name = getName(tznp, locale, requestID, style, alias); + if (name != null) { + return name; + } + name = examineAliases(tznp, locale, requestID, alias, style, aliases); + if (name != null) { + return name; } } } diff --git a/jdk/src/java.base/share/classes/sun/util/logging/PlatformLogger.java b/jdk/src/java.base/share/classes/sun/util/logging/PlatformLogger.java index 03c48a4ffec..b81269d3fa8 100644 --- a/jdk/src/java.base/share/classes/sun/util/logging/PlatformLogger.java +++ b/jdk/src/java.base/share/classes/sun/util/logging/PlatformLogger.java @@ -161,7 +161,7 @@ public class PlatformLogger { private static boolean loggingEnabled; static { loggingEnabled = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { public Boolean run() { String cname = System.getProperty("java.util.logging.config.class"); String fname = System.getProperty("java.util.logging.config.file"); diff --git a/jdk/src/java.base/share/classes/sun/util/resources/LocaleData.java b/jdk/src/java.base/share/classes/sun/util/resources/LocaleData.java index 75ee2f018ba..60ddfefe134 100644 --- a/jdk/src/java.base/share/classes/sun/util/resources/LocaleData.java +++ b/jdk/src/java.base/share/classes/sun/util/resources/LocaleData.java @@ -159,7 +159,7 @@ public class LocaleData { } public static ResourceBundle getBundle(final String baseName, final Locale locale) { - return AccessController.doPrivileged(new PrivilegedAction() { + return AccessController.doPrivileged(new PrivilegedAction<>() { @Override public ResourceBundle run() { return ResourceBundle @@ -169,7 +169,7 @@ public class LocaleData { } private static OpenListResourceBundle getSupplementary(final String baseName, final Locale locale) { - return AccessController.doPrivileged(new PrivilegedAction() { + return AccessController.doPrivileged(new PrivilegedAction<>() { @Override public OpenListResourceBundle run() { OpenListResourceBundle rb = null; diff --git a/jdk/src/java.base/share/classes/sun/util/resources/ParallelListResourceBundle.java b/jdk/src/java.base/share/classes/sun/util/resources/ParallelListResourceBundle.java index 862143c9745..35319575010 100644 --- a/jdk/src/java.base/share/classes/sun/util/resources/ParallelListResourceBundle.java +++ b/jdk/src/java.base/share/classes/sun/util/resources/ParallelListResourceBundle.java @@ -213,7 +213,7 @@ public abstract class ParallelListResourceBundle extends ResourceBundle { if (parent == null) { return set.iterator(); } - return new Iterator() { + return new Iterator<>() { private Iterator itr = set.iterator(); private boolean usingParent; diff --git a/jdk/src/java.base/share/classes/sun/util/resources/TimeZoneNamesBundle.java b/jdk/src/java.base/share/classes/sun/util/resources/TimeZoneNamesBundle.java index ab2d10a676e..3385887596e 100644 --- a/jdk/src/java.base/share/classes/sun/util/resources/TimeZoneNamesBundle.java +++ b/jdk/src/java.base/share/classes/sun/util/resources/TimeZoneNamesBundle.java @@ -44,6 +44,7 @@ import java.util.Map; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.MissingResourceException; +import java.util.Objects; import java.util.Set; /** @@ -60,26 +61,6 @@ import java.util.Set; */ public abstract class TimeZoneNamesBundle extends OpenListResourceBundle { - /** - * Returns a String array containing time zone names. The String array has - * at most size elements. - * - * @param key the time zone ID for which names are obtained - * @param size the requested size of array for names - * @return a String array containing names - */ - public String[] getStringArray(String key, int size) { - String[] names = handleGetObject(key, size); - if ((names == null || names.length != size) && parent != null) { - names = ((TimeZoneNamesBundle)parent).getStringArray(key, size); - } - if (names == null) { - throw new MissingResourceException("no time zone names", getClass().getName(), key); - } - return names; - - } - /** * Maps time zone IDs to locale-specific names. * The value returned is an array of five strings: @@ -89,6 +70,8 @@ public abstract class TimeZoneNamesBundle extends OpenListResourceBundle { *
                              • The short name of the time zone in standard time (localized). *
                              • The long name of the time zone in daylight savings time (localized). *
                              • The short name of the time zone in daylight savings time (localized). + *
                              • The long name of the time zone in generic form (localized). + *
                              • The short name of the time zone in generic form (localized). * * The localized names come from the subclasses's * getContents implementations, while the time zone @@ -96,16 +79,12 @@ public abstract class TimeZoneNamesBundle extends OpenListResourceBundle { */ @Override public Object handleGetObject(String key) { - return handleGetObject(key, 5); - } - - private String[] handleGetObject(String key, int n) { String[] contents = (String[]) super.handleGetObject(key); - if (contents == null) { + if (Objects.isNull(contents)) { return null; } - int clen = Math.min(n - 1, contents.length); - String[] tmpobj = new String[clen+1]; + int clen = contents.length; + String[] tmpobj = new String[7]; tmpobj[0] = key; System.arraycopy(contents, 0, tmpobj, 1, clen); return tmpobj; diff --git a/jdk/src/java.base/share/classes/sun/util/resources/en/TimeZoneNames_en_IE.java b/jdk/src/java.base/share/classes/sun/util/resources/en/TimeZoneNames_en_IE.java index ce91613f6ba..14a74e860ad 100644 --- a/jdk/src/java.base/share/classes/sun/util/resources/en/TimeZoneNames_en_IE.java +++ b/jdk/src/java.base/share/classes/sun/util/resources/en/TimeZoneNames_en_IE.java @@ -47,7 +47,8 @@ public final class TimeZoneNames_en_IE extends TimeZoneNamesBundle { protected final Object[][] getContents() { return new Object[][] { {"Europe/London", new String[] {"Greenwich Mean Time", "GMT", - "Irish Summer Time", "IST" /*Dublin*/}}, + "Irish Summer Time", "IST", /*Dublin*/ + "Irish Time", "IT" /*Dublin*/}}, }; } } diff --git a/jdk/src/java.base/share/conf/security/java.security b/jdk/src/java.base/share/conf/security/java.security index 1d05aae8eba..b863516a481 100644 --- a/jdk/src/java.base/share/conf/security/java.security +++ b/jdk/src/java.base/share/conf/security/java.security @@ -533,4 +533,4 @@ jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024 # # Example: # jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048 -jdk.tls.disabledAlgorithms=SSLv3 +jdk.tls.disabledAlgorithms=SSLv3, RC4 diff --git a/jdk/src/java.base/share/native/libjli/java.c b/jdk/src/java.base/share/native/libjli/java.c index 846e6835855..fa4c1c9ca99 100644 --- a/jdk/src/java.base/share/native/libjli/java.c +++ b/jdk/src/java.base/share/native/libjli/java.c @@ -730,7 +730,7 @@ SetJvmEnvironment(int argc, char **argv) { static int parse_size(const char *s, jlong *result) { jlong n = 0; - int args_read = sscanf(s, jlong_format_specifier(), &n); + int args_read = sscanf(s, JLONG_FORMAT_SPECIFIER, &n); if (args_read != 1) { return 0; } @@ -798,7 +798,7 @@ AddOption(char *str, void *info) * overflow before the JVM startup code can check to make sure the stack * is big enough. */ - if (threadStackSize < STACK_SIZE_MINIMUM) { + if (threadStackSize < (jlong)STACK_SIZE_MINIMUM) { threadStackSize = STACK_SIZE_MINIMUM; } } diff --git a/jdk/src/java.base/share/native/libjli/java.h b/jdk/src/java.base/share/native/libjli/java.h index 5cc7608b566..1bff9a4906f 100644 --- a/jdk/src/java.base/share/native/libjli/java.h +++ b/jdk/src/java.base/share/native/libjli/java.h @@ -144,8 +144,6 @@ void JLI_ReportMessage(const char * message, ...); void JLI_ReportExceptionDescription(JNIEnv * env); void PrintMachineDependentOptions(); -const char *jlong_format_specifier(); - /* * Block current thread and continue execution in new thread */ diff --git a/jdk/src/java.base/share/native/libjli/manifest_info.h b/jdk/src/java.base/share/native/libjli/manifest_info.h index 5f9773e0bca..1e04058f87e 100644 --- a/jdk/src/java.base/share/native/libjli/manifest_info.h +++ b/jdk/src/java.base/share/native/libjli/manifest_info.h @@ -109,6 +109,8 @@ /* * Macros for getting end of central directory header (END) fields */ +#define ENDNMD(b) SH(b, 4) /* number of this disk */ +#define ENDDSK(b) SH(b, 6) /* disk number of start */ #define ENDSUB(b) SH(b, 8) /* number of entries on this disk */ #define ENDTOT(b) SH(b, 10) /* total number of entries */ #define ENDSIZ(b) LG(b, 12) /* central directory size */ diff --git a/jdk/src/java.base/share/native/libjli/parse_manifest.c b/jdk/src/java.base/share/native/libjli/parse_manifest.c index 9ce82c1a1d6..54f2adf5cdb 100644 --- a/jdk/src/java.base/share/native/libjli/parse_manifest.c +++ b/jdk/src/java.base/share/native/libjli/parse_manifest.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -111,52 +111,127 @@ inflate_file(int fd, zentry *entry, int *size_out) return (NULL); } -static jboolean zip64_present = JNI_FALSE; +/* + * Implementation notes: + * + * This is a zip format reader for seekable files, that tolerates + * leading and trailing garbage, and tolerates having had internal + * offsets adjusted for leading garbage (as with Info-Zip's zip -A). + * + * We find the end header by scanning backwards from the end of the + * file for the end signature. This may fail in the presence of + * trailing garbage or a ZIP file comment that contains binary data. + * Similarly, the ZIP64 end header may need to be located by scanning + * backwards from the end header. It may be misidentified, but this + * is very unlikely to happen in practice without adversarial input. + * + * The zip file format is documented at: + * https://www.pkware.com/documents/casestudies/APPNOTE.TXT + * + * TODO: more informative error messages + */ + +/** Reads count bytes from fd at position pos into given buffer. */ +static jboolean +readAt(int fd, jlong pos, unsigned int count, void *buf) { + return (pos >= 0 + && JLI_Lseek(fd, pos, SEEK_SET) == pos + && read(fd, buf, count) == (jlong) count); +} + /* - * Checks to see if we have ZIP64 archive, and save - * the check for later use + * Tells whether given header values (obtained from either ZIP64 or + * non-ZIP64 header) appear to be correct, by checking the first LOC + * and CEN headers. + */ +static jboolean +is_valid_end_header(int fd, jlong endpos, + jlong censiz, jlong cenoff, jlong entries) { + Byte cenhdr[CENHDR]; + Byte lochdr[LOCHDR]; + // Expected offset of the first central directory header + jlong censtart = endpos - censiz; + // Expected position within the file that offsets are relative to + jlong base_offset = endpos - (censiz + cenoff); + return censtart >= 0 && cenoff >= 0 && + (censiz == 0 || + // Validate first CEN and LOC header signatures. + // Central directory must come directly before the end header. + (readAt(fd, censtart, CENHDR, cenhdr) + && CENSIG_AT(cenhdr) + && readAt(fd, base_offset + CENOFF(cenhdr), LOCHDR, lochdr) + && LOCSIG_AT(lochdr) + && CENNAM(cenhdr) == LOCNAM(lochdr))); +} + +/* + * Tells whether p appears to be pointing at a valid ZIP64 end header. + * Values censiz, cenoff, and entries are the corresponding values + * from the non-ZIP64 end header. We perform extra checks to avoid + * misidentifying data from the last entry as a ZIP64 end header. + */ +static jboolean +is_zip64_endhdr(int fd, const Byte *p, jlong end64pos, + jlong censiz, jlong cenoff, jlong entries) { + if (ZIP64_ENDSIG_AT(p)) { + jlong censiz64 = ZIP64_ENDSIZ(p); + jlong cenoff64 = ZIP64_ENDOFF(p); + jlong entries64 = ZIP64_ENDTOT(p); + return (censiz64 == censiz || censiz == ZIP64_MAGICVAL) + && (cenoff64 == cenoff || cenoff == ZIP64_MAGICVAL) + && (entries64 == entries || entries == ZIP64_MAGICCOUNT) + && is_valid_end_header(fd, end64pos, censiz64, cenoff64, entries64); + } + return JNI_FALSE; +} + +/* + * Given a non-ZIP64 end header located at endhdr and endpos, look for + * an adjacent ZIP64 end header, finding the base offset and censtart + * from the ZIP64 header if available, else from the non-ZIP64 header. + * @return 0 if successful, -1 in case of failure */ static int -haveZIP64(Byte *p) { - jlong cenlen, cenoff, centot; - cenlen = ENDSIZ(p); - cenoff = ENDOFF(p); - centot = ENDTOT(p); - zip64_present = (cenlen == ZIP64_MAGICVAL || - cenoff == ZIP64_MAGICVAL || - centot == ZIP64_MAGICCOUNT); - return zip64_present; -} - -static jlong -find_end64(int fd, Byte *ep, jlong pos) +find_positions64(int fd, const Byte * const endhdr, const jlong endpos, + jlong* base_offset, jlong* censtart) { + jlong censiz = ENDSIZ(endhdr); + jlong cenoff = ENDOFF(endhdr); + jlong entries = ENDTOT(endhdr); jlong end64pos; - jlong bytes; - if ((end64pos = JLI_Lseek(fd, pos - ZIP64_LOCHDR, SEEK_SET)) < (jlong)0) - return -1; - if ((bytes = read(fd, ep, ZIP64_LOCHDR)) < 0) - return -1; - if (ZIP64_LOCSIG_AT(ep)) - return end64pos; - return -1; + Byte buf[ZIP64_ENDHDR + ZIP64_LOCHDR]; + if (censiz + cenoff != endpos + && (end64pos = endpos - sizeof(buf)) >= (jlong)0 + && readAt(fd, end64pos, sizeof(buf), buf) + && ZIP64_LOCSIG_AT(buf + ZIP64_ENDHDR) + && (jlong) ZIP64_LOCDSK(buf + ZIP64_ENDHDR) == ENDDSK(endhdr) + && (is_zip64_endhdr(fd, buf, end64pos, censiz, cenoff, entries) + || // A variable sized "zip64 extensible data sector" ? + ((end64pos = ZIP64_LOCOFF(buf + ZIP64_ENDHDR)) >= (jlong)0 + && readAt(fd, end64pos, ZIP64_ENDHDR, buf) + && is_zip64_endhdr(fd, buf, end64pos, censiz, cenoff, entries))) + ) { + *censtart = end64pos - ZIP64_ENDSIZ(buf); + *base_offset = *censtart - ZIP64_ENDOFF(buf); + } else { + if (!is_valid_end_header(fd, endpos, censiz, cenoff, entries)) + return -1; + *censtart = endpos - censiz; + *base_offset = *censtart - cenoff; + } + return 0; } /* - * A very little used routine to handle the case that zip file has - * a comment at the end. Believe it or not, the only way to find the - * END record is to walk backwards, byte by bloody byte looking for - * the END record signature. + * Finds the base offset and censtart of the zip file. * - * fd: File descriptor of the jar file. - * eb: Pointer to a buffer to receive a copy of the END header. - * - * Returns the offset of the END record in the file on success, - * -1 on failure. + * @param fd file descriptor of the jar file + * @param eb scratch buffer + * @return 0 if successful, -1 in case of failure */ -static jlong -find_end(int fd, Byte *eb) +static int +find_positions(int fd, Byte *eb, jlong* base_offset, jlong* censtart) { jlong len; jlong pos; @@ -174,10 +249,10 @@ find_end(int fd, Byte *eb) */ if ((pos = JLI_Lseek(fd, -ENDHDR, SEEK_END)) < (jlong)0) return (-1); - if ((bytes = read(fd, eb, ENDHDR)) < 0) + if (read(fd, eb, ENDHDR) < 0) return (-1); if (ENDSIG_AT(eb)) { - return haveZIP64(eb) ? find_end64(fd, eb, pos) : pos; + return find_positions64(fd, eb, pos, base_offset, censtart); } /* @@ -193,7 +268,13 @@ find_end(int fd, Byte *eb) return (-1); if ((buffer = malloc(END_MAXLEN)) == NULL) return (-1); - if ((bytes = read(fd, buffer, len)) < 0) { + + /* + * read() on windows takes an unsigned int for count. Casting len + * to an unsigned int here is safe since it is guaranteed to be + * less than END_MAXLEN. + */ + if ((bytes = read(fd, buffer, (unsigned int)len)) < 0) { free(buffer); return (-1); } @@ -208,7 +289,7 @@ find_end(int fd, Byte *eb) (void) memcpy(eb, cp, ENDHDR); free(buffer); pos = flen - (endpos - cp); - return haveZIP64(eb) ? find_end64(fd, eb, pos) : pos; + return find_positions64(fd, eb, pos, base_offset, censtart); } free(buffer); return (-1); @@ -217,82 +298,6 @@ find_end(int fd, Byte *eb) #define BUFSIZE (3 * 65536 + CENHDR + SIGSIZ) #define MINREAD 1024 -/* - * Computes and positions at the start of the CEN header, ie. the central - * directory, this will also return the offset if there is a zip file comment - * at the end of the archive, for most cases this would be 0. - */ -static jlong -compute_cen(int fd, Byte *bp) -{ - int bytes; - Byte *p; - jlong base_offset; - jlong offset; - char buffer[MINREAD]; - p = (Byte*) buffer; - /* - * Read the END Header, which is the starting point for ZIP files. - * (Clearly designed to make writing a zip file easier than reading - * one. Now isn't that precious...) - */ - if ((base_offset = find_end(fd, bp)) == -1) { - return (-1); - } - p = bp; - /* - * There is a historical, but undocumented, ability to allow for - * additional "stuff" to be prepended to the zip/jar file. It seems - * that this has been used to prepend an actual java launcher - * executable to the jar on Windows. Although this is just another - * form of statically linking a small piece of the JVM to the - * application, we choose to continue to support it. Note that no - * guarantees have been made (or should be made) to the customer that - * this will continue to work. - * - * Therefore, calculate the base offset of the zip file (within the - * expanded file) by assuming that the central directory is followed - * immediately by the end record. - */ - if (zip64_present) { - if ((offset = ZIP64_LOCOFF(p)) < (jlong)0) { - return -1; - } - if (JLI_Lseek(fd, offset, SEEK_SET) < (jlong) 0) { - return (-1); - } - if ((bytes = read(fd, buffer, MINREAD)) < 0) { - return (-1); - } - if (!ZIP64_ENDSIG_AT(buffer)) { - return -1; - } - if ((offset = ZIP64_ENDOFF(buffer)) < (jlong)0) { - return -1; - } - if (JLI_Lseek(fd, offset, SEEK_SET) < (jlong)0) { - return (-1); - } - p = (Byte*) buffer; - base_offset = base_offset - ZIP64_ENDSIZ(p) - ZIP64_ENDOFF(p) - ZIP64_ENDHDR; - } else { - base_offset = base_offset - ENDSIZ(p) - ENDOFF(p); - /* - * The END Header indicates the start of the Central Directory - * Headers. Remember that the desired Central Directory Header (CEN) - * will almost always be the second one and the first one is a small - * directory entry ("META-INF/"). Keep the code optimized for - * that case. - * - * Seek to the beginning of the Central Directory. - */ - if (JLI_Lseek(fd, base_offset + ENDOFF(p), SEEK_SET) < (jlong) 0) { - return (-1); - } - } - return base_offset; -} - /* * Locate the manifest file with the zip/jar file. * @@ -327,7 +332,23 @@ find_file(int fd, zentry *entry, const char *file_name) int res; int entry_size; int read_size; + + /* + * The (imaginary) position within the file relative to which + * offsets within the zip file refer. This is usually the + * location of the first local header (the start of the zip data) + * (which in turn is usually 0), but if the zip file has content + * prepended, then it will be either 0 or the length of the + * prepended content, depending on whether or not internal offsets + * have been adjusted (via e.g. zip -A). May be negative if + * content is prepended, zip -A is run, then the prefix is + * detached! + */ jlong base_offset; + + /** The position within the file of the start of the central directory. */ + jlong censtart; + Byte *p; Byte *bp; Byte *buffer; @@ -338,9 +359,11 @@ find_file(int fd, zentry *entry, const char *file_name) } bp = buffer; - base_offset = compute_cen(fd, bp); - if (base_offset == -1) { - free(buffer); + + if (find_positions(fd, bp, &base_offset, &censtart) == -1) { + return -1; + } + if (JLI_Lseek(fd, censtart, SEEK_SET) < (jlong) 0) { return -1; } @@ -574,7 +597,7 @@ JLI_ParseManifest(char *jarfile, manifest_info *info) info->jre_version = NULL; info->jre_restrict_search = 0; info->splashscreen_image_file_name = NULL; - if (rc = find_file(fd, &entry, manifest_name) != 0) { + if ((rc = find_file(fd, &entry, manifest_name)) != 0) { close(fd); return (-2); } @@ -675,7 +698,7 @@ JLI_ManifestIterate(const char *jarfile, attribute_closure ac, void *user_data) return (-1); } - if (rc = find_file(fd, &entry, manifest_name) != 0) { + if ((rc = find_file(fd, &entry, manifest_name)) != 0) { close(fd); return (-2); } diff --git a/jdk/src/java.base/share/native/libjli/splashscreen_stubs.c b/jdk/src/java.base/share/native/libjli/splashscreen_stubs.c index 9c1f5148c45..f741ccf807a 100644 --- a/jdk/src/java.base/share/native/libjli/splashscreen_stubs.c +++ b/jdk/src/java.base/share/native/libjli/splashscreen_stubs.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -61,11 +61,11 @@ typedef char* (*SplashGetScaledImageName_t)(const char* fileName, #define INVOKEV(name) _INVOKE(name, ,;) int DoSplashLoadMemory(void* pdata, int size) { - INVOKE(SplashLoadMemory, NULL)(pdata, size); + INVOKE(SplashLoadMemory, 0)(pdata, size); } int DoSplashLoadFile(const char* filename) { - INVOKE(SplashLoadFile, NULL)(filename); + INVOKE(SplashLoadFile, 0)(filename); } void DoSplashInit(void) { @@ -87,4 +87,4 @@ void DoSplashSetScaleFactor(float scaleFactor) { char* DoSplashGetScaledImageName(const char* fileName, const char* jarName, float* scaleFactor) { INVOKE(SplashGetScaledImageName, NULL)(fileName, jarName, scaleFactor); -} \ No newline at end of file +} diff --git a/jdk/src/java.base/share/native/libjli/wildcard.c b/jdk/src/java.base/share/native/libjli/wildcard.c index 96dac738aa0..d8c9df02109 100644 --- a/jdk/src/java.base/share/native/libjli/wildcard.c +++ b/jdk/src/java.base/share/native/libjli/wildcard.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -274,7 +274,7 @@ FileList_add(FileList fl, char *file) } static void -FileList_addSubstring(FileList fl, const char *beg, int len) +FileList_addSubstring(FileList fl, const char *beg, size_t len) { char *filename = (char *) JLI_MemAlloc(len+1); memcpy(filename, beg, len); @@ -310,7 +310,7 @@ static FileList FileList_split(const char *path, char sep) { const char *p, *q; - int len = (int)JLI_StrLen(path); + size_t len = JLI_StrLen(path); int count; FileList fl; for (count = 1, p = path; p < path + len; p++) diff --git a/jdk/src/java.base/unix/classes/java/lang/ProcessEnvironment.java b/jdk/src/java.base/unix/classes/java/lang/ProcessEnvironment.java index 08d260cf4a3..08e0ce4e053 100644 --- a/jdk/src/java.base/unix/classes/java/lang/ProcessEnvironment.java +++ b/jdk/src/java.base/unix/classes/java/lang/ProcessEnvironment.java @@ -99,7 +99,7 @@ final class ProcessEnvironment /* Only for use by Runtime.exec(...String[]envp...) */ static Map emptyEnvironment(int capacity) { - return new StringEnvironment(new HashMap(capacity)); + return new StringEnvironment(new HashMap<>(capacity)); } private static native byte[][] environ(); diff --git a/jdk/src/java.base/unix/classes/java/lang/ProcessImpl.java b/jdk/src/java.base/unix/classes/java/lang/ProcessImpl.java index a35405fc8d9..7fa7dfed338 100644 --- a/jdk/src/java.base/unix/classes/java/lang/ProcessImpl.java +++ b/jdk/src/java.base/unix/classes/java/lang/ProcessImpl.java @@ -285,8 +285,6 @@ final class ProcessImpl extends Process { * 1 - fork(2) and exec(2) * 2 - posix_spawn(3P) * 3 - vfork(2) and exec(2) - * - * (4 - clone(2) and exec(2) - obsolete and currently disabled in native code) * * @param fds an array of three file descriptors. * Indexes 0, 1, and 2 correspond to standard input, @@ -496,12 +494,11 @@ final class ProcessImpl extends Process { public synchronized boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException { + long remainingNanos = unit.toNanos(timeout); // throw NPE before other conditions if (hasExited) return true; if (timeout <= 0) return false; - long remainingNanos = unit.toNanos(timeout); long deadline = System.nanoTime() + remainingNanos; - do { // Round up to next millisecond wait(TimeUnit.NANOSECONDS.toMillis(remainingNanos + 999_999L)); diff --git a/jdk/src/java.base/unix/classes/sun/net/PortConfig.java b/jdk/src/java.base/unix/classes/sun/net/PortConfig.java index 1825b0b59a0..eb2e4d57865 100644 --- a/jdk/src/java.base/unix/classes/sun/net/PortConfig.java +++ b/jdk/src/java.base/unix/classes/sun/net/PortConfig.java @@ -42,7 +42,7 @@ public final class PortConfig { static { AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public Void run() { System.loadLibrary("net"); String os = System.getProperty("os.name"); diff --git a/jdk/src/java.base/unix/classes/sun/net/dns/ResolverConfigurationImpl.java b/jdk/src/java.base/unix/classes/sun/net/dns/ResolverConfigurationImpl.java index 5af3d445e09..46fd008681e 100644 --- a/jdk/src/java.base/unix/classes/sun/net/dns/ResolverConfigurationImpl.java +++ b/jdk/src/java.base/unix/classes/sun/net/dns/ResolverConfigurationImpl.java @@ -85,6 +85,15 @@ public class ResolverConfigurationImpl if (val.charAt(0) == '#' || val.charAt(0) == ';') { break; } + if ("nameserver".equals(keyword)) { + if (val.indexOf(':') >= 0 && + val.indexOf('.') < 0 && // skip for IPv4 literals with port + val.indexOf('[') < 0 && + val.indexOf(']') < 0 ) { + // IPv6 literal, in non-BSD-style. + val = "[" + val + "]"; + } + } ll.add(val); if (--maxvalues == 0) { break; @@ -122,7 +131,7 @@ public class ResolverConfigurationImpl // get the name servers from /etc/resolv.conf nameservers = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction>() { + new java.security.PrivilegedAction<>() { public LinkedList run() { // typically MAXNS is 3 but we've picked 5 here // to allow for additional servers if required. @@ -147,7 +156,7 @@ public class ResolverConfigurationImpl // first try the search keyword in /etc/resolv.conf sl = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction>() { + new java.security.PrivilegedAction<>() { public LinkedList run() { LinkedList ll; @@ -173,7 +182,7 @@ public class ResolverConfigurationImpl String localDomain = localDomain0(); if (localDomain != null && localDomain.length() > 0) { - sl = new LinkedList(); + sl = new LinkedList<>(); sl.add(localDomain); return sl; } @@ -181,7 +190,7 @@ public class ResolverConfigurationImpl // try domain keyword in /etc/resolv.conf sl = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction>() { + new java.security.PrivilegedAction<>() { public LinkedList run() { LinkedList ll; @@ -251,7 +260,7 @@ public class ResolverConfigurationImpl static { java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public Void run() { System.loadLibrary("net"); return null; diff --git a/jdk/src/java.base/unix/classes/sun/net/sdp/SdpProvider.java b/jdk/src/java.base/unix/classes/sun/net/sdp/SdpProvider.java index ec974744419..2b1c3fd841e 100644 --- a/jdk/src/java.base/unix/classes/sun/net/sdp/SdpProvider.java +++ b/jdk/src/java.base/unix/classes/sun/net/sdp/SdpProvider.java @@ -198,7 +198,7 @@ public class SdpProvider extends NetHooks.Provider { { Scanner scanner = new Scanner(new File(file)); try { - List result = new ArrayList(); + List result = new ArrayList<>(); while (scanner.hasNextLine()) { String line = scanner.nextLine().trim(); diff --git a/jdk/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java b/jdk/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java index 6211811e512..0c4523c19f1 100644 --- a/jdk/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java +++ b/jdk/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java @@ -95,7 +95,7 @@ public class NTLMAuthentication extends AuthenticationInfo { private void init0() { hostname = java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { + new java.security.PrivilegedAction<>() { public String run() { String localhost; try { diff --git a/jdk/src/java.base/unix/classes/sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java b/jdk/src/java.base/unix/classes/sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java index 8c7cfd2291d..8dec1a3553d 100644 --- a/jdk/src/java.base/unix/classes/sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java +++ b/jdk/src/java.base/unix/classes/sun/nio/ch/UnixAsynchronousServerSocketChannelImpl.java @@ -216,7 +216,7 @@ class UnixAsynchronousServerSocketChannelImpl // permission check must always be in initiator's context try { if (acc != null) { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public Void run() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { @@ -287,7 +287,7 @@ class UnixAsynchronousServerSocketChannelImpl synchronized (updateLock) { if (handler == null) { this.acceptHandler = null; - result = new PendingFuture(this); + result = new PendingFuture<>(this); this.acceptFuture = result; } else { this.acceptHandler = handler; diff --git a/jdk/src/java.base/unix/classes/sun/nio/fs/GnomeFileTypeDetector.java b/jdk/src/java.base/unix/classes/sun/nio/fs/GnomeFileTypeDetector.java index f455afe2381..e579f176e2b 100644 --- a/jdk/src/java.base/unix/classes/sun/nio/fs/GnomeFileTypeDetector.java +++ b/jdk/src/java.base/unix/classes/sun/nio/fs/GnomeFileTypeDetector.java @@ -93,7 +93,7 @@ public class GnomeFileTypeDetector private static native byte[] probeUsingGnomeVfs(long pathAddress); static { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public Void run() { System.loadLibrary("nio"); return null; diff --git a/jdk/src/java.base/unix/classes/sun/nio/fs/MimeTypesFileTypeDetector.java b/jdk/src/java.base/unix/classes/sun/nio/fs/MimeTypesFileTypeDetector.java index 8878703a343..b742b3f626f 100644 --- a/jdk/src/java.base/unix/classes/sun/nio/fs/MimeTypesFileTypeDetector.java +++ b/jdk/src/java.base/unix/classes/sun/nio/fs/MimeTypesFileTypeDetector.java @@ -106,7 +106,7 @@ class MimeTypesFileTypeDetector extends AbstractFileTypeDetector { synchronized (this) { if (!loaded) { List lines = AccessController.doPrivileged( - new PrivilegedAction>() { + new PrivilegedAction<>() { @Override public List run() { try { diff --git a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixCopyFile.java b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixCopyFile.java index 399259c18c4..7a31ab186a6 100644 --- a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixCopyFile.java +++ b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixCopyFile.java @@ -606,7 +606,7 @@ class UnixCopyFile { throws UnixException; static { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { @Override public Void run() { System.loadLibrary("nio"); diff --git a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixFileStore.java b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixFileStore.java index 98fc9abe054..e9c8fe110b0 100644 --- a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixFileStore.java +++ b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixFileStore.java @@ -222,7 +222,7 @@ abstract class UnixFileStore synchronized (loadLock) { if (props == null) { props = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { @Override public Properties run() { return loadProperties(); diff --git a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixFileSystem.java b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixFileSystem.java index 3cdcd595f7f..d394ac10173 100644 --- a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixFileSystem.java +++ b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixFileSystem.java @@ -152,7 +152,7 @@ abstract class UnixFileSystem public final Iterable getRootDirectories() { final List allowedList = Collections.unmodifiableList(Arrays.asList((Path)rootDirectory)); - return new Iterable() { + return new Iterable<>() { public Iterator iterator() { try { SecurityManager sm = System.getSecurityManager(); @@ -254,7 +254,7 @@ abstract class UnixFileSystem return Collections.emptyList(); } } - return new Iterable() { + return new Iterable<>() { public Iterator iterator() { return new FileStoreIterator(); } diff --git a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixNativeDispatcher.java b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixNativeDispatcher.java index 7a676d1863f..b84fa5c3861 100644 --- a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixNativeDispatcher.java +++ b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixNativeDispatcher.java @@ -568,7 +568,7 @@ class UnixNativeDispatcher { private static native int init(); static { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<>() { public Void run() { System.loadLibrary("nio"); return null; diff --git a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixPath.java b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixPath.java index b74a393e9b2..b219764d3e7 100644 --- a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixPath.java +++ b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixPath.java @@ -121,7 +121,7 @@ class UnixPath implements Path { ce = Util.jnuEncoding().newEncoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT); - encoder.set(new SoftReference(ce)); + encoder.set(new SoftReference<>(ce)); } char[] ca = fs.normalizeNativePath(input.toCharArray()); diff --git a/jdk/src/java.base/unix/classes/sun/security/provider/NativePRNG.java b/jdk/src/java.base/unix/classes/sun/security/provider/NativePRNG.java index ef728aa78eb..200ca9a56b6 100644 --- a/jdk/src/java.base/unix/classes/sun/security/provider/NativePRNG.java +++ b/jdk/src/java.base/unix/classes/sun/security/provider/NativePRNG.java @@ -125,7 +125,7 @@ public final class NativePRNG extends SecureRandomSpi { */ private static RandomIO initIO(final Variant v) { return AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { @Override public RandomIO run() { @@ -440,7 +440,7 @@ public final class NativePRNG extends SecureRandomSpi { if (seedOutInitialized == false) { seedOutInitialized = true; seedOut = AccessController.doPrivileged( - new PrivilegedAction() { + new PrivilegedAction<>() { @Override public OutputStream run() { try { diff --git a/jdk/src/java.base/unix/native/libjava/ProcessImpl_md.c b/jdk/src/java.base/unix/native/libjava/ProcessImpl_md.c index 3a962aba0a4..b2992b5c557 100644 --- a/jdk/src/java.base/unix/native/libjava/ProcessImpl_md.c +++ b/jdk/src/java.base/unix/native/libjava/ProcessImpl_md.c @@ -97,8 +97,7 @@ * address space temporarily, before launching the target command. * * Based on the above analysis, we are currently using vfork() on - * Linux and spawn() on other Unix systems, but the code to use clone() - * and fork() remains. + * Linux and posix_spawn() on other Unix systems. */ @@ -385,39 +384,13 @@ static int copystrings(char *buf, int offset, const char * const *arg) { } /** - * We are unusually paranoid; use of clone/vfork is + * We are unusually paranoid; use of vfork is * especially likely to tickle gcc/glibc bugs. */ #ifdef __attribute_noinline__ /* See: sys/cdefs.h */ __attribute_noinline__ #endif -#define START_CHILD_USE_CLONE 0 /* clone() currently disabled; see above. */ - -#ifdef START_CHILD_USE_CLONE -static pid_t -cloneChild(ChildStuff *c) { -#ifdef __linux__ -#define START_CHILD_CLONE_STACK_SIZE (64 * 1024) - /* - * See clone(2). - * Instead of worrying about which direction the stack grows, just - * allocate twice as much and start the stack in the middle. - */ - if ((c->clone_stack = malloc(2 * START_CHILD_CLONE_STACK_SIZE)) == NULL) - /* errno will be set to ENOMEM */ - return -1; - return clone(childProcess, - c->clone_stack + START_CHILD_CLONE_STACK_SIZE, - CLONE_VFORK | CLONE_VM | SIGCHLD, c); -#else -/* not available on Solaris / Mac */ - assert(0); - return -1; -#endif -} -#endif - static pid_t vforkChild(ChildStuff *c) { volatile pid_t resultPid; @@ -590,12 +563,11 @@ Java_java_lang_ProcessImpl_forkAndExec(JNIEnv *env, c->argv = NULL; c->envv = NULL; c->pdir = NULL; - c->clone_stack = NULL; /* Convert prog + argBlock into a char ** argv. * Add one word room for expansion of argv for use by * execve_as_traditional_shell_script. - * This word is also used when using spawn mode + * This word is also used when using posix_spawn mode */ assert(prog != NULL && argBlock != NULL); if ((phelperpath = getBytes(env, helperpath)) == NULL) goto Catch; @@ -654,7 +626,7 @@ Java_java_lang_ProcessImpl_forkAndExec(JNIEnv *env, throwIOException(env, errno, "fork failed"); break; case MODE_POSIX_SPAWN: - throwIOException(env, errno, "spawn failed"); + throwIOException(env, errno, "posix_spawn failed"); break; } goto Catch; @@ -677,8 +649,6 @@ Java_java_lang_ProcessImpl_forkAndExec(JNIEnv *env, fds[2] = (err[0] != -1) ? err[0] : -1; Finally: - free(c->clone_stack); - /* Always clean up the child's side of the pipes */ closeSafely(in [0]); closeSafely(out[1]); diff --git a/jdk/src/java.base/unix/native/libjava/childproc.c b/jdk/src/java.base/unix/native/libjava/childproc.c index 1d183cf1fb2..3f2932f1d50 100644 --- a/jdk/src/java.base/unix/native/libjava/childproc.c +++ b/jdk/src/java.base/unix/native/libjava/childproc.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -304,7 +304,7 @@ JDK_execvpe(int mode, const char *file, } /** - * Child process after a successful fork() or clone(). + * Child process after a successful fork(). * This function must not return, and must be prepared for either all * of its address space to be shared with its parent, or to be a copy. * It must not modify global variables such as "environ". diff --git a/jdk/src/java.base/unix/native/libjava/childproc.h b/jdk/src/java.base/unix/native/libjava/childproc.h index 4dd129c2d66..4a32b93f852 100644 --- a/jdk/src/java.base/unix/native/libjava/childproc.h +++ b/jdk/src/java.base/unix/native/libjava/childproc.h @@ -101,7 +101,6 @@ typedef struct _ChildStuff const char **envv; const char *pdir; int redirectErrorStream; - void *clone_stack; } ChildStuff; /* following used in addition when mode is SPAWN */ diff --git a/jdk/src/java.base/unix/native/libjava/jni_util_md.c b/jdk/src/java.base/unix/native/libjava/jni_util_md.c index 36d3565c401..e0c479b96ca 100644 --- a/jdk/src/java.base/unix/native/libjava/jni_util_md.c +++ b/jdk/src/java.base/unix/native/libjava/jni_util_md.c @@ -55,10 +55,12 @@ void buildJniFunctionName(const char *sym, const char *cname, size_t getLastErrorString(char *buf, size_t len) { + char *err; + size_t n; if (errno == 0 || len < 1) return 0; - const char *err = strerror(errno); - size_t n = strlen(err); + err = strerror(errno); + n = strlen(err); if (n >= len) n = len - 1; diff --git a/jdk/src/java.base/unix/native/libjli/java_md.h b/jdk/src/java.base/unix/native/libjli/java_md.h index 212ae0a2732..ab99dbbdf66 100644 --- a/jdk/src/java.base/unix/native/libjli/java_md.h +++ b/jdk/src/java.base/unix/native/libjli/java_md.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,6 +43,12 @@ #define MAXNAMELEN PATH_MAX #endif +#ifdef _LP64 +#define JLONG_FORMAT_SPECIFIER "%ld" +#else +#define JLONG_FORMAT_SPECIFIER "%lld" +#endif + int UnsetEnv(char *name); char *FindExecName(char *program); const char *SetExecname(char **argv); diff --git a/jdk/src/java.base/unix/native/libjli/java_md_common.c b/jdk/src/java.base/unix/native/libjli/java_md_common.c index 27d5a2ddcaa..48c0d8b377e 100644 --- a/jdk/src/java.base/unix/native/libjli/java_md_common.c +++ b/jdk/src/java.base/unix/native/libjli/java_md_common.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -269,11 +269,6 @@ UnsetEnv(char *name) return(borrowed_unsetenv(name)); } -const char * -jlong_format_specifier() { - return "%lld"; -} - jboolean IsJavaw() { diff --git a/jdk/src/java.base/unix/native/libjli/java_md_solinux.c b/jdk/src/java.base/unix/native/libjli/java_md_solinux.c index c453276b458..00b0f690651 100644 --- a/jdk/src/java.base/unix/native/libjli/java_md_solinux.c +++ b/jdk/src/java.base/unix/native/libjli/java_md_solinux.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -888,7 +888,7 @@ ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void if (pthread_create(&tid, &attr, (void *(*)(void*))continuation, (void*)args) == 0) { void * tmp; pthread_join(tid, &tmp); - rslt = (int)tmp; + rslt = (int)(intptr_t)tmp; } else { /* * Continue execution in current thread if for some reason (e.g. out of @@ -906,7 +906,7 @@ ContinueInNewThread0(int (JNICALL *continuation)(void *), jlong stack_size, void if (thr_create(NULL, stack_size, (void *(*)(void *))continuation, args, flags, &tid) == 0) { void * tmp; thr_join(tid, NULL, &tmp); - rslt = (int)tmp; + rslt = (int)(intptr_t)tmp; } else { /* See above. Continue in current thread if thr_create() failed */ rslt = continuation(args); diff --git a/jdk/src/java.base/windows/classes/java/lang/ProcessImpl.java b/jdk/src/java.base/windows/classes/java/lang/ProcessImpl.java index ec90ea0da3a..f6ed286d991 100644 --- a/jdk/src/java.base/windows/classes/java/lang/ProcessImpl.java +++ b/jdk/src/java.base/windows/classes/java/lang/ProcessImpl.java @@ -458,12 +458,11 @@ final class ProcessImpl extends Process { public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException { + long remainingNanos = unit.toNanos(timeout); // throw NPE before other conditions if (getExitCodeProcess(handle) != STILL_ACTIVE) return true; if (timeout <= 0) return false; - long remainingNanos = unit.toNanos(timeout); long deadline = System.nanoTime() + remainingNanos ; - do { // Round up to next millisecond long msTimeout = TimeUnit.NANOSECONDS.toMillis(remainingNanos + 999_999L); diff --git a/jdk/src/java.base/windows/classes/sun/nio/ch/WindowsSelectorImpl.java b/jdk/src/java.base/windows/classes/sun/nio/ch/WindowsSelectorImpl.java index eec35ea9518..28fc83a0b31 100644 --- a/jdk/src/java.base/windows/classes/sun/nio/ch/WindowsSelectorImpl.java +++ b/jdk/src/java.base/windows/classes/sun/nio/ch/WindowsSelectorImpl.java @@ -40,6 +40,7 @@ import java.util.List; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; +import sun.misc.ManagedLocalsThread; /** * A multi-threaded implementation of Selector for Windows. @@ -403,7 +404,7 @@ final class WindowsSelectorImpl extends SelectorImpl { } // Represents a helper thread used for select. - private final class SelectThread extends Thread { + private final class SelectThread extends ManagedLocalsThread { private final int index; // index of this thread final SubSelector subSelector; private long lastRun = 0; // last run number diff --git a/jdk/src/java.base/windows/conf/security/java.policy b/jdk/src/java.base/windows/conf/security/java.policy index 01d7bef3f43..cff0be5af98 100644 --- a/jdk/src/java.base/windows/conf/security/java.policy +++ b/jdk/src/java.base/windows/conf/security/java.policy @@ -6,3 +6,7 @@ grant codeBase "jrt:/jdk.crypto.mscapi" { permission java.security.SecurityPermission "clearProviderProperties.SunMSCAPI"; permission java.security.SecurityPermission "removeProviderProperty.SunMSCAPI"; }; + +grant codeBase "jrt:/jdk.accessibility" { + permission java.security.AllPermission; +}; diff --git a/jdk/src/java.base/windows/native/launcher/java.manifest b/jdk/src/java.base/windows/native/launcher/java.manifest index 52f997e8b39..906624bd6fa 100644 --- a/jdk/src/java.base/windows/native/launcher/java.manifest +++ b/jdk/src/java.base/windows/native/launcher/java.manifest @@ -4,12 +4,12 @@ xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" > -Java(TM) SE PROGRAM process +Java(TM) SE process = 6; + if (dtzi.TimeZoneKeyName[0] != 0) { + if (dtzi.DynamicDaylightTimeDisabled) { + customZoneName(dtzi.Bias, winZoneName); + return VALUE_GMTOFFSET; + } + wcstombs(winZoneName, dtzi.TimeZoneKeyName, MAX_ZONE_CHAR); + return VALUE_KEY; + } - ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_CURRENT_TZ_KEY, 0, - KEY_READ, (PHKEY)&hKey); - if (ret == ERROR_SUCCESS) { - DWORD val; - DWORD bufSize; + /* + * If TimeZoneKeyName is not available, check whether StandardName + * is available to fall back to the older API GetTimeZoneInformation. + * If not, directly read the value from registry keys. + */ + if (dtzi.StandardName[0] == 0) { + ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_CURRENT_TZ_KEY, 0, + KEY_READ, (PHKEY)&hKey); + if (ret != ERROR_SUCCESS) { + goto err; + } /* * Determine if auto-daylight time adjustment is turned off. */ - valueType = 0; bufSize = sizeof(val); - ret = RegQueryValueExA(hKey, "DisableAutoDaylightTimeSet", - NULL, &valueType, (LPBYTE) &val, &bufSize); - /* - * Vista uses the different key name. - */ + ret = RegQueryValueExA(hKey, "DynamicDaylightTimeDisabled", NULL, + &valueType, (LPBYTE) &val, &bufSize); if (ret != ERROR_SUCCESS) { - bufSize = sizeof(val); - ret = RegQueryValueExA(hKey, "DynamicDaylightTimeDisabled", - NULL, &valueType, (LPBYTE) &val, &bufSize); + goto err; } - - if (ret == ERROR_SUCCESS) { - int daylightSavingsUpdateDisabledOther = val == 1 && tzi.DaylightDate.wMonth != 0; - int daylightSavingsUpdateDisabledVista = val == 1; - int daylightSavingsUpdateDisabled = isVista ? daylightSavingsUpdateDisabledVista : daylightSavingsUpdateDisabledOther; - - if (daylightSavingsUpdateDisabled) { - (void) RegCloseKey(hKey); - customZoneName(tzi.Bias, winZoneName); - return VALUE_GMTOFFSET; - } - } - /* - * Vista has the key for the current "Time Zones" entry. + * Return a custom time zone name if auto-daylight time adjustment + * is disabled. */ - if (isVista) { - valueType = 0; - bufSize = MAX_ZONE_CHAR; - ret = RegQueryValueExA(hKey, "TimeZoneKeyName", NULL, - &valueType, (LPBYTE) winZoneName, &bufSize); - if (ret != ERROR_SUCCESS) { - goto err; - } + if (val == 1) { + customZoneName(dtzi.Bias, winZoneName); (void) RegCloseKey(hKey); - return VALUE_KEY; + return VALUE_GMTOFFSET; } - /* - * Win32 problem: If the length of the standard time name is equal - * to (or probably longer than) 32 in the registry, - * GetTimeZoneInformation() on NT returns a null string as its - * standard time name. We need to work around this problem by - * getting the same information from the TimeZoneInformation - * registry. The function on Win98 seems to return its key name. - * We can't do anything in that case. - */ - if (tzi.StandardName[0] == 0) { - bufSize = sizeof(stdNameInReg); - ret = getValueInRegistry(hKey, STANDARD_NAME, &valueType, - (LPBYTE) stdNameInReg, &bufSize); - if (ret != ERROR_SUCCESS) { - goto err; - } - stdNamePtr = stdNameInReg; + bufSize = MAX_ZONE_CHAR; + ret = RegQueryValueExA(hKey, "TimeZoneKeyName", NULL, + &valueType, (LPBYTE) winZoneName, &bufSize); + if (ret != ERROR_SUCCESS) { + goto err; } (void) RegCloseKey(hKey); - } - - /* - * Open the "Time Zones" registry. - */ - ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, NT_TZ_KEY, 0, KEY_READ, (PHKEY)&hKey); - if (ret != ERROR_SUCCESS) { - ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_TZ_KEY, 0, KEY_READ, (PHKEY)&hKey); + return VALUE_KEY; + } else { /* - * If both failed, then give up. + * Fall back to GetTimeZoneInformation */ - if (ret != ERROR_SUCCESS) { - return VALUE_UNKNOWN; - } - } + TIME_ZONE_INFORMATION tzi; + HANDLE hSubKey = NULL; + DWORD nSubKeys, i; + ULONG valueType; + TCHAR subKeyName[MAX_ZONE_CHAR]; + TCHAR szValue[MAX_ZONE_CHAR]; + WCHAR stdNameInReg[MAX_ZONE_CHAR]; + TziValue tempTzi; + WCHAR *stdNamePtr = tzi.StandardName; + DWORD valueSize; + int onlyMapID; - /* - * Get the number of subkeys of the "Time Zones" registry for - * enumeration. - */ - ret = RegQueryInfoKey(hKey, NULL, NULL, NULL, &nSubKeys, - NULL, NULL, NULL, NULL, NULL, NULL, NULL); - if (ret != ERROR_SUCCESS) { - goto err; - } - - /* - * Compare to the "Std" value of each subkey and find the entry that - * matches the current control panel setting. - */ - onlyMapID = 0; - for (i = 0; i < nSubKeys; ++i) { - DWORD size = sizeof(subKeyName); - ret = RegEnumKeyEx(hKey, i, subKeyName, &size, NULL, NULL, NULL, NULL); - if (ret != ERROR_SUCCESS) { - goto err; - } - ret = RegOpenKeyEx(hKey, subKeyName, 0, KEY_READ, (PHKEY)&hSubKey); - if (ret != ERROR_SUCCESS) { + timeType = GetTimeZoneInformation(&tzi); + if (timeType == TIME_ZONE_ID_INVALID) { goto err; } - size = sizeof(szValue); - ret = getValueInRegistry(hSubKey, STD_NAME, &valueType, - szValue, &size); - if (ret != ERROR_SUCCESS) { + ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_CURRENT_TZ_KEY, 0, + KEY_READ, (PHKEY)&hKey); + if (ret == ERROR_SUCCESS) { /* - * NT 4.0 SP3 fails here since it doesn't have the "Std" - * entry in the Time Zones registry. + * Determine if auto-daylight time adjustment is turned off. */ - RegCloseKey(hSubKey); - onlyMapID = 1; - ret = RegOpenKeyExW(hKey, stdNamePtr, 0, KEY_READ, (PHKEY)&hSubKey); + bufSize = sizeof(val); + ret = RegQueryValueExA(hKey, "DynamicDaylightTimeDisabled", NULL, + &valueType, (LPBYTE) &val, &bufSize); + if (ret == ERROR_SUCCESS) { + if (val == 1 && tzi.DaylightDate.wMonth != 0) { + (void) RegCloseKey(hKey); + customZoneName(tzi.Bias, winZoneName); + return VALUE_GMTOFFSET; + } + } + + /* + * Win32 problem: If the length of the standard time name is equal + * to (or probably longer than) 32 in the registry, + * GetTimeZoneInformation() on NT returns a null string as its + * standard time name. We need to work around this problem by + * getting the same information from the TimeZoneInformation + * registry. + */ + if (tzi.StandardName[0] == 0) { + bufSize = sizeof(stdNameInReg); + ret = getValueInRegistry(hKey, STANDARD_NAME, &valueType, + (LPBYTE) stdNameInReg, &bufSize); + if (ret != ERROR_SUCCESS) { + goto err; + } + stdNamePtr = stdNameInReg; + } + (void) RegCloseKey(hKey); + } + + /* + * Open the "Time Zones" registry. + */ + ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, NT_TZ_KEY, 0, KEY_READ, (PHKEY)&hKey); + if (ret != ERROR_SUCCESS) { + ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_TZ_KEY, 0, KEY_READ, (PHKEY)&hKey); + /* + * If both failed, then give up. + */ + if (ret != ERROR_SUCCESS) { + return VALUE_UNKNOWN; + } + } + + /* + * Get the number of subkeys of the "Time Zones" registry for + * enumeration. + */ + ret = RegQueryInfoKey(hKey, NULL, NULL, NULL, &nSubKeys, + NULL, NULL, NULL, NULL, NULL, NULL, NULL); + if (ret != ERROR_SUCCESS) { + goto err; + } + + /* + * Compare to the "Std" value of each subkey and find the entry that + * matches the current control panel setting. + */ + onlyMapID = 0; + for (i = 0; i < nSubKeys; ++i) { + DWORD size = sizeof(subKeyName); + ret = RegEnumKeyEx(hKey, i, subKeyName, &size, NULL, NULL, NULL, NULL); + if (ret != ERROR_SUCCESS) { + goto err; + } + ret = RegOpenKeyEx(hKey, subKeyName, 0, KEY_READ, (PHKEY)&hSubKey); if (ret != ERROR_SUCCESS) { goto err; } - break; - } - if (wcscmp((WCHAR *)szValue, stdNamePtr) == 0) { - /* - * Some localized Win32 platforms use a same name to - * different time zones. So, we can't rely only on the name - * here. We need to check GMT offsets and transition dates - * to make sure it's the registry of the current time - * zone. - */ - DWORD tziValueSize = sizeof(tempTzi); - ret = RegQueryValueEx(hSubKey, "TZI", NULL, &valueType, - (unsigned char *) &tempTzi, &tziValueSize); - if (ret == ERROR_SUCCESS) { - if ((tzi.Bias != tempTzi.bias) || - (memcmp((const void *) &tzi.StandardDate, - (const void *) &tempTzi.stdDate, - sizeof(SYSTEMTIME)) != 0)) { - goto out; + size = sizeof(szValue); + ret = getValueInRegistry(hSubKey, STD_NAME, &valueType, + szValue, &size); + if (ret != ERROR_SUCCESS) { + /* + * NT 4.0 SP3 fails here since it doesn't have the "Std" + * entry in the Time Zones registry. + */ + RegCloseKey(hSubKey); + onlyMapID = 1; + ret = RegOpenKeyExW(hKey, stdNamePtr, 0, KEY_READ, (PHKEY)&hSubKey); + if (ret != ERROR_SUCCESS) { + goto err; } + break; + } - if (tzi.DaylightBias != 0) { - if ((tzi.DaylightBias != tempTzi.dstBias) || - (memcmp((const void *) &tzi.DaylightDate, - (const void *) &tempTzi.dstDate, + if (wcscmp((WCHAR *)szValue, stdNamePtr) == 0) { + /* + * Some localized Win32 platforms use a same name to + * different time zones. So, we can't rely only on the name + * here. We need to check GMT offsets and transition dates + * to make sure it's the registry of the current time + * zone. + */ + DWORD tziValueSize = sizeof(tempTzi); + ret = RegQueryValueEx(hSubKey, "TZI", NULL, &valueType, + (unsigned char *) &tempTzi, &tziValueSize); + if (ret == ERROR_SUCCESS) { + if ((tzi.Bias != tempTzi.bias) || + (memcmp((const void *) &tzi.StandardDate, + (const void *) &tempTzi.stdDate, sizeof(SYSTEMTIME)) != 0)) { goto out; } + + if (tzi.DaylightBias != 0) { + if ((tzi.DaylightBias != tempTzi.dstBias) || + (memcmp((const void *) &tzi.DaylightDate, + (const void *) &tempTzi.dstDate, + sizeof(SYSTEMTIME)) != 0)) { + goto out; + } + } } + + /* + * found matched record, terminate search + */ + strcpy(winZoneName, subKeyName); + break; } - - /* - * found matched record, terminate search - */ - strcpy(winZoneName, subKeyName); - break; + out: + (void) RegCloseKey(hSubKey); } - out: - (void) RegCloseKey(hSubKey); - } - /* - * Get the "MapID" value of the registry to be able to eliminate - * duplicated key names later. - */ - valueSize = MAX_MAPID_LENGTH; - ret = RegQueryValueExA(hSubKey, "MapID", NULL, &valueType, winMapID, &valueSize); - (void) RegCloseKey(hSubKey); - (void) RegCloseKey(hKey); - - if (ret != ERROR_SUCCESS) { /* - * Vista doesn't have mapID. VALUE_UNKNOWN should be returned - * only for Windows NT. + * Get the "MapID" value of the registry to be able to eliminate + * duplicated key names later. */ - if (onlyMapID == 1) { - return VALUE_UNKNOWN; + valueSize = MAX_MAPID_LENGTH; + ret = RegQueryValueExA(hSubKey, "MapID", NULL, &valueType, winMapID, &valueSize); + (void) RegCloseKey(hSubKey); + (void) RegCloseKey(hKey); + + if (ret != ERROR_SUCCESS) { + /* + * Vista doesn't have mapID. VALUE_UNKNOWN should be returned + * only for Windows NT. + */ + if (onlyMapID == 1) { + return VALUE_UNKNOWN; + } } } diff --git a/jdk/src/java.base/windows/native/libjli/cmdtoargs.c b/jdk/src/java.base/windows/native/libjli/cmdtoargs.c index f4f893825ec..cfc1a463e81 100644 --- a/jdk/src/java.base/windows/native/libjli/cmdtoargs.c +++ b/jdk/src/java.base/windows/native/libjli/cmdtoargs.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -77,7 +77,7 @@ static char* next_arg(char* cmdline, char* arg, jboolean* wildcard) { USHORT ch = 0; int i; jboolean done = JNI_FALSE; - int charLength; + ptrdiff_t charLength; *wildcard = JNI_FALSE; while (!done) { @@ -208,10 +208,12 @@ void JLI_CmdToArgs(char* cmdline) { argv = (StdArg*) JLI_MemRealloc(argv, (nargs+1) * sizeof(StdArg)); argv[nargs].arg = JLI_StringDup(arg); argv[nargs].has_wildcard = wildcard; - *arg = NULL; + *arg = '\0'; nargs++; } while (src != NULL); + JLI_MemFree(arg); + stdargc = nargs; stdargs = argv; } diff --git a/jdk/src/java.base/windows/native/libjli/java_md.c b/jdk/src/java.base/windows/native/libjli/java_md.c index 2bf50ea7fc3..596e263ec07 100644 --- a/jdk/src/java.base/windows/native/libjli/java_md.c +++ b/jdk/src/java.base/windows/native/libjli/java_md.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -107,7 +107,7 @@ int awtPreloadD3D = -1; * GetParamValue("theParam", "theParam=value") returns pointer to "value". */ const char * GetParamValue(const char *paramName, const char *arg) { - int nameLen = JLI_StrLen(paramName); + size_t nameLen = JLI_StrLen(paramName); if (JLI_StrNCmp(paramName, arg, nameLen) == 0) { /* arg[nameLen] is valid (may contain final NULL) */ if (arg[nameLen] == '=') { @@ -561,7 +561,7 @@ JLI_Snprintf(char* buffer, size_t size, const char* format, ...) { if (rc < 0) { /* apply ansi semantics */ buffer[size - 1] = '\0'; - return size; + return (int)size; } else if (rc == size) { /* force a null terminator */ buffer[size - 1] = '\0'; @@ -728,11 +728,6 @@ void SplashFreeLibrary() { } } -const char * -jlong_format_specifier() { - return "%I64d"; -} - /* * Block current thread and continue execution in a new thread */ @@ -882,7 +877,7 @@ int AWTPreload(const char *funcName) if (hPreloadAwt == NULL) { /* awt.dll is not loaded yet */ char libraryPath[MAXPATHLEN]; - int jrePathLen = 0; + size_t jrePathLen = 0; HMODULE hJava = NULL; HMODULE hVerify = NULL; @@ -1004,7 +999,8 @@ ProcessPlatformOption(const char *arg) jobjectArray CreateApplicationArgs(JNIEnv *env, char **strv, int argc) { - int i, j, idx, tlen; + int i, j, idx; + size_t tlen; jobjectArray outArray, inArray; char *ostart, *astart, **nargv; jboolean needs_expansion = JNI_FALSE; diff --git a/jdk/src/java.base/windows/native/libjli/java_md.h b/jdk/src/java.base/windows/native/libjli/java_md.h index aa9fc2f0b44..76c15ea8e32 100644 --- a/jdk/src/java.base/windows/native/libjli/java_md.h +++ b/jdk/src/java.base/windows/native/libjli/java_md.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,6 +39,7 @@ #define MAXPATHLEN MAX_PATH #define MAXNAMELEN MAX_PATH +#define JLONG_FORMAT_SPECIFIER "%I64d" /* * Support for doing cheap, accurate interval timing. diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaFileSystemModel.java b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaFileSystemModel.java index b0713215077..7aa82f51a9e 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaFileSystemModel.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaFileSystemModel.java @@ -25,15 +25,16 @@ package com.apple.laf; + import java.beans.*; import java.io.File; import java.util.*; - import javax.swing.*; import javax.swing.event.ListDataEvent; import javax.swing.filechooser.FileSystemView; import javax.swing.table.AbstractTableModel; +import sun.misc.ManagedLocalsThread; /** * NavServices-like implementation of a file Table * @@ -42,7 +43,7 @@ import javax.swing.table.AbstractTableModel; @SuppressWarnings("serial") // Superclass is not serializable across versions class AquaFileSystemModel extends AbstractTableModel implements PropertyChangeListener { private final JTable fFileList; - private LoadFilesThread loadThread = null; + private FilesLoader filesLoader = null; private Vector files = null; JFileChooser filechooser = null; @@ -141,9 +142,9 @@ class AquaFileSystemModel extends AbstractTableModel implements PropertyChangeLi public void runWhenDone(final Runnable runnable){ synchronized (fileCacheLock) { - if (loadThread != null) { - if (loadThread.isAlive()) { - loadThread.queuedTasks.add(runnable); + if (filesLoader != null) { + if (filesLoader.loadThread.isAlive()) { + filesLoader.queuedTasks.add(runnable); return; } } @@ -160,9 +161,9 @@ class AquaFileSystemModel extends AbstractTableModel implements PropertyChangeLi return; } - if (loadThread != null) { + if (filesLoader != null) { // interrupt - loadThread.interrupt(); + filesLoader.loadThread.interrupt(); } fetchID++; @@ -173,8 +174,7 @@ class AquaFileSystemModel extends AbstractTableModel implements PropertyChangeLi fileCache = new Vector(50); } - loadThread = new LoadFilesThread(currentDirectory, fetchID); - loadThread.start(); + filesLoader = new FilesLoader(currentDirectory, fetchID); } public int getColumnCount() { @@ -373,17 +373,25 @@ class AquaFileSystemModel extends AbstractTableModel implements PropertyChangeLi } } - class LoadFilesThread extends Thread { - Vector queuedTasks = new Vector(); + class FilesLoader implements Runnable { + Vector queuedTasks = new Vector<>(); File currentDirectory = null; int fid; + Thread loadThread; - public LoadFilesThread(final File currentDirectory, final int fid) { - super("Aqua L&F File Loading Thread"); + public FilesLoader(final File currentDirectory, final int fid) { this.currentDirectory = currentDirectory; this.fid = fid; + String name = "Aqua L&F File Loading Thread"; + if (System.getSecurityManager() == null) { + this.loadThread = new Thread(FilesLoader.this, name); + } else { + this.loadThread = new ManagedLocalsThread(FilesLoader.this, name); + } + this.loadThread.start(); } + @Override public void run() { final Vector runnables = new Vector(10); final FileSystemView fileSystem = filechooser.getFileSystemView(); @@ -415,7 +423,7 @@ class AquaFileSystemModel extends AbstractTableModel implements PropertyChangeLi runnables.addElement(runnable); SwingUtilities.invokeLater(runnable); chunk = new Vector(10); - if (isInterrupted()) { + if (loadThread.isInterrupted()) { // interrupted, cancel all runnables cancelRunnables(runnables); return; diff --git a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaScrollPaneUI.java b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaScrollPaneUI.java index ee0bf7cdf54..0729321552d 100644 --- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaScrollPaneUI.java +++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaScrollPaneUI.java @@ -29,6 +29,7 @@ import java.awt.event.*; import javax.swing.*; import javax.swing.plaf.ComponentUI; +import javax.swing.plaf.basic.BasicScrollPaneUI; public class AquaScrollPaneUI extends javax.swing.plaf.basic.BasicScrollPaneUI { public static ComponentUI createUI(final JComponent x) { @@ -39,28 +40,9 @@ public class AquaScrollPaneUI extends javax.swing.plaf.basic.BasicScrollPaneUI { return new XYMouseWheelHandler(); } - // This is a grody hack to trick BasicScrollPaneUI into scrolling horizontally - // when we notice that the shift key is down. This should be removed when AWT/Swing - // becomes aware of multi-axis scroll wheels. - protected class XYMouseWheelHandler extends javax.swing.plaf.basic.BasicScrollPaneUI.MouseWheelHandler { + protected class XYMouseWheelHandler extends BasicScrollPaneUI.MouseWheelHandler { public void mouseWheelMoved(final MouseWheelEvent e) { - JScrollBar vScrollBar = null; - boolean wasVisible = false; - - if (e.isShiftDown()) { - vScrollBar = scrollpane.getVerticalScrollBar(); - if (vScrollBar != null) { - wasVisible = vScrollBar.isVisible(); - vScrollBar.setVisible(false); - } - } - super.mouseWheelMoved(e); - - if (wasVisible) { - vScrollBar.setVisible(true); - } - // Consume the event even when the scrollBar is invisible // see #7124320 e.consume(); diff --git a/jdk/src/java.desktop/macosx/classes/sun/font/CFontManager.java b/jdk/src/java.desktop/macosx/classes/sun/font/CFontManager.java index e37e9e449ea..341af9ff347 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/font/CFontManager.java +++ b/jdk/src/java.desktop/macosx/classes/sun/font/CFontManager.java @@ -42,9 +42,9 @@ import sun.awt.FontConfiguration; import sun.awt.HeadlessToolkit; import sun.awt.util.ThreadGroupUtils; import sun.lwawt.macosx.*; +import sun.misc.InnocuousThread; public final class CFontManager extends SunFontManager { - private FontConfigManager fcManager = null; private static Hashtable genericFonts = new Hashtable(); @Override @@ -212,14 +212,18 @@ public final class CFontManager extends SunFontManager { }); } }; - AccessController.doPrivileged( - (PrivilegedAction) () -> { - /* The thread must be a member of a thread group - * which will not get GCed before VM exit. - * Make its parent the top-level thread group. - */ - ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); - fileCloser = new Thread(rootTG, fileCloserRunnable); + AccessController.doPrivileged((PrivilegedAction) () -> { + if (System.getSecurityManager() == null) { + /* The thread must be a member of a thread group + * which will not get GCed before VM exit. + * Make its parent the top-level thread group. + */ + ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); + fileCloser = new Thread(rootTG, fileCloserRunnable); + } else { + /* InnocuousThread is a member of a correct TG by default */ + fileCloser = new InnocuousThread(fileCloserRunnable); + } fileCloser.setContextClassLoader(null); Runtime.getRuntime().addShutdownHook(fileCloser); return null; @@ -231,15 +235,6 @@ public final class CFontManager extends SunFontManager { return font2D; } - /* - public synchronized FontConfigManager getFontConfigManager() { - if (fcManager == null) { - fcManager = new FontConfigManager(); - } - return fcManager; - } - */ - protected void registerFontsInDir(String dirName, boolean useJavaRasterizer, int fontRank, boolean defer, boolean resolveSymLinks) { loadNativeDirFonts(dirName); super.registerFontsInDir(dirName, useJavaRasterizer, fontRank, defer, resolveSymLinks); diff --git a/jdk/src/java.desktop/macosx/classes/sun/font/NativeFont.java b/jdk/src/java.desktop/macosx/classes/sun/font/NativeFont.java new file mode 100644 index 00000000000..0eb6db7e6e0 --- /dev/null +++ b/jdk/src/java.desktop/macosx/classes/sun/font/NativeFont.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.font; + +import java.awt.FontFormatException; +import java.awt.font.FontRenderContext; +import java.awt.geom.GeneralPath; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; + +/* + * This class should never be invoked on the windows implementation + * So the constructor throws a FontFormatException, which is caught + * and the font is ignored. + */ + +public class NativeFont extends PhysicalFont { + + /** + * Verifies native font is accessible. + * @throws FontFormatException - if the font can't be located. + */ + public NativeFont(String platName, boolean isBitmapDelegate) + throws FontFormatException { + + throw new FontFormatException("NativeFont not used on OS X"); + } + + static boolean hasExternalBitmaps(String platName) { + return false; + } + + public CharToGlyphMapper getMapper() { + return null; + } + + PhysicalFont getDelegateFont() { + return null; + } + + FontStrike createStrike(FontStrikeDesc desc) { + return null; + } + + public Rectangle2D getMaxCharBounds(FontRenderContext frc) { + return null; + } + + StrikeMetrics getFontMetrics(long pScalerContext) { + return null; + } + + public GeneralPath getGlyphOutline(long pScalerContext, + int glyphCode, + float x, float y) { + return null; + } + + public GeneralPath getGlyphVectorOutline(long pScalerContext, + int[] glyphs, int numGlyphs, + float x, float y) { + return null; + } + + + long getGlyphImage(long pScalerContext, int glyphCode) { + return 0L; + } + + + void getGlyphMetrics(long pScalerContext, int glyphCode, + Point2D.Float metrics) { + } + + + float getGlyphAdvance(long pScalerContext, int glyphCode) { + return 0f; + } + + Rectangle2D.Float getGlyphOutlineBounds(long pScalerContext, + int glyphCode) { + return new Rectangle2D.Float(0f, 0f, 0f, 0f); + } +} diff --git a/jdk/src/java.desktop/macosx/classes/sun/font/NativeStrike.java b/jdk/src/java.desktop/macosx/classes/sun/font/NativeStrike.java new file mode 100644 index 00000000000..de5c3aca312 --- /dev/null +++ b/jdk/src/java.desktop/macosx/classes/sun/font/NativeStrike.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.font; + +import java.awt.geom.GeneralPath; +import java.awt.geom.Point2D; +import java.awt.Rectangle; +import java.awt.geom.Rectangle2D; + +public class NativeStrike extends PhysicalStrike { + + NativeFont nativeFont; + + NativeStrike(NativeFont nativeFont, FontStrikeDesc desc) { + super(nativeFont, desc); + + throw new RuntimeException("NativeFont not used on OS X"); + } + + NativeStrike(NativeFont nativeFont, FontStrikeDesc desc, + boolean nocache) { + super(nativeFont, desc); + + throw new RuntimeException("NativeFont not used on Windows"); + } + + + void getGlyphImagePtrs(int[] glyphCodes, long[] images,int len) { + } + + long getGlyphImagePtr(int glyphCode) { + return 0L; + } + + long getGlyphImagePtrNoCache(int glyphCode) { + return 0L; + } + + void getGlyphImageBounds(int glyphcode, + Point2D.Float pt, + Rectangle result) { + } + + Point2D.Float getGlyphMetrics(int glyphCode) { + return null; + } + + float getGlyphAdvance(int glyphCode) { + return 0f; + } + + Rectangle2D.Float getGlyphOutlineBounds(int glyphCode) { + return null; + } + GeneralPath getGlyphOutline(int glyphCode, float x, float y) { + return null; + } + + GeneralPath getGlyphVectorOutline(int[] glyphs, float x, float y) { + return null; + } + +} diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWCheckboxPeer.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWCheckboxPeer.java index c3b91a2fa86..fe85cce8081 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWCheckboxPeer.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWCheckboxPeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -132,7 +132,9 @@ final class LWCheckboxPeer @Override public void setState(final boolean state) { synchronized (getDelegateLock()) { + getDelegate().getCurrentButton().removeItemListener(this); getDelegate().setSelected(state); + getDelegate().getCurrentButton().addItemListener(this); } repaintPeer(); } diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWToolkit.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWToolkit.java index 315a19a7ff3..9aea94cdc6c 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWToolkit.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWToolkit.java @@ -35,6 +35,7 @@ import java.security.*; import java.util.*; import sun.awt.*; +import sun.misc.InnocuousThread; import sun.print.*; import sun.awt.util.ThreadGroupUtils; @@ -71,22 +72,32 @@ public abstract class LWToolkit extends SunToolkit implements Runnable { */ protected final void init() { AWTAutoShutdown.notifyToolkitThreadBusy(); - - ThreadGroup rootTG = AccessController.doPrivileged( - (PrivilegedAction) ThreadGroupUtils::getRootThreadGroup); - - Runtime.getRuntime().addShutdownHook( - new Thread(rootTG, () -> { + AccessController.doPrivileged((PrivilegedAction) () -> { + Runnable shutdownRunnable = () -> { shutdown(); waitForRunState(STATE_CLEANUP); - }) - ); - - Thread toolkitThread = new Thread(rootTG, this, "AWT-LW"); - toolkitThread.setDaemon(true); - toolkitThread.setPriority(Thread.NORM_PRIORITY + 1); - toolkitThread.start(); + }; + Thread shutdown; + if (System.getSecurityManager() == null) { + shutdown = new Thread(ThreadGroupUtils.getRootThreadGroup(), shutdownRunnable); + } else { + shutdown = new InnocuousThread(shutdownRunnable); + } + shutdown.setContextClassLoader(null); + Runtime.getRuntime().addShutdownHook(shutdown); + String name = "AWT-LW"; + Thread toolkitThread; + if (System.getSecurityManager() == null) { + toolkitThread = new Thread(ThreadGroupUtils.getRootThreadGroup(), LWToolkit.this, name); + } else { + toolkitThread = new InnocuousThread(LWToolkit.this, name); + } + toolkitThread.setDaemon(true); + toolkitThread.setPriority(Thread.NORM_PRIORITY + 1); + toolkitThread.start(); + return null; + }); waitForRunState(STATE_MESSAGELOOP); } diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWWindowPeer.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWWindowPeer.java index 386c8c7bb7f..d8656c58750 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWWindowPeer.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWWindowPeer.java @@ -1296,6 +1296,12 @@ public class LWWindowPeer } KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance(); + + if (!becomesFocused && kfmPeer.getCurrentFocusedWindow() != getTarget()) { + // late window focus lost event - ingoring + return; + } + kfmPeer.setCurrentFocusedWindow(becomesFocused ? getTarget() : null); int eventID = becomesFocused ? WindowEvent.WINDOW_GAINED_FOCUS : WindowEvent.WINDOW_LOST_FOCUS; diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CClipboard.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CClipboard.java index b657aee8ed9..19f9a408220 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CClipboard.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CClipboard.java @@ -56,6 +56,18 @@ final class CClipboard extends SunClipboard { // Leaving Empty, as WClipboard.clearNativeContext is empty as well. } + @Override + public synchronized Transferable getContents(Object requestor) { + checkPasteboardAndNotify(); + return super.getContents(requestor); + } + + @Override + protected synchronized Transferable getContextContents() { + checkPasteboardAndNotify(); + return super.getContextContents(); + } + @Override protected void setContentsNative(Transferable contents) { FlavorTable flavorMap = getDefaultFlavorTable(); @@ -116,13 +128,20 @@ final class CClipboard extends SunClipboard { private native void declareTypes(long[] formats, SunClipboard newOwner); private native void setData(byte[] data, long format); + void checkPasteboardAndNotify() { + if (checkPasteboardWithoutNotification()) { + notifyChanged(); + lostOwnershipNow(null); + } + } + /** * Invokes native check whether a change count on the general pasteboard is different * than when we set it. The different count value means the current owner lost * pasteboard ownership and someone else put data on the clipboard. * @since 1.7 */ - native void checkPasteboard(); + native boolean checkPasteboardWithoutNotification(); /*** Native Callbacks ***/ private void notifyLostOwnership() { diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java index 20c48cd4133..0f4224bb803 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java @@ -31,7 +31,6 @@ import java.awt.datatransfer.*; import java.awt.dnd.*; import java.awt.event.*; import java.awt.image.*; -import java.awt.peer.*; import javax.swing.*; import javax.swing.text.*; @@ -44,6 +43,7 @@ import sun.awt.dnd.*; import sun.lwawt.LWComponentPeer; import sun.lwawt.LWWindowPeer; import sun.lwawt.PlatformWindow; +import sun.misc.ManagedLocalsThread; public final class CDragSourceContextPeer extends SunDragSourceContextPeer { @@ -164,28 +164,29 @@ public final class CDragSourceContextPeer extends SunDragSourceContextPeer { // are posted during dragging by native event handlers. try { - Thread dragThread = new Thread() { - public void run() { - final long nativeDragSource = getNativeContext(); - try { - doDragging(nativeDragSource); - } catch (Exception e) { - e.printStackTrace(); - } finally { - releaseNativeDragSource(nativeDragSource); - fDragImage = null; - if (fDragCImage != null) { - fDragCImage.dispose(); - fDragCImage = null; - } + Runnable dragRunnable = () -> { + final long nativeDragSource = getNativeContext(); + try { + doDragging(nativeDragSource); + } catch (Exception e) { + e.printStackTrace(); + } finally { + releaseNativeDragSource(nativeDragSource); + fDragImage = null; + if (fDragCImage != null) { + fDragCImage.dispose(); + fDragCImage = null; } } }; - + Thread dragThread; + if (System.getSecurityManager() == null) { + dragThread = new Thread(dragRunnable); + } else { + dragThread = new ManagedLocalsThread(dragRunnable); + } dragThread.start(); - } - - catch (Exception e) { + } catch (Exception e) { final long nativeDragSource = getNativeContext(); setNativeContext(0); releaseNativeDragSource(nativeDragSource); diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java index fed9957502a..e1895c2e2f0 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java @@ -123,7 +123,7 @@ public class CEmbeddedFrame extends EmbeddedFrame { // it won't be invoced if focuse is moved to a html element // on the same page. CClipboard clipboard = (CClipboard) Toolkit.getDefaultToolkit().getSystemClipboard(); - clipboard.checkPasteboard(); + clipboard.checkPasteboardAndNotify(); } if (parentWindowActive) { responder.handleWindowFocusEvent(focused, null); @@ -164,7 +164,7 @@ public class CEmbeddedFrame extends EmbeddedFrame { } // ignore focus "lost" native request as it may mistakenly // deactivate active window (see 8001161) - if (globalFocusedWindow == this && parentWindowActive) { + if (globalFocusedWindow == this) { responder.handleWindowFocusEvent(parentWindowActive, null); } } diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CFileDialog.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CFileDialog.java index cc31b532f76..0e8ee1e1fc4 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CFileDialog.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CFileDialog.java @@ -37,6 +37,7 @@ import java.io.*; import sun.awt.CausedFocusEvent.Cause; import sun.awt.AWTAccessor; import sun.java2d.pipe.Region; +import sun.misc.ManagedLocalsThread; import sun.security.action.GetBooleanAction; class CFileDialog implements FileDialogPeer { @@ -119,7 +120,11 @@ class CFileDialog implements FileDialogPeer { if (visible) { // Java2 Dialog class requires peer to run code in a separate thread // and handles keeping the call modal - new Thread(new Task()).start(); // invokes my 'run' method, below... + if (System.getSecurityManager() == null) { + new Thread(new Task()).start(); + } else { + new ManagedLocalsThread(new Task()).start(); + } } // We hide ourself before "show" returns - setVisible(false) // doesn't apply diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterDialogPeer.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterDialogPeer.java index 8dfe7e1e51e..6ff3ec01e0e 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterDialogPeer.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterDialogPeer.java @@ -29,6 +29,7 @@ import java.awt.*; import java.awt.dnd.*; import sun.lwawt.*; +import sun.misc.ManagedLocalsThread; public class CPrinterDialogPeer extends LWWindowPeer { static { @@ -53,13 +54,16 @@ public class CPrinterDialogPeer extends LWWindowPeer { public void setVisible(boolean visible) { if (visible) { - new Thread(new Runnable() { - public void run() { - CPrinterDialog printerDialog = (CPrinterDialog)fTarget; - printerDialog.setRetVal(printerDialog.showDialog()); - printerDialog.setVisible(false); - } - }).start(); + Runnable task = () -> { + CPrinterDialog printerDialog = (CPrinterDialog)fTarget; + printerDialog.setRetVal(printerDialog.showDialog()); + printerDialog.setVisible(false); + }; + if (System.getSecurityManager() == null) { + new Thread(task).start(); + } else { + new ManagedLocalsThread(task).start(); + } } } diff --git a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterJob.java b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterJob.java index ede3bec7b73..b82094d5b7d 100644 --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterJob.java +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterJob.java @@ -39,6 +39,7 @@ import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.standard.PageRanges; import sun.java2d.*; +import sun.misc.ManagedLocalsThread; import sun.print.*; public final class CPrinterJob extends RasterPrinterJob { @@ -731,9 +732,12 @@ public final class CPrinterJob extends RasterPrinterJob { // upcall from native private static void detachPrintLoop(final long target, final long arg) { - new Thread() { public void run() { - _safePrintLoop(target, arg); - }}.start(); + Runnable task = () -> _safePrintLoop(target, arg); + if (System.getSecurityManager() == null) { + new Thread(task).start(); + } else { + new ManagedLocalsThread(task).start(); + } } private static native void _safePrintLoop(long target, long arg); diff --git a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m index 34b997988b4..e7466fc5cba 100644 --- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m +++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m @@ -311,7 +311,10 @@ AWT_ASSERT_APPKIT_THREAD; } - (BOOL) performKeyEquivalent: (NSEvent *) event { - [self deliverJavaKeyEventHelper: event]; + // if IM is active key events should be ignored + if (![self hasMarkedText] && !fInPressAndHold) { + [self deliverJavaKeyEventHelper: event]; + } // Workaround for 8020209: special case for "Cmd =" and "Cmd ." // because Cocoa calls performKeyEquivalent twice for these keystrokes diff --git a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CClipboard.m b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CClipboard.m index 15ae6db79dc..fceb2d72682 100644 --- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CClipboard.m +++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CClipboard.m @@ -107,6 +107,19 @@ } } +- (BOOL) checkPasteboardWithoutNotification:(id)application { + AWT_ASSERT_APPKIT_THREAD; + + NSInteger newChangeCount = [[NSPasteboard generalPasteboard] changeCount]; + + if (self.changeCount != newChangeCount) { + self.changeCount = newChangeCount; + return YES; + } else { + return NO; + } +} + @end /* @@ -260,21 +273,20 @@ JNF_COCOA_EXIT(env); return returnValue; } -/* - * Class: sun_lwawt_macosx_CClipboard - * Method: checkPasteboard - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CClipboard_checkPasteboard -(JNIEnv *env, jobject inObject ) -{ -JNF_COCOA_ENTER(env); - - [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ - [[CClipboard sharedClipboard] checkPasteboard:nil]; - }]; - -JNF_COCOA_EXIT(env); -} - - +/* + * Class: sun_lwawt_macosx_CClipboard + * Method: checkPasteboard + * Signature: ()V + */ +JNIEXPORT jboolean JNICALL Java_sun_lwawt_macosx_CClipboard_checkPasteboardWithoutNotification +(JNIEnv *env, jobject inObject) +{ + __block BOOL ret = NO; + JNF_COCOA_ENTER(env); + [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ + ret = [[CClipboard sharedClipboard] checkPasteboardWithoutNotification:nil]; + }]; + + JNF_COCOA_EXIT(env); + return ret; +} \ No newline at end of file diff --git a/jdk/src/java.desktop/macosx/native/libsplashscreen/splashscreen_sys.m b/jdk/src/java.desktop/macosx/native/libsplashscreen/splashscreen_sys.m index 25b00545a74..07bbd43e0a5 100644 --- a/jdk/src/java.desktop/macosx/native/libsplashscreen/splashscreen_sys.m +++ b/jdk/src/java.desktop/macosx/native/libsplashscreen/splashscreen_sys.m @@ -126,14 +126,28 @@ done: return buf; } +BOOL isSWTRunning() { + char envVar[80]; + // If this property is present we are running SWT + snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid()); + return getenv(envVar) != NULL; +} + char* SplashGetScaledImageName(const char* jar, const char* file, float *scaleFactor) { - NSAutoreleasePool *pool = [NSAutoreleasePool new]; *scaleFactor = 1; + + if(isSWTRunning()){ + return nil; + } + + NSAutoreleasePool *pool = [NSAutoreleasePool new]; char* scaledFile = nil; __block float screenScaleFactor = 1; [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ + // initialize NSApplication and AWT stuff + [NSApplicationAWT sharedApplication]; screenScaleFactor = [SplashNSScreen() backingScaleFactor]; }]; @@ -180,12 +194,8 @@ SplashInitPlatform(Splash * splash) { splash->screenFormat.byteOrder = 1 ? BYTE_ORDER_LSBFIRST : BYTE_ORDER_MSBFIRST; splash->screenFormat.depthBytes = 4; - // If this property is present we are running SWT and should not start a runLoop - // Can't check if running SWT in webstart, so splash screen in webstart SWT - // applications is not supported - char envVar[80]; - snprintf(envVar, sizeof(envVar), "JAVA_STARTED_ON_FIRST_THREAD_%d", getpid()); - if (getenv(envVar) == NULL) { + // If we are running SWT we should not start a runLoop + if (!isSWTRunning()) { [JNFRunLoop performOnMainThreadWaiting:NO withBlock:^() { [NSApplicationAWT runAWTLoopWithApp:[NSApplicationAWT sharedApplication]]; }]; diff --git a/jdk/src/java.desktop/share/classes/com/sun/imageio/stream/StreamCloser.java b/jdk/src/java.desktop/share/classes/com/sun/imageio/stream/StreamCloser.java index 356c0c092f9..b660f272e2c 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/imageio/stream/StreamCloser.java +++ b/jdk/src/java.desktop/share/classes/com/sun/imageio/stream/StreamCloser.java @@ -25,7 +25,12 @@ package com.sun.imageio.stream; +import sun.awt.util.ThreadGroupUtils; +import sun.misc.InnocuousThread; + import java.io.IOException; +import java.security.AccessController; +import java.security.PrivilegedAction; import java.util.Set; import java.util.WeakHashMap; import javax.imageio.stream.ImageInputStream; @@ -81,27 +86,25 @@ public class StreamCloser { } }; - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - /* The thread must be a member of a thread group - * which will not get GCed before VM exit. - * Make its parent the top-level thread group. - */ - ThreadGroup tg = - Thread.currentThread().getThreadGroup(); - for (ThreadGroup tgn = tg; - tgn != null; - tg = tgn, tgn = tg.getParent()); - streamCloser = new Thread(tg, streamCloserRunnable); - /* Set context class loader to null in order to avoid - * keeping a strong reference to an application classloader. - */ - streamCloser.setContextClassLoader(null); - Runtime.getRuntime().addShutdownHook(streamCloser); - return null; - } - }); + AccessController.doPrivileged((PrivilegedAction) () -> { + if (System.getSecurityManager() == null) { + /* The thread must be a member of a thread group + * which will not get GCed before VM exit. + * Make its parent the top-level thread group. + */ + ThreadGroup tg = ThreadGroupUtils.getRootThreadGroup(); + streamCloser = new Thread(tg, streamCloserRunnable); + } else { + /* InnocuousThread is a member of a correct TG by default */ + streamCloser = new InnocuousThread(streamCloserRunnable); + } + /* Set context class loader to null in order to avoid + * keeping a strong reference to an application classloader. + */ + streamCloser.setContextClassLoader(null); + Runtime.getRuntime().addShutdownHook(streamCloser); + return null; + }); } } } diff --git a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsDesktopManager.java b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsDesktopManager.java index 16eef680706..82708f571e5 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsDesktopManager.java +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsDesktopManager.java @@ -68,7 +68,7 @@ public class WindowsDesktopManager extends DefaultDesktopManager if (currentFrame != null && f != currentFrame) { // If the current frame is maximized, transfer that // attribute to the frame being activated. - if (currentFrame.isMaximum() && + if (!currentFrame.isClosed() && currentFrame.isMaximum() && (f.getClientProperty("JInternalFrame.frameType") != "optionDialog") ) { //Special case. If key binding was used to select next diff --git a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java index ee81a15f637..0a666b12e25 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java @@ -64,6 +64,7 @@ import sun.awt.SunToolkit; import sun.awt.OSInfo; import sun.awt.shell.ShellFolder; import sun.font.FontUtilities; +import sun.misc.ManagedLocalsThread; import sun.security.action.GetPropertyAction; import sun.swing.DefaultLayoutStyle; @@ -2037,7 +2038,11 @@ public class WindowsLookAndFeel extends BasicLookAndFeel if (audioRunnable != null) { // Runnable appears to block until completed playing, hence // start up another thread to handle playing. - new Thread(audioRunnable).start(); + if (System.getSecurityManager() == null) { + new Thread(audioRunnable).start(); + } else { + new ManagedLocalsThread(audioRunnable).start(); + } } } } diff --git a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsRootPaneUI.java b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsRootPaneUI.java index ec505959a31..347f2943155 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsRootPaneUI.java +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsRootPaneUI.java @@ -197,6 +197,10 @@ public class WindowsRootPaneUI extends BasicRootPaneUI { root = null; winAncestor = null; } else { + if (WindowsLookAndFeel.isMnemonicHidden() && ev.isAltDown()) { + WindowsLookAndFeel.setMnemonicHidden(false); + WindowsGraphicsUtils.repaintMnemonicsInWindow(winAncestor); + } altKeyPressed = false; } return false; diff --git a/jdk/src/java.desktop/share/classes/com/sun/media/sound/JSSecurityManager.java b/jdk/src/java.desktop/share/classes/com/sun/media/sound/JSSecurityManager.java index 8382f15e8c2..63eaba1c4ec 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/JSSecurityManager.java +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/JSSecurityManager.java @@ -25,6 +25,9 @@ package com.sun.media.sound; +import sun.misc.InnocuousThread; +import sun.misc.ManagedLocalsThread; + import java.io.BufferedInputStream; import java.io.InputStream; import java.io.File; @@ -144,7 +147,13 @@ final class JSSecurityManager { final String threadName, final boolean isDaemon, final int priority, final boolean doStart) { - Thread thread = new Thread(runnable); + Thread thread; + if (System.getSecurityManager() == null) { + thread = new Thread(runnable); + } else { + thread = new ManagedLocalsThread(runnable); + } + if (threadName != null) { thread.setName(threadName); } diff --git a/jdk/src/java.desktop/share/classes/com/sun/media/sound/SoftAudioPusher.java b/jdk/src/java.desktop/share/classes/com/sun/media/sound/SoftAudioPusher.java index 1a07a23ec6f..a5fdd4e9f86 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/SoftAudioPusher.java +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/SoftAudioPusher.java @@ -24,6 +24,8 @@ */ package com.sun.media.sound; +import sun.misc.ManagedLocalsThread; + import java.io.IOException; import javax.sound.sampled.AudioInputStream; @@ -53,7 +55,11 @@ public final class SoftAudioPusher implements Runnable { if (active) return; active = true; - audiothread = new Thread(this); + if (System.getSecurityManager() == null) { + audiothread = new Thread(this); + } else { + audiothread = new ManagedLocalsThread(this); + } audiothread.setDaemon(true); audiothread.setPriority(Thread.MAX_PRIORITY); audiothread.start(); diff --git a/jdk/src/java.desktop/share/classes/com/sun/media/sound/SoftJitterCorrector.java b/jdk/src/java.desktop/share/classes/com/sun/media/sound/SoftJitterCorrector.java index 0f5ff294574..85c615e1801 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/SoftJitterCorrector.java +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/SoftJitterCorrector.java @@ -24,12 +24,13 @@ */ package com.sun.media.sound; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; +import sun.misc.ManagedLocalsThread; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; /** * A jitter corrector to be used with SoftAudioPusher. @@ -215,7 +216,11 @@ public final class SoftJitterCorrector extends AudioInputStream { } }; - thread = new Thread(runnable); + if (System.getSecurityManager() == null) { + thread = new Thread(runnable); + } else { + thread = new ManagedLocalsThread(runnable); + } thread.setDaemon(true); thread.setPriority(Thread.MAX_PRIORITY); thread.start(); diff --git a/jdk/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java b/jdk/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java index e895ead074f..81c33ff788b 100644 --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java @@ -25,6 +25,8 @@ package com.sun.media.sound; +import sun.misc.ManagedLocalsThread; + import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; @@ -139,7 +141,11 @@ public final class SoftSynthesizer implements AudioSynthesizer, pusher = null; jitter_stream = null; sourceDataLine = null; - new Thread(runnable).start(); + if (System.getSecurityManager() == null) { + new Thread(runnable).start(); + } else { + new ManagedLocalsThread(runnable).start(); + } } return len; } diff --git a/jdk/src/java.desktop/share/classes/java/awt/AWTEventMulticaster.java b/jdk/src/java.desktop/share/classes/java/awt/AWTEventMulticaster.java index 01e42428a73..8297188f1f9 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/AWTEventMulticaster.java +++ b/jdk/src/java.desktop/share/classes/java/awt/AWTEventMulticaster.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1088,6 +1088,7 @@ public class AWTEventMulticaster implements * contains only the specified listener. If no such listeners are chained, * this method returns an empty array. * + * @param the listener type * @param l the specified java.util.EventListener * @param listenerType the type of listeners requested; this parameter * should specify an interface that descends from diff --git a/jdk/src/java.desktop/share/classes/java/awt/Component.java b/jdk/src/java.desktop/share/classes/java/awt/Component.java index a5e8dfee50c..72e473d8465 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/Component.java +++ b/jdk/src/java.desktop/share/classes/java/awt/Component.java @@ -4316,9 +4316,12 @@ public abstract class Component implements ImageObserver, MenuContainer, */ protected boolean validatedContents; // = false /** - * Size of the back buffers + * Width of the back buffers */ protected int width; + /** + * Height of the back buffers + */ protected int height; /** @@ -6013,6 +6016,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * * If no such listeners exist, this method returns an empty array. * + * @param the type of the listeners * @param listenerType the type of listeners requested; this parameter * should specify an interface that descends from * java.util.EventListener diff --git a/jdk/src/java.desktop/share/classes/java/awt/EventDispatchThread.java b/jdk/src/java.desktop/share/classes/java/awt/EventDispatchThread.java index 5bf91e6ab8c..dd9ea860ec2 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/EventDispatchThread.java +++ b/jdk/src/java.desktop/share/classes/java/awt/EventDispatchThread.java @@ -30,6 +30,8 @@ import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import java.util.ArrayList; + +import sun.misc.ManagedLocalsThread; import sun.util.logging.PlatformLogger; import sun.awt.dnd.SunDragSourceContextPeer; @@ -53,7 +55,7 @@ import sun.awt.dnd.SunDragSourceContextPeer; * * @since 1.1 */ -class EventDispatchThread extends Thread { +class EventDispatchThread extends ManagedLocalsThread { private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.EventDispatchThread"); @@ -65,7 +67,7 @@ class EventDispatchThread extends Thread { private ArrayList eventFilters = new ArrayList(); EventDispatchThread(ThreadGroup group, String name, EventQueue queue) { - super(group, name); + super(group, null, name); setEventQueue(queue); } diff --git a/jdk/src/java.desktop/share/classes/java/awt/GridBagLayout.java b/jdk/src/java.desktop/share/classes/java/awt/GridBagLayout.java index 1624700353f..7c86dcc1f67 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/GridBagLayout.java +++ b/jdk/src/java.desktop/share/classes/java/awt/GridBagLayout.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -353,7 +353,7 @@ import java.util.Arrays; * } * } *
                                - *

                                + * * @author Doug Stein * @author Bill Spitzak (orignial NeWS & OLIT implementation) * @see java.awt.GridBagConstraints @@ -770,7 +770,7 @@ java.io.Serializable { * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. - *

                                + * * @return the value 0.5f to indicate centered */ public float getLayoutAlignmentX(Container parent) { @@ -783,7 +783,7 @@ java.io.Serializable { * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. - *

                                + * * @return the value 0.5f to indicate centered */ public float getLayoutAlignmentY(Container parent) { diff --git a/jdk/src/java.desktop/share/classes/java/awt/MenuComponent.java b/jdk/src/java.desktop/share/classes/java/awt/MenuComponent.java index 64b1db9bf06..f9f9f28da0d 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/MenuComponent.java +++ b/jdk/src/java.desktop/share/classes/java/awt/MenuComponent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -328,6 +328,7 @@ public abstract class MenuComponent implements java.io.Serializable { * Its use is discouraged, and it may not be supported * in the future. * @param evt the event which is to take place + * @return unconditionally returns false * @deprecated As of JDK version 1.1, replaced by {@link * #dispatchEvent(AWTEvent) dispatchEvent}. */ diff --git a/jdk/src/java.desktop/share/classes/java/awt/MenuContainer.java b/jdk/src/java.desktop/share/classes/java/awt/MenuContainer.java index 8ba5e70245b..995c7d4ceb6 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/MenuContainer.java +++ b/jdk/src/java.desktop/share/classes/java/awt/MenuContainer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -50,6 +50,7 @@ public interface MenuContainer { * Posts an event to the listeners. * * @param evt the event to dispatch + * @return the results of posting the event * @deprecated As of JDK version 1.1 * replaced by dispatchEvent(AWTEvent). */ diff --git a/jdk/src/java.desktop/share/classes/java/awt/MenuItem.java b/jdk/src/java.desktop/share/classes/java/awt/MenuItem.java index ab797f4dd1a..e70ec305cdf 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/MenuItem.java +++ b/jdk/src/java.desktop/share/classes/java/awt/MenuItem.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -595,6 +595,7 @@ public class MenuItem extends MenuComponent implements Accessible { * * If no such listeners exist, this method returns an empty array. * + * @param the type of the listeners * @param listenerType the type of listeners requested; this parameter * should specify an interface that descends from * java.util.EventListener diff --git a/jdk/src/java.desktop/share/classes/java/awt/Toolkit.java b/jdk/src/java.desktop/share/classes/java/awt/Toolkit.java index 985c946f422..9b3ad9b5777 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/Toolkit.java +++ b/jdk/src/java.desktop/share/classes/java/awt/Toolkit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1766,6 +1766,7 @@ public abstract class Toolkit { * * subclasses should override this to provide their own implementation * + * @param the type of DragGestureRecognizer to create * @param abstractRecognizerClass The abstract class of the required recognizer * @param ds The DragSource * @param c The Component target for the DragGestureRecognizer @@ -1867,7 +1868,9 @@ public abstract class Toolkit { } /** - * an opportunity to lazily evaluate desktop property values. + * An opportunity to lazily evaluate desktop property values. + * @return the desktop property or null + * @param name the name */ protected Object lazilyLoadDesktopProperty(String name) { return null; @@ -1947,8 +1950,14 @@ public abstract class Toolkit { return desktopPropsSupport.getPropertyChangeListeners(propertyName); } + /** + * The desktop properties. + */ protected final Map desktopProperties = new HashMap(); + /** + * The desktop properties change support. + */ protected final PropertyChangeSupport desktopPropsSupport = Toolkit.createPropertyChangeSupport(this); diff --git a/jdk/src/java.desktop/share/classes/java/awt/Window.java b/jdk/src/java.desktop/share/classes/java/awt/Window.java index 5f819cda87a..56ca461a90b 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/Window.java +++ b/jdk/src/java.desktop/share/classes/java/awt/Window.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -2789,6 +2789,7 @@ public class Window extends Container implements Accessible { /** * @deprecated As of J2SE 1.4, replaced by * {@link Component#applyComponentOrientation Component.applyComponentOrientation}. + * @param rb the resource bundle */ @Deprecated public void applyResourceBundle(ResourceBundle rb) { @@ -2798,6 +2799,7 @@ public class Window extends Container implements Accessible { /** * @deprecated As of J2SE 1.4, replaced by * {@link Component#applyComponentOrientation Component.applyComponentOrientation}. + * @param rbName the resource name */ @Deprecated public void applyResourceBundle(String rbName) { diff --git a/jdk/src/java.desktop/share/classes/java/awt/doc-files/Modality.html b/jdk/src/java.desktop/share/classes/java/awt/doc-files/Modality.html index 19695f00177..242e96b914f 100644 --- a/jdk/src/java.desktop/share/classes/java/awt/doc-files/Modality.html +++ b/jdk/src/java.desktop/share/classes/java/awt/doc-files/Modality.html @@ -1,5 +1,5 @@ RGB case. * @@ -1426,23 +1462,23 @@ png_init_read_transformations(png_structp png_ptr) * png_set_background, along with the bit depth, then the code has a record * of exactly what color space the background is currently in. */ - if (png_ptr->transformations & PNG_BACKGROUND_EXPAND) + if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) != 0) { /* PNG_BACKGROUND_EXPAND: the background is in the file color space, so if - * the file was greyscale the background value is gray. + * the file was grayscale the background value is gray. */ - if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) + if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) png_ptr->mode |= PNG_BACKGROUND_IS_GRAY; } - else if (png_ptr->transformations & PNG_COMPOSE) + else if ((png_ptr->transformations & PNG_COMPOSE) != 0) { /* PNG_COMPOSE: png_set_background was called with need_expand false, * so the color is in the color space of the output or png_set_alpha_mode * was called and the color is black. Ignore RGB_TO_GRAY because that * happens before GRAY_TO_RGB. */ - if (png_ptr->transformations & PNG_GRAY_TO_RGB) + if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0) { if (png_ptr->background.red == png_ptr->background.green && png_ptr->background.red == png_ptr->background.blue) @@ -1452,7 +1488,8 @@ png_init_read_transformations(png_structp png_ptr) } } } -#endif /* PNG_READ_GRAY_TO_RGB_SUPPORTED (etc) */ +#endif /* READ_EXPAND && READ_BACKGROUND */ +#endif /* READ_GRAY_TO_RGB */ /* For indexed PNG data (PNG_COLOR_TYPE_PALETTE) many of the transformations * can be performed directly on the palette, and some (such as rgb to gray) @@ -1473,10 +1510,10 @@ png_init_read_transformations(png_structp png_ptr) #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \ defined(PNG_READ_EXPAND_16_SUPPORTED) - if ((png_ptr->transformations & PNG_EXPAND_16) && - (png_ptr->transformations & PNG_COMPOSE) && - !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) && - png_ptr->bit_depth != 16) + if ((png_ptr->transformations & PNG_EXPAND_16) != 0 && + (png_ptr->transformations & PNG_COMPOSE) != 0 && + (png_ptr->transformations & PNG_BACKGROUND_EXPAND) == 0 && + png_ptr->bit_depth != 16) { /* TODO: fix this. Because the expand_16 operation is after the compose * handling the background color must be 8, not 16, bits deep, but the @@ -1488,14 +1525,36 @@ png_init_read_transformations(png_structp png_ptr) * NOTE: this discards the low 16 bits of the user supplied background * color, but until expand_16 works properly there is no choice! */ -# define CHOP(x) (x)=((png_uint_16)(((png_uint_32)(x)*255+32895) >> 16)) +# define CHOP(x) (x)=((png_uint_16)PNG_DIV257(x)) CHOP(png_ptr->background.red); CHOP(png_ptr->background.green); CHOP(png_ptr->background.blue); CHOP(png_ptr->background.gray); # undef CHOP } -#endif /* PNG_READ_BACKGROUND_SUPPORTED && PNG_READ_EXPAND_16_SUPPORTED */ +#endif /* READ_BACKGROUND && READ_EXPAND_16 */ + +#if defined(PNG_READ_BACKGROUND_SUPPORTED) && \ + (defined(PNG_READ_SCALE_16_TO_8_SUPPORTED) || \ + defined(PNG_READ_STRIP_16_TO_8_SUPPORTED)) + if ((png_ptr->transformations & (PNG_16_TO_8|PNG_SCALE_16_TO_8)) != 0 && + (png_ptr->transformations & PNG_COMPOSE) != 0 && + (png_ptr->transformations & PNG_BACKGROUND_EXPAND) == 0 && + png_ptr->bit_depth == 16) + { + /* On the other hand, if a 16-bit file is to be reduced to 8-bits per + * component this will also happen after PNG_COMPOSE and so the background + * color must be pre-expanded here. + * + * TODO: fix this too. + */ + png_ptr->background.red = (png_uint_16)(png_ptr->background.red * 257); + png_ptr->background.green = + (png_uint_16)(png_ptr->background.green * 257); + png_ptr->background.blue = (png_uint_16)(png_ptr->background.blue * 257); + png_ptr->background.gray = (png_uint_16)(png_ptr->background.gray * 257); + } +#endif /* NOTE: below 'PNG_READ_ALPHA_MODE_SUPPORTED' is presumed to also enable the * background support (see the comments in scripts/pnglibconf.dfa), this @@ -1524,27 +1583,36 @@ png_init_read_transformations(png_structp png_ptr) * file gamma - if it is not 1.0 both RGB_TO_GRAY and COMPOSE need the * tables. */ - if ((png_ptr->transformations & PNG_GAMMA) - || ((png_ptr->transformations & PNG_RGB_TO_GRAY) - && (png_gamma_significant(png_ptr->gamma) || - png_gamma_significant(png_ptr->screen_gamma))) - || ((png_ptr->transformations & PNG_COMPOSE) - && (png_gamma_significant(png_ptr->gamma) - || png_gamma_significant(png_ptr->screen_gamma) + if ((png_ptr->transformations & PNG_GAMMA) != 0 || + ((png_ptr->transformations & PNG_RGB_TO_GRAY) != 0 && + (png_gamma_significant(png_ptr->colorspace.gamma) != 0 || + png_gamma_significant(png_ptr->screen_gamma) != 0)) || + ((png_ptr->transformations & PNG_COMPOSE) != 0 && + (png_gamma_significant(png_ptr->colorspace.gamma) != 0 || + png_gamma_significant(png_ptr->screen_gamma) != 0 # ifdef PNG_READ_BACKGROUND_SUPPORTED - || (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_UNIQUE - && png_gamma_significant(png_ptr->background_gamma)) + || (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_UNIQUE && + png_gamma_significant(png_ptr->background_gamma) != 0) # endif - )) || ((png_ptr->transformations & PNG_ENCODE_ALPHA) - && png_gamma_significant(png_ptr->screen_gamma)) - ) + )) || ((png_ptr->transformations & PNG_ENCODE_ALPHA) != 0 && + png_gamma_significant(png_ptr->screen_gamma) != 0)) { png_build_gamma_table(png_ptr, png_ptr->bit_depth); #ifdef PNG_READ_BACKGROUND_SUPPORTED - if (png_ptr->transformations & PNG_COMPOSE) + if ((png_ptr->transformations & PNG_COMPOSE) != 0) { - if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + /* Issue a warning about this combination: because RGB_TO_GRAY is + * optimized to do the gamma transform if present yet do_background has + * to do the same thing if both options are set a + * double-gamma-correction happens. This is true in all versions of + * libpng to date. + */ + if ((png_ptr->transformations & PNG_RGB_TO_GRAY) != 0) + png_warning(png_ptr, + "libpng does not support gamma+background+rgb_to_gray"); + + if ((png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) != 0) { /* We don't get to here unless there is a tRNS chunk with non-opaque * entries - see the checking code at the start of this function. @@ -1576,8 +1644,8 @@ png_init_read_transformations(png_structp png_ptr) break; case PNG_BACKGROUND_GAMMA_FILE: - g = png_reciprocal(png_ptr->gamma); - gs = png_reciprocal2(png_ptr->gamma, + g = png_reciprocal(png_ptr->colorspace.gamma); + gs = png_reciprocal2(png_ptr->colorspace.gamma, png_ptr->screen_gamma); break; @@ -1592,7 +1660,7 @@ png_init_read_transformations(png_structp png_ptr) break; } - if (png_gamma_significant(gs)) + if (png_gamma_significant(gs) != 0) { back.red = png_gamma_8bit_correct(png_ptr->background.red, gs); @@ -1609,7 +1677,7 @@ png_init_read_transformations(png_structp png_ptr) back.blue = (png_byte)png_ptr->background.blue; } - if (png_gamma_significant(g)) + if (png_gamma_significant(g) != 0) { back_1.red = png_gamma_8bit_correct(png_ptr->background.red, g); @@ -1663,7 +1731,7 @@ png_init_read_transformations(png_structp png_ptr) /* Prevent the transformations being done again. * - * NOTE: this is highly dubious; it zaps the transformations in + * NOTE: this is highly dubious; it removes the transformations in * place. This seems inconsistent with the general treatment of the * transformations elsewhere. */ @@ -1673,8 +1741,9 @@ png_init_read_transformations(png_structp png_ptr) /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */ else /* color_type != PNG_COLOR_TYPE_PALETTE */ { - png_fixed_point g = PNG_FP_1; - png_fixed_point gs = PNG_FP_1; + int gs_sig, g_sig; + png_fixed_point g = PNG_FP_1; /* Correction to linear */ + png_fixed_point gs = PNG_FP_1; /* Correction to screen */ switch (png_ptr->background_gamma_type) { @@ -1684,8 +1753,9 @@ png_init_read_transformations(png_structp png_ptr) break; case PNG_BACKGROUND_GAMMA_FILE: - g = png_reciprocal(png_ptr->gamma); - gs = png_reciprocal2(png_ptr->gamma, png_ptr->screen_gamma); + g = png_reciprocal(png_ptr->colorspace.gamma); + gs = png_reciprocal2(png_ptr->colorspace.gamma, + png_ptr->screen_gamma); break; case PNG_BACKGROUND_GAMMA_UNIQUE: @@ -1698,34 +1768,45 @@ png_init_read_transformations(png_structp png_ptr) png_error(png_ptr, "invalid background gamma type"); } - png_ptr->background_1.gray = png_gamma_correct(png_ptr, - png_ptr->background.gray, g); + g_sig = png_gamma_significant(g); + gs_sig = png_gamma_significant(gs); - png_ptr->background.gray = png_gamma_correct(png_ptr, - png_ptr->background.gray, gs); + if (g_sig != 0) + png_ptr->background_1.gray = png_gamma_correct(png_ptr, + png_ptr->background.gray, g); + + if (gs_sig != 0) + png_ptr->background.gray = png_gamma_correct(png_ptr, + png_ptr->background.gray, gs); if ((png_ptr->background.red != png_ptr->background.green) || (png_ptr->background.red != png_ptr->background.blue) || (png_ptr->background.red != png_ptr->background.gray)) { /* RGB or RGBA with color background */ - png_ptr->background_1.red = png_gamma_correct(png_ptr, - png_ptr->background.red, g); + if (g_sig != 0) + { + png_ptr->background_1.red = png_gamma_correct(png_ptr, + png_ptr->background.red, g); - png_ptr->background_1.green = png_gamma_correct(png_ptr, - png_ptr->background.green, g); + png_ptr->background_1.green = png_gamma_correct(png_ptr, + png_ptr->background.green, g); - png_ptr->background_1.blue = png_gamma_correct(png_ptr, - png_ptr->background.blue, g); + png_ptr->background_1.blue = png_gamma_correct(png_ptr, + png_ptr->background.blue, g); + } - png_ptr->background.red = png_gamma_correct(png_ptr, - png_ptr->background.red, gs); + if (gs_sig != 0) + { + png_ptr->background.red = png_gamma_correct(png_ptr, + png_ptr->background.red, gs); - png_ptr->background.green = png_gamma_correct(png_ptr, - png_ptr->background.green, gs); + png_ptr->background.green = png_gamma_correct(png_ptr, + png_ptr->background.green, gs); - png_ptr->background.blue = png_gamma_correct(png_ptr, - png_ptr->background.blue, gs); + png_ptr->background.blue = png_gamma_correct(png_ptr, + png_ptr->background.blue, gs); + } } else @@ -1737,20 +1818,29 @@ png_init_read_transformations(png_structp png_ptr) png_ptr->background.red = png_ptr->background.green = png_ptr->background.blue = png_ptr->background.gray; } + + /* The background is now in screen gamma: */ + png_ptr->background_gamma_type = PNG_BACKGROUND_GAMMA_SCREEN; } /* color_type != PNG_COLOR_TYPE_PALETTE */ }/* png_ptr->transformations & PNG_BACKGROUND */ else /* Transformation does not include PNG_BACKGROUND */ -#endif /* PNG_READ_BACKGROUND_SUPPORTED */ - if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) +#endif /* READ_BACKGROUND */ + if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE +#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED + /* RGB_TO_GRAY needs to have non-gamma-corrected values! */ + && ((png_ptr->transformations & PNG_EXPAND) == 0 || + (png_ptr->transformations & PNG_RGB_TO_GRAY) == 0) +#endif + ) { png_colorp palette = png_ptr->palette; int num_palette = png_ptr->num_palette; int i; - /*NOTE: there are other transformations that should probably be in here - * too. + /* NOTE: there are other transformations that should probably be in + * here too. */ for (i = 0; i < num_palette; i++) { @@ -1766,11 +1856,11 @@ png_init_read_transformations(png_structp png_ptr) #ifdef PNG_READ_BACKGROUND_SUPPORTED else #endif -#endif /* PNG_READ_GAMMA_SUPPORTED */ +#endif /* READ_GAMMA */ #ifdef PNG_READ_BACKGROUND_SUPPORTED /* No GAMMA transformation (see the hanging else 4 lines above) */ - if ((png_ptr->transformations & PNG_COMPOSE) && + if ((png_ptr->transformations & PNG_COMPOSE) != 0 && (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)) { int i; @@ -1805,35 +1895,53 @@ png_init_read_transformations(png_structp png_ptr) png_ptr->transformations &= ~PNG_COMPOSE; } -#endif /* PNG_READ_BACKGROUND_SUPPORTED */ +#endif /* READ_BACKGROUND */ #ifdef PNG_READ_SHIFT_SUPPORTED - if ((png_ptr->transformations & PNG_SHIFT) && + if ((png_ptr->transformations & PNG_SHIFT) != 0 && + (png_ptr->transformations & PNG_EXPAND) == 0 && (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)) { - png_uint_16 i; - png_uint_16 istop = png_ptr->num_palette; - int sr = 8 - png_ptr->sig_bit.red; - int sg = 8 - png_ptr->sig_bit.green; - int sb = 8 - png_ptr->sig_bit.blue; + int i; + int istop = png_ptr->num_palette; + int shift = 8 - png_ptr->sig_bit.red; - if (sr < 0 || sr > 8) - sr = 0; + png_ptr->transformations &= ~PNG_SHIFT; - if (sg < 0 || sg > 8) - sg = 0; + /* significant bits can be in the range 1 to 7 for a meaninful result, if + * the number of significant bits is 0 then no shift is done (this is an + * error condition which is silently ignored.) + */ + if (shift > 0 && shift < 8) + for (i=0; ipalette[i].red; - if (sb < 0 || sb > 8) - sb = 0; + component >>= shift; + png_ptr->palette[i].red = (png_byte)component; + } - for (i = 0; i < istop; i++) - { - png_ptr->palette[i].red >>= sr; - png_ptr->palette[i].green >>= sg; - png_ptr->palette[i].blue >>= sb; - } + shift = 8 - png_ptr->sig_bit.green; + if (shift > 0 && shift < 8) + for (i=0; ipalette[i].green; + + component >>= shift; + png_ptr->palette[i].green = (png_byte)component; + } + + shift = 8 - png_ptr->sig_bit.blue; + if (shift > 0 && shift < 8) + for (i=0; ipalette[i].blue; + + component >>= shift; + png_ptr->palette[i].blue = (png_byte)component; + } } -#endif /* PNG_READ_SHIFT_SUPPORTED */ +#endif /* READ_SHIFT */ } /* Modify the info structure to reflect the transformations. The @@ -1841,12 +1949,12 @@ png_init_read_transformations(png_structp png_ptr) * assuming the transformations result in valid PNG data. */ void /* PRIVATE */ -png_read_transform_info(png_structp png_ptr, png_infop info_ptr) +png_read_transform_info(png_structrp png_ptr, png_inforp info_ptr) { png_debug(1, "in png_read_transform_info"); #ifdef PNG_READ_EXPAND_SUPPORTED - if (png_ptr->transformations & PNG_EXPAND) + if ((png_ptr->transformations & PNG_EXPAND) != 0) { if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { @@ -1868,9 +1976,9 @@ png_read_transform_info(png_structp png_ptr, png_infop info_ptr) } else { - if (png_ptr->num_trans) + if (png_ptr->num_trans != 0) { - if (png_ptr->transformations & PNG_EXPAND_tRNS) + if ((png_ptr->transformations & PNG_EXPAND_tRNS) != 0) info_ptr->color_type |= PNG_COLOR_MASK_ALPHA; } if (info_ptr->bit_depth < 8) @@ -1886,7 +1994,7 @@ png_read_transform_info(png_structp png_ptr, png_infop info_ptr) /* The following is almost certainly wrong unless the background value is in * the screen space! */ - if (png_ptr->transformations & PNG_COMPOSE) + if ((png_ptr->transformations & PNG_COMPOSE) != 0) info_ptr->background = png_ptr->background; #endif @@ -1895,20 +2003,24 @@ png_read_transform_info(png_structp png_ptr, png_infop info_ptr) * however it seems that the code in png_init_read_transformations, which has * been called before this from png_read_update_info->png_read_start_row * sometimes does the gamma transform and cancels the flag. + * + * TODO: this looks wrong; the info_ptr should end up with a gamma equal to + * the screen_gamma value. The following probably results in weirdness if + * the info_ptr is used by the app after the rows have been read. */ - info_ptr->gamma = png_ptr->gamma; + info_ptr->colorspace.gamma = png_ptr->colorspace.gamma; #endif if (info_ptr->bit_depth == 16) { # ifdef PNG_READ_16BIT_SUPPORTED # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED - if (png_ptr->transformations & PNG_SCALE_16_TO_8) + if ((png_ptr->transformations & PNG_SCALE_16_TO_8) != 0) info_ptr->bit_depth = 8; # endif # ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED - if (png_ptr->transformations & PNG_16_TO_8) + if ((png_ptr->transformations & PNG_16_TO_8) != 0) info_ptr->bit_depth = 8; # endif @@ -1926,7 +2038,7 @@ png_read_transform_info(png_structp png_ptr, png_infop info_ptr) info_ptr->bit_depth = 8; # else -# if PNG_READ_SCALE_16_TO_8_SUPPORTED +# ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED png_ptr->transformations |= PNG_SCALE_16_TO_8; info_ptr->bit_depth = 8; # else @@ -1934,25 +2046,27 @@ png_read_transform_info(png_structp png_ptr, png_infop info_ptr) CONFIGURATION ERROR: you must enable at least one 16 to 8 method # endif # endif -#endif /* !READ_16BIT_SUPPORTED */ +#endif /* !READ_16BIT */ } #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED - if (png_ptr->transformations & PNG_GRAY_TO_RGB) - info_ptr->color_type |= PNG_COLOR_MASK_COLOR; + if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0) + info_ptr->color_type = (png_byte)(info_ptr->color_type | + PNG_COLOR_MASK_COLOR); #endif #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED - if (png_ptr->transformations & PNG_RGB_TO_GRAY) - info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR; + if ((png_ptr->transformations & PNG_RGB_TO_GRAY) != 0) + info_ptr->color_type = (png_byte)(info_ptr->color_type & + ~PNG_COLOR_MASK_COLOR); #endif #ifdef PNG_READ_QUANTIZE_SUPPORTED - if (png_ptr->transformations & PNG_QUANTIZE) + if ((png_ptr->transformations & PNG_QUANTIZE) != 0) { if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) || (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) && - png_ptr->palette_lookup && info_ptr->bit_depth == 8) + png_ptr->palette_lookup != 0 && info_ptr->bit_depth == 8) { info_ptr->color_type = PNG_COLOR_TYPE_PALETTE; } @@ -1960,54 +2074,57 @@ png_read_transform_info(png_structp png_ptr, png_infop info_ptr) #endif #ifdef PNG_READ_EXPAND_16_SUPPORTED - if (png_ptr->transformations & PNG_EXPAND_16 && info_ptr->bit_depth == 8 && - info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) + if ((png_ptr->transformations & PNG_EXPAND_16) != 0 && + info_ptr->bit_depth == 8 && + info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) { info_ptr->bit_depth = 16; } #endif #ifdef PNG_READ_PACK_SUPPORTED - if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8)) + if ((png_ptr->transformations & PNG_PACK) != 0 && + (info_ptr->bit_depth < 8)) info_ptr->bit_depth = 8; #endif if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) info_ptr->channels = 1; - else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) + else if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0) info_ptr->channels = 3; else info_ptr->channels = 1; #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED - if (png_ptr->transformations & PNG_STRIP_ALPHA) + if ((png_ptr->transformations & PNG_STRIP_ALPHA) != 0) { - info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA; + info_ptr->color_type = (png_byte)(info_ptr->color_type & + ~PNG_COLOR_MASK_ALPHA); info_ptr->num_trans = 0; } #endif - if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA) + if ((info_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0) info_ptr->channels++; #ifdef PNG_READ_FILLER_SUPPORTED /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */ - if ((png_ptr->transformations & PNG_FILLER) && - ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) || - (info_ptr->color_type == PNG_COLOR_TYPE_GRAY))) + if ((png_ptr->transformations & PNG_FILLER) != 0 && + (info_ptr->color_type == PNG_COLOR_TYPE_RGB || + info_ptr->color_type == PNG_COLOR_TYPE_GRAY)) { info_ptr->channels++; /* If adding a true alpha channel not just filler */ - if (png_ptr->transformations & PNG_ADD_ALPHA) + if ((png_ptr->transformations & PNG_ADD_ALPHA) != 0) info_ptr->color_type |= PNG_COLOR_MASK_ALPHA; } #endif #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \ defined(PNG_READ_USER_TRANSFORM_SUPPORTED) - if (png_ptr->transformations & PNG_USER_TRANSFORM) + if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0) { if (info_ptr->bit_depth < png_ptr->user_transform_depth) info_ptr->bit_depth = png_ptr->user_transform_depth; @@ -2031,291 +2148,11 @@ defined(PNG_READ_USER_TRANSFORM_SUPPORTED) png_ptr->info_rowbytes = info_ptr->rowbytes; #ifndef PNG_READ_EXPAND_SUPPORTED - if (png_ptr) + if (png_ptr != NULL) return; #endif } -/* Transform the row. The order of transformations is significant, - * and is very touchy. If you add a transformation, take care to - * decide how it fits in with the other transformations here. - */ -void /* PRIVATE */ -png_do_read_transformations(png_structp png_ptr) -{ - png_debug(1, "in png_do_read_transformations"); - - if (png_ptr->row_buf == NULL) - { - /* Prior to 1.5.4 this output row/pass where the NULL pointer is, but this - * error is incredibly rare and incredibly easy to debug without this - * information. - */ - png_error(png_ptr, "NULL row buffer"); - } - - /* The following is debugging; prior to 1.5.4 the code was never compiled in; - * in 1.5.4 PNG_FLAG_DETECT_UNINITIALIZED was added and the macro - * PNG_WARN_UNINITIALIZED_ROW removed. In 1.5 the new flag is set only for - * selected new APIs to ensure that there is no API change. - */ - if ((png_ptr->flags & PNG_FLAG_DETECT_UNINITIALIZED) != 0 && - !(png_ptr->flags & PNG_FLAG_ROW_INIT)) - { - /* Application has failed to call either png_read_start_image() or - * png_read_update_info() after setting transforms that expand pixels. - * This check added to libpng-1.2.19 (but not enabled until 1.5.4). - */ - png_error(png_ptr, "Uninitialized row"); - } - -#ifdef PNG_READ_EXPAND_SUPPORTED - if (png_ptr->transformations & PNG_EXPAND) - { - if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE) - { - png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1, - png_ptr->palette, png_ptr->trans_alpha, png_ptr->num_trans); - } - - else - { - if (png_ptr->num_trans && - (png_ptr->transformations & PNG_EXPAND_tRNS)) - png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1, - &(png_ptr->trans_color)); - - else - png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1, - NULL); - } - } -#endif - -#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED - if ((png_ptr->transformations & PNG_STRIP_ALPHA) && - !(png_ptr->transformations & PNG_COMPOSE) && - (png_ptr->row_info.color_type == PNG_COLOR_TYPE_RGB_ALPHA || - png_ptr->row_info.color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) - png_do_strip_channel(&(png_ptr->row_info), png_ptr->row_buf + 1, - 0 /* at_start == false, because SWAP_ALPHA happens later */); -#endif - -#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED - if (png_ptr->transformations & PNG_RGB_TO_GRAY) - { - int rgb_error = - png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), - png_ptr->row_buf + 1); - - if (rgb_error) - { - png_ptr->rgb_to_gray_status=1; - if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == - PNG_RGB_TO_GRAY_WARN) - png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel"); - - if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == - PNG_RGB_TO_GRAY_ERR) - png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel"); - } - } -#endif - -/* From Andreas Dilger e-mail to png-implement, 26 March 1998: - * - * In most cases, the "simple transparency" should be done prior to doing - * gray-to-RGB, or you will have to test 3x as many bytes to check if a - * pixel is transparent. You would also need to make sure that the - * transparency information is upgraded to RGB. - * - * To summarize, the current flow is: - * - Gray + simple transparency -> compare 1 or 2 gray bytes and composite - * with background "in place" if transparent, - * convert to RGB if necessary - * - Gray + alpha -> composite with gray background and remove alpha bytes, - * convert to RGB if necessary - * - * To support RGB backgrounds for gray images we need: - * - Gray + simple transparency -> convert to RGB + simple transparency, - * compare 3 or 6 bytes and composite with - * background "in place" if transparent - * (3x compare/pixel compared to doing - * composite with gray bkgrnd) - * - Gray + alpha -> convert to RGB + alpha, composite with background and - * remove alpha bytes (3x float - * operations/pixel compared with composite - * on gray background) - * - * Greg's change will do this. The reason it wasn't done before is for - * performance, as this increases the per-pixel operations. If we would check - * in advance if the background was gray or RGB, and position the gray-to-RGB - * transform appropriately, then it would save a lot of work/time. - */ - -#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED - /* If gray -> RGB, do so now only if background is non-gray; else do later - * for performance reasons - */ - if ((png_ptr->transformations & PNG_GRAY_TO_RGB) && - !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY)) - png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#if (defined PNG_READ_BACKGROUND_SUPPORTED) ||\ - (defined PNG_READ_ALPHA_MODE_SUPPORTED) - if (png_ptr->transformations & PNG_COMPOSE) - png_do_compose(&(png_ptr->row_info), png_ptr->row_buf + 1, png_ptr); -#endif - -#ifdef PNG_READ_GAMMA_SUPPORTED - if ((png_ptr->transformations & PNG_GAMMA) && -#if (defined PNG_READ_BACKGROUND_SUPPORTED) ||\ - (defined PNG_READ_ALPHA_MODE_SUPPORTED) - !((png_ptr->transformations & PNG_COMPOSE) && - ((png_ptr->num_trans != 0) || - (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) && -#endif - (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)) - png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1, png_ptr); -#endif - -#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED - if ((png_ptr->transformations & PNG_STRIP_ALPHA) && - (png_ptr->transformations & PNG_COMPOSE) && - (png_ptr->row_info.color_type == PNG_COLOR_TYPE_RGB_ALPHA || - png_ptr->row_info.color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) - png_do_strip_channel(&(png_ptr->row_info), png_ptr->row_buf + 1, - 0 /* at_start == false, because SWAP_ALPHA happens later */); -#endif - -#ifdef PNG_READ_ALPHA_MODE_SUPPORTED - if ((png_ptr->transformations & PNG_ENCODE_ALPHA) && - (png_ptr->row_info.color_type & PNG_COLOR_MASK_ALPHA)) - png_do_encode_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1, png_ptr); -#endif - -#ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED - if (png_ptr->transformations & PNG_SCALE_16_TO_8) - png_do_scale_16_to_8(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED - /* There is no harm in doing both of these because only one has any effect, - * by putting the 'scale' option first if the app asks for scale (either by - * calling the API or in a TRANSFORM flag) this is what happens. - */ - if (png_ptr->transformations & PNG_16_TO_8) - png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_READ_QUANTIZE_SUPPORTED - if (png_ptr->transformations & PNG_QUANTIZE) - { - png_do_quantize(&(png_ptr->row_info), png_ptr->row_buf + 1, - png_ptr->palette_lookup, png_ptr->quantize_index); - - if (png_ptr->row_info.rowbytes == 0) - png_error(png_ptr, "png_do_quantize returned rowbytes=0"); - } -#endif /* PNG_READ_QUANTIZE_SUPPORTED */ - -#ifdef PNG_READ_EXPAND_16_SUPPORTED - /* Do the expansion now, after all the arithmetic has been done. Notice - * that previous transformations can handle the PNG_EXPAND_16 flag if this - * is efficient (particularly true in the case of gamma correction, where - * better accuracy results faster!) - */ - if (png_ptr->transformations & PNG_EXPAND_16) - png_do_expand_16(&png_ptr->row_info, png_ptr->row_buf + 1); -#endif - -#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED - /*NOTE: moved here in 1.5.4 (from much later in this list.) */ - if ((png_ptr->transformations & PNG_GRAY_TO_RGB) && - (png_ptr->mode & PNG_BACKGROUND_IS_GRAY)) - png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_READ_INVERT_SUPPORTED - if (png_ptr->transformations & PNG_INVERT_MONO) - png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_READ_SHIFT_SUPPORTED - if (png_ptr->transformations & PNG_SHIFT) - png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1, - &(png_ptr->shift)); -#endif - -#ifdef PNG_READ_PACK_SUPPORTED - if (png_ptr->transformations & PNG_PACK) - png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_READ_BGR_SUPPORTED - if (png_ptr->transformations & PNG_BGR) - png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_READ_PACKSWAP_SUPPORTED - if (png_ptr->transformations & PNG_PACKSWAP) - png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_READ_FILLER_SUPPORTED - if (png_ptr->transformations & PNG_FILLER) - png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1, - (png_uint_32)png_ptr->filler, png_ptr->flags); -#endif - -#ifdef PNG_READ_INVERT_ALPHA_SUPPORTED - if (png_ptr->transformations & PNG_INVERT_ALPHA) - png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_READ_SWAP_ALPHA_SUPPORTED - if (png_ptr->transformations & PNG_SWAP_ALPHA) - png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_READ_16BIT_SUPPORTED -#ifdef PNG_READ_SWAP_SUPPORTED - if (png_ptr->transformations & PNG_SWAP_BYTES) - png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif -#endif - -#ifdef PNG_READ_USER_TRANSFORM_SUPPORTED - if (png_ptr->transformations & PNG_USER_TRANSFORM) - { - if (png_ptr->read_user_transform_fn != NULL) - (*(png_ptr->read_user_transform_fn)) /* User read transform function */ - (png_ptr, /* png_ptr */ - &(png_ptr->row_info), /* row_info: */ - /* png_uint_32 width; width of row */ - /* png_size_t rowbytes; number of bytes in row */ - /* png_byte color_type; color type of pixels */ - /* png_byte bit_depth; bit depth of samples */ - /* png_byte channels; number of channels (1-4) */ - /* png_byte pixel_depth; bits per pixel (depth*channels) */ - png_ptr->row_buf + 1); /* start of pixel data for row */ -#ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED - if (png_ptr->user_transform_depth) - png_ptr->row_info.bit_depth = png_ptr->user_transform_depth; - - if (png_ptr->user_transform_channels) - png_ptr->row_info.channels = png_ptr->user_transform_channels; -#endif - png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth * - png_ptr->row_info.channels); - - png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth, - png_ptr->row_info.width); - } -#endif -} - #ifdef PNG_READ_PACK_SUPPORTED /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel, * without changing the actual values. Thus, if you had a row with @@ -2323,7 +2160,7 @@ png_do_read_transformations(png_structp png_ptr) * the numbers 0 or 1. If you would rather they contain 0 and 255, use * png_do_shift() after this. */ -void /* PRIVATE */ +static void png_do_unpack(png_row_infop row_info, png_bytep row) { png_debug(1, "in png_do_unpack"); @@ -2421,109 +2258,132 @@ png_do_unpack(png_row_infop row_info, png_bytep row) * a row of bit depth 8, but only 5 are significant, this will shift * the values back to 0 through 31. */ -void /* PRIVATE */ +static void png_do_unshift(png_row_infop row_info, png_bytep row, png_const_color_8p sig_bits) { + int color_type; + png_debug(1, "in png_do_unshift"); - if ( - row_info->color_type != PNG_COLOR_TYPE_PALETTE) + /* The palette case has already been handled in the _init routine. */ + color_type = row_info->color_type; + + if (color_type != PNG_COLOR_TYPE_PALETTE) { int shift[4]; int channels = 0; - int c; - png_uint_16 value = 0; - png_uint_32 row_width = row_info->width; + int bit_depth = row_info->bit_depth; - if (row_info->color_type & PNG_COLOR_MASK_COLOR) + if ((color_type & PNG_COLOR_MASK_COLOR) != 0) { - shift[channels++] = row_info->bit_depth - sig_bits->red; - shift[channels++] = row_info->bit_depth - sig_bits->green; - shift[channels++] = row_info->bit_depth - sig_bits->blue; + shift[channels++] = bit_depth - sig_bits->red; + shift[channels++] = bit_depth - sig_bits->green; + shift[channels++] = bit_depth - sig_bits->blue; } else { - shift[channels++] = row_info->bit_depth - sig_bits->gray; + shift[channels++] = bit_depth - sig_bits->gray; } - if (row_info->color_type & PNG_COLOR_MASK_ALPHA) + if ((color_type & PNG_COLOR_MASK_ALPHA) != 0) { - shift[channels++] = row_info->bit_depth - sig_bits->alpha; + shift[channels++] = bit_depth - sig_bits->alpha; } - for (c = 0; c < channels; c++) { - if (shift[c] <= 0) - shift[c] = 0; + int c, have_shift; - else - value = 1; + for (c = have_shift = 0; c < channels; ++c) + { + /* A shift of more than the bit depth is an error condition but it + * gets ignored here. + */ + if (shift[c] <= 0 || shift[c] >= bit_depth) + shift[c] = 0; + + else + have_shift = 1; + } + + if (have_shift == 0) + return; } - if (!value) - return; - - switch (row_info->bit_depth) + switch (bit_depth) { default: + /* Must be 1bpp gray: should not be here! */ + /* NOTREACHED */ break; case 2: + /* Must be 2bpp gray */ + /* assert(channels == 1 && shift[0] == 1) */ { - png_bytep bp; - png_size_t i; - png_size_t istop = row_info->rowbytes; + png_bytep bp = row; + png_bytep bp_end = bp + row_info->rowbytes; - for (bp = row, i = 0; i < istop; i++) + while (bp < bp_end) { - *bp >>= 1; - *bp++ &= 0x55; + int b = (*bp >> 1) & 0x55; + *bp++ = (png_byte)b; } break; } case 4: + /* Must be 4bpp gray */ + /* assert(channels == 1) */ { png_bytep bp = row; - png_size_t i; - png_size_t istop = row_info->rowbytes; - png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) | - (png_byte)((int)0xf >> shift[0])); + png_bytep bp_end = bp + row_info->rowbytes; + int gray_shift = shift[0]; + int mask = 0xf >> gray_shift; - for (i = 0; i < istop; i++) + mask |= mask << 4; + + while (bp < bp_end) { - *bp >>= shift[0]; - *bp++ &= mask; + int b = (*bp >> gray_shift) & mask; + *bp++ = (png_byte)b; } break; } case 8: + /* Single byte components, G, GA, RGB, RGBA */ { png_bytep bp = row; - png_uint_32 i; - png_uint_32 istop = row_width * channels; + png_bytep bp_end = bp + row_info->rowbytes; + int channel = 0; - for (i = 0; i < istop; i++) + while (bp < bp_end) { - *bp++ >>= shift[i%channels]; + int b = *bp >> shift[channel]; + if (++channel >= channels) + channel = 0; + *bp++ = (png_byte)b; } break; } #ifdef PNG_READ_16BIT_SUPPORTED case 16: + /* Double byte components, G, GA, RGB, RGBA */ { png_bytep bp = row; - png_uint_32 i; - png_uint_32 istop = channels * row_width; + png_bytep bp_end = bp + row_info->rowbytes; + int channel = 0; - for (i = 0; i < istop; i++) + while (bp < bp_end) { - value = (png_uint_16)((*bp << 8) + *(bp + 1)); - value >>= shift[i%channels]; + int value = (bp[0] << 8) + bp[1]; + + value >>= shift[channel]; + if (++channel >= channels) + channel = 0; *bp++ = (png_byte)(value >> 8); *bp++ = (png_byte)(value & 0xff); } @@ -2537,7 +2397,7 @@ png_do_unshift(png_row_infop row_info, png_bytep row, #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED /* Scale rows of bit depth 16 down to 8 accurately */ -void /* PRIVATE */ +static void png_do_scale_16_to_8(png_row_infop row_info, png_bytep row) { png_debug(1, "in png_do_scale_16_to_8"); @@ -2545,7 +2405,7 @@ png_do_scale_16_to_8(png_row_infop row_info, png_bytep row) if (row_info->bit_depth == 16) { png_bytep sp = row; /* source */ - png_bytep dp = row; /* destinaton */ + png_bytep dp = row; /* destination */ png_bytep ep = sp + row_info->rowbytes; /* end+1 */ while (sp < ep) @@ -2595,7 +2455,7 @@ png_do_scale_16_to_8(png_row_infop row_info, png_bytep row) #endif #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED -void /* PRIVATE */ +static void /* Simply discard the low byte. This was the default behavior prior * to libpng-1.5.4. */ @@ -2606,7 +2466,7 @@ png_do_chop(png_row_infop row_info, png_bytep row) if (row_info->bit_depth == 16) { png_bytep sp = row; /* source */ - png_bytep dp = row; /* destinaton */ + png_bytep dp = row; /* destination */ png_bytep ep = sp + row_info->rowbytes; /* end+1 */ while (sp < ep) @@ -2623,7 +2483,7 @@ png_do_chop(png_row_infop row_info, png_bytep row) #endif #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED -void /* PRIVATE */ +static void png_do_read_swap_alpha(png_row_infop row_info, png_bytep row) { png_debug(1, "in png_do_read_swap_alpha"); @@ -2720,7 +2580,7 @@ png_do_read_swap_alpha(png_row_infop row_info, png_bytep row) #endif #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED -void /* PRIVATE */ +static void png_do_read_invert_alpha(png_row_infop row_info, png_bytep row) { png_uint_32 row_width; @@ -2822,7 +2682,7 @@ png_do_read_invert_alpha(png_row_infop row_info, png_bytep row) #ifdef PNG_READ_FILLER_SUPPORTED /* Add filler channel if we have RGB color */ -void /* PRIVATE */ +static void png_do_read_filler(png_row_infop row_info, png_bytep row, png_uint_32 filler, png_uint_32 flags) { @@ -2841,7 +2701,7 @@ png_do_read_filler(png_row_infop row_info, png_bytep row, { if (row_info->bit_depth == 8) { - if (flags & PNG_FLAG_FILLER_AFTER) + if ((flags & PNG_FLAG_FILLER_AFTER) != 0) { /* This changes the data from G to GX */ png_bytep sp = row + (png_size_t)row_width; @@ -2876,7 +2736,7 @@ png_do_read_filler(png_row_infop row_info, png_bytep row, #ifdef PNG_READ_16BIT_SUPPORTED else if (row_info->bit_depth == 16) { - if (flags & PNG_FLAG_FILLER_AFTER) + if ((flags & PNG_FLAG_FILLER_AFTER) != 0) { /* This changes the data from GG to GGXX */ png_bytep sp = row + (png_size_t)row_width * 2; @@ -2918,7 +2778,7 @@ png_do_read_filler(png_row_infop row_info, png_bytep row, { if (row_info->bit_depth == 8) { - if (flags & PNG_FLAG_FILLER_AFTER) + if ((flags & PNG_FLAG_FILLER_AFTER) != 0) { /* This changes the data from RGB to RGBX */ png_bytep sp = row + (png_size_t)row_width * 3; @@ -2957,7 +2817,7 @@ png_do_read_filler(png_row_infop row_info, png_bytep row, #ifdef PNG_READ_16BIT_SUPPORTED else if (row_info->bit_depth == 16) { - if (flags & PNG_FLAG_FILLER_AFTER) + if ((flags & PNG_FLAG_FILLER_AFTER) != 0) { /* This changes the data from RRGGBB to RRGGBBXX */ png_bytep sp = row + (png_size_t)row_width * 6; @@ -3009,7 +2869,7 @@ png_do_read_filler(png_row_infop row_info, png_bytep row, #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED /* Expand grayscale files to RGB, with or without alpha */ -void /* PRIVATE */ +static void png_do_gray_to_rgb(png_row_infop row_info, png_bytep row) { png_uint_32 i; @@ -3018,7 +2878,7 @@ png_do_gray_to_rgb(png_row_infop row_info, png_bytep row) png_debug(1, "in png_do_gray_to_rgb"); if (row_info->bit_depth >= 8 && - !(row_info->color_type & PNG_COLOR_MASK_COLOR)) + (row_info->color_type & PNG_COLOR_MASK_COLOR) == 0) { if (row_info->color_type == PNG_COLOR_TYPE_GRAY) { @@ -3086,7 +2946,7 @@ png_do_gray_to_rgb(png_row_infop row_info, png_bytep row) } } } - row_info->channels += (png_byte)2; + row_info->channels = (png_byte)(row_info->channels + 2); row_info->color_type |= PNG_COLOR_MASK_COLOR; row_info->pixel_depth = (png_byte)(row_info->channels * row_info->bit_depth); @@ -3097,269 +2957,242 @@ png_do_gray_to_rgb(png_row_infop row_info, png_bytep row) #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED /* Reduce RGB files to grayscale, with or without alpha - * using the equation given in Poynton's ColorFAQ at - * (THIS LINK IS DEAD June 2008) - * New link: - * + * using the equation given in Poynton's ColorFAQ of 1998-01-04 at + * (THIS LINK IS DEAD June 2008 but + * versions dated 1998 through November 2002 have been archived at + * http://web.archive.org/web/20000816232553/http://www.inforamp.net/ + * ~poynton/notes/colour_and_gamma/ColorFAQ.txt ) * Charles Poynton poynton at poynton.com * * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B * - * We approximate this with - * - * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B - * * which can be expressed with integers as * * Y = (6969 * R + 23434 * G + 2365 * B)/32768 * - * The calculation is to be done in a linear colorspace. + * Poynton's current link (as of January 2003 through July 2011): + * + * has changed the numbers slightly: * - * Other integer coefficents can be used via png_set_rgb_to_gray(). + * Y = 0.2126*R + 0.7152*G + 0.0722*B + * + * which can be expressed with integers as + * + * Y = (6966 * R + 23436 * G + 2366 * B)/32768 + * + * Historically, however, libpng uses numbers derived from the ITU-R Rec 709 + * end point chromaticities and the D65 white point. Depending on the + * precision used for the D65 white point this produces a variety of different + * numbers, however if the four decimal place value used in ITU-R Rec 709 is + * used (0.3127,0.3290) the Y calculation would be: + * + * Y = (6968 * R + 23435 * G + 2366 * B)/32768 + * + * While this is correct the rounding results in an overflow for white, because + * the sum of the rounded coefficients is 32769, not 32768. Consequently + * libpng uses, instead, the closest non-overflowing approximation: + * + * Y = (6968 * R + 23434 * G + 2366 * B)/32768 + * + * Starting with libpng-1.5.5, if the image being converted has a cHRM chunk + * (including an sRGB chunk) then the chromaticities are used to calculate the + * coefficients. See the chunk handling in pngrutil.c for more information. + * + * In all cases the calculation is to be done in a linear colorspace. If no + * gamma information is available to correct the encoding of the original RGB + * values this results in an implicit assumption that the original PNG RGB + * values were linear. + * + * Other integer coefficents can be used via png_set_rgb_to_gray(). Because + * the API takes just red and green coefficients the blue coefficient is + * calculated to make the sum 32768. This will result in different rounding + * to that used above. */ -int /* PRIVATE */ -png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row) +static int +png_do_rgb_to_gray(png_structrp png_ptr, png_row_infop row_info, png_bytep row) { - png_uint_32 i; - - png_uint_32 row_width = row_info->width; int rgb_error = 0; png_debug(1, "in png_do_rgb_to_gray"); - if (!(row_info->color_type & PNG_COLOR_MASK_PALETTE) && - (row_info->color_type & PNG_COLOR_MASK_COLOR)) + if ((row_info->color_type & PNG_COLOR_MASK_PALETTE) == 0 && + (row_info->color_type & PNG_COLOR_MASK_COLOR) != 0) { - png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff; - png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff; - png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff; + PNG_CONST png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff; + PNG_CONST png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff; + PNG_CONST png_uint_32 bc = 32768 - rc - gc; + PNG_CONST png_uint_32 row_width = row_info->width; + PNG_CONST int have_alpha = + (row_info->color_type & PNG_COLOR_MASK_ALPHA) != 0; - if (row_info->color_type == PNG_COLOR_TYPE_RGB) + if (row_info->bit_depth == 8) { - if (row_info->bit_depth == 8) +#ifdef PNG_READ_GAMMA_SUPPORTED + /* Notice that gamma to/from 1 are not necessarily inverses (if + * there is an overall gamma correction). Prior to 1.5.5 this code + * checked the linearized values for equality; this doesn't match + * the documentation, the original values must be checked. + */ + if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL) { -#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) - if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL) + png_bytep sp = row; + png_bytep dp = row; + png_uint_32 i; + + for (i = 0; i < row_width; i++) { - png_bytep sp = row; - png_bytep dp = row; + png_byte red = *(sp++); + png_byte green = *(sp++); + png_byte blue = *(sp++); - for (i = 0; i < row_width; i++) + if (red != green || red != blue) { - png_byte red = png_ptr->gamma_to_1[*(sp++)]; - png_byte green = png_ptr->gamma_to_1[*(sp++)]; - png_byte blue = png_ptr->gamma_to_1[*(sp++)]; + red = png_ptr->gamma_to_1[red]; + green = png_ptr->gamma_to_1[green]; + blue = png_ptr->gamma_to_1[blue]; - if (red != green || red != blue) - { - rgb_error |= 1; - *(dp++) = png_ptr->gamma_from_1[ - (rc*red + gc*green + bc*blue)>>15]; - } - - else - *(dp++) = *(sp - 1); + rgb_error |= 1; + *(dp++) = png_ptr->gamma_from_1[ + (rc*red + gc*green + bc*blue + 16384)>>15]; } - } - else -#endif - { - png_bytep sp = row; - png_bytep dp = row; - for (i = 0; i < row_width; i++) + + else { - png_byte red = *(sp++); - png_byte green = *(sp++); - png_byte blue = *(sp++); + /* If there is no overall correction the table will not be + * set. + */ + if (png_ptr->gamma_table != NULL) + red = png_ptr->gamma_table[red]; - if (red != green || red != blue) - { - rgb_error |= 1; - *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15); - } - - else - *(dp++) = *(sp - 1); + *(dp++) = red; } + + if (have_alpha != 0) + *(dp++) = *(sp++); } } - - else /* RGB bit_depth == 16 */ - { -#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) - if (png_ptr->gamma_16_to_1 != NULL && - png_ptr->gamma_16_from_1 != NULL) - { - png_bytep sp = row; - png_bytep dp = row; - for (i = 0; i < row_width; i++) - { - png_uint_16 red, green, blue, w; - - red = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; - green = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; - blue = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; - - if (red == green && red == blue) - w = red; - - else - { - png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) - >> png_ptr->gamma_shift][red>>8]; - png_uint_16 green_1 = - png_ptr->gamma_16_to_1[(green&0xff) >> - png_ptr->gamma_shift][green>>8]; - png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) - >> png_ptr->gamma_shift][blue>>8]; - png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1 - + bc*blue_1)>>15); - w = png_ptr->gamma_16_from_1[(gray16&0xff) >> - png_ptr->gamma_shift][gray16 >> 8]; - rgb_error |= 1; - } - - *(dp++) = (png_byte)((w>>8) & 0xff); - *(dp++) = (png_byte)(w & 0xff); - } - } - else + else #endif + { + png_bytep sp = row; + png_bytep dp = row; + png_uint_32 i; + + for (i = 0; i < row_width; i++) { - png_bytep sp = row; - png_bytep dp = row; - for (i = 0; i < row_width; i++) + png_byte red = *(sp++); + png_byte green = *(sp++); + png_byte blue = *(sp++); + + if (red != green || red != blue) { - png_uint_16 red, green, blue, gray16; - - red = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; - green = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; - blue = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; - - if (red != green || red != blue) - rgb_error |= 1; - - gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15); - *(dp++) = (png_byte)((gray16>>8) & 0xff); - *(dp++) = (png_byte)(gray16 & 0xff); + rgb_error |= 1; + /* NOTE: this is the historical approach which simply + * truncates the results. + */ + *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15); } + + else + *(dp++) = red; + + if (have_alpha != 0) + *(dp++) = *(sp++); } } } - if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + + else /* RGB bit_depth == 16 */ { - if (row_info->bit_depth == 8) +#ifdef PNG_READ_GAMMA_SUPPORTED + if (png_ptr->gamma_16_to_1 != NULL && png_ptr->gamma_16_from_1 != NULL) { -#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) - if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL) + png_bytep sp = row; + png_bytep dp = row; + png_uint_32 i; + + for (i = 0; i < row_width; i++) { - png_bytep sp = row; - png_bytep dp = row; - for (i = 0; i < row_width; i++) + png_uint_16 red, green, blue, w; + + red = (png_uint_16)(((*(sp)) << 8) | *(sp + 1)); sp += 2; + green = (png_uint_16)(((*(sp)) << 8) | *(sp + 1)); sp += 2; + blue = (png_uint_16)(((*(sp)) << 8) | *(sp + 1)); sp += 2; + + if (red == green && red == blue) { - png_byte red = png_ptr->gamma_to_1[*(sp++)]; - png_byte green = png_ptr->gamma_to_1[*(sp++)]; - png_byte blue = png_ptr->gamma_to_1[*(sp++)]; - - if (red != green || red != blue) - rgb_error |= 1; - - *(dp++) = png_ptr->gamma_from_1 - [(rc*red + gc*green + bc*blue)>>15]; - - *(dp++) = *(sp++); /* alpha */ - } - } - else -#endif - { - png_bytep sp = row; - png_bytep dp = row; - for (i = 0; i < row_width; i++) - { - png_byte red = *(sp++); - png_byte green = *(sp++); - png_byte blue = *(sp++); - if (red != green || red != blue) - rgb_error |= 1; - - *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15); - *(dp++) = *(sp++); /* alpha */ - } - } - } - else /* RGBA bit_depth == 16 */ - { -#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) - if (png_ptr->gamma_16_to_1 != NULL && - png_ptr->gamma_16_from_1 != NULL) - { - png_bytep sp = row; - png_bytep dp = row; - for (i = 0; i < row_width; i++) - { - png_uint_16 red, green, blue, w; - - red = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; - green = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; - blue = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; - - if (red == green && red == blue) - w = red; + if (png_ptr->gamma_16_table != NULL) + w = png_ptr->gamma_16_table[(red & 0xff) + >> png_ptr->gamma_shift][red >> 8]; else - { - png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >> - png_ptr->gamma_shift][red>>8]; + w = red; + } - png_uint_16 green_1 = - png_ptr->gamma_16_to_1[(green&0xff) >> - png_ptr->gamma_shift][green>>8]; + else + { + png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) + >> png_ptr->gamma_shift][red>>8]; + png_uint_16 green_1 = + png_ptr->gamma_16_to_1[(green&0xff) >> + png_ptr->gamma_shift][green>>8]; + png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) + >> png_ptr->gamma_shift][blue>>8]; + png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1 + + bc*blue_1 + 16384)>>15); + w = png_ptr->gamma_16_from_1[(gray16&0xff) >> + png_ptr->gamma_shift][gray16 >> 8]; + rgb_error |= 1; + } - png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >> - png_ptr->gamma_shift][blue>>8]; + *(dp++) = (png_byte)((w>>8) & 0xff); + *(dp++) = (png_byte)(w & 0xff); - png_uint_16 gray16 = (png_uint_16)((rc * red_1 - + gc * green_1 + bc * blue_1)>>15); - - w = png_ptr->gamma_16_from_1[(gray16&0xff) >> - png_ptr->gamma_shift][gray16 >> 8]; - - rgb_error |= 1; - } - - *(dp++) = (png_byte)((w>>8) & 0xff); - *(dp++) = (png_byte)(w & 0xff); - *(dp++) = *(sp++); /* alpha */ + if (have_alpha != 0) + { + *(dp++) = *(sp++); *(dp++) = *(sp++); } } - else + } + else #endif + { + png_bytep sp = row; + png_bytep dp = row; + png_uint_32 i; + + for (i = 0; i < row_width; i++) { - png_bytep sp = row; - png_bytep dp = row; - for (i = 0; i < row_width; i++) + png_uint_16 red, green, blue, gray16; + + red = (png_uint_16)(((*(sp)) << 8) | *(sp + 1)); sp += 2; + green = (png_uint_16)(((*(sp)) << 8) | *(sp + 1)); sp += 2; + blue = (png_uint_16)(((*(sp)) << 8) | *(sp + 1)); sp += 2; + + if (red != green || red != blue) + rgb_error |= 1; + + /* From 1.5.5 in the 16 bit case do the accurate conversion even + * in the 'fast' case - this is because this is where the code + * ends up when handling linear 16 bit data. + */ + gray16 = (png_uint_16)((rc*red + gc*green + bc*blue + 16384) >> + 15); + *(dp++) = (png_byte)((gray16 >> 8) & 0xff); + *(dp++) = (png_byte)(gray16 & 0xff); + + if (have_alpha != 0) { - png_uint_16 red, green, blue, gray16; - red = (png_uint_16)((*(sp)<<8) | *(sp + 1)); sp += 2; - green = (png_uint_16)((*(sp)<<8) | *(sp + 1)); sp += 2; - blue = (png_uint_16)((*(sp)<<8) | *(sp + 1)); sp += 2; - - if (red != green || red != blue) - rgb_error |= 1; - - gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15); - *(dp++) = (png_byte)((gray16>>8) & 0xff); - *(dp++) = (png_byte)(gray16 & 0xff); - *(dp++) = *(sp++); /* alpha */ + *(dp++) = *(sp++); *(dp++) = *(sp++); } } } } - row_info->channels -= 2; + + row_info->channels = (png_byte)(row_info->channels - 2); row_info->color_type = (png_byte)(row_info->color_type & ~PNG_COLOR_MASK_COLOR); row_info->pixel_depth = (png_byte)(row_info->channels * @@ -3369,73 +3202,15 @@ png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row) return rgb_error; } #endif -#endif /* PNG_READ_TRANSFORMS_SUPPORTED */ -#ifdef PNG_BUILD_GRAYSCALE_PALETTE_SUPPORTED -/* Build a grayscale palette. Palette is assumed to be 1 << bit_depth - * large of png_color. This lets grayscale images be treated as - * paletted. Most useful for gamma correction and simplification - * of code. This API is not used internally. - */ -void PNGAPI -png_build_grayscale_palette(int bit_depth, png_colorp palette) -{ - int num_palette; - int color_inc; - int i; - int v; - - png_debug(1, "in png_do_build_grayscale_palette"); - - if (palette == NULL) - return; - - switch (bit_depth) - { - case 1: - num_palette = 2; - color_inc = 0xff; - break; - - case 2: - num_palette = 4; - color_inc = 0x55; - break; - - case 4: - num_palette = 16; - color_inc = 0x11; - break; - - case 8: - num_palette = 256; - color_inc = 1; - break; - - default: - num_palette = 0; - color_inc = 0; - break; - } - - for (i = 0, v = 0; i < num_palette; i++, v += color_inc) - { - palette[i].red = (png_byte)v; - palette[i].green = (png_byte)v; - palette[i].blue = (png_byte)v; - } -} -#endif - - -#ifdef PNG_READ_TRANSFORMS_SUPPORTED -#ifdef PNG_READ_BACKGROUND_SUPPORTED +#if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\ + defined(PNG_READ_ALPHA_MODE_SUPPORTED) /* Replace any alpha or transparency with the supplied background color. * "background" is already in the screen gamma, while "background_1" is * at a gamma of 1.0. Paletted files have already been taken care of. */ -void /* PRIVATE */ -png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) +static void +png_do_compose(png_row_infop row_info, png_bytep row, png_structrp png_ptr) { #ifdef PNG_READ_GAMMA_SUPPORTED png_const_bytep gamma_table = png_ptr->gamma_table; @@ -3445,12 +3220,12 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) png_const_uint_16pp gamma_16_from_1 = png_ptr->gamma_16_from_1; png_const_uint_16pp gamma_16_to_1 = png_ptr->gamma_16_to_1; int gamma_shift = png_ptr->gamma_shift; + int optimize = (png_ptr->flags & PNG_FLAG_OPTIMIZE_ALPHA) != 0; #endif png_bytep sp; png_uint_32 i; png_uint_32 row_width = row_info->width; - int optimize = (png_ptr->flags & PNG_FLAG_OPTIMIZE_ALPHA) != 0; int shift; png_debug(1, "in png_do_compose"); @@ -3471,11 +3246,12 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) if ((png_uint_16)((*sp >> shift) & 0x01) == png_ptr->trans_color.gray) { - *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff); - *sp |= (png_byte)(png_ptr->background.gray << shift); + unsigned int tmp = *sp & (0x7f7f >> (7 - shift)); + tmp |= png_ptr->background.gray << shift; + *sp = (png_byte)(tmp & 0xff); } - if (!shift) + if (shift == 0) { shift = 7; sp++; @@ -3499,20 +3275,22 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) if ((png_uint_16)((*sp >> shift) & 0x03) == png_ptr->trans_color.gray) { - *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff); - *sp |= (png_byte)(png_ptr->background.gray << shift); + unsigned int tmp = *sp & (0x3f3f >> (6 - shift)); + tmp |= png_ptr->background.gray << shift; + *sp = (png_byte)(tmp & 0xff); } else { - png_byte p = (png_byte)((*sp >> shift) & 0x03); - png_byte g = (png_byte)((gamma_table [p | (p << 2) | - (p << 4) | (p << 6)] >> 6) & 0x03); - *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff); - *sp |= (png_byte)(g << shift); + unsigned int p = (*sp >> shift) & 0x03; + unsigned int g = (gamma_table [p | (p << 2) | + (p << 4) | (p << 6)] >> 6) & 0x03; + unsigned int tmp = *sp & (0x3f3f >> (6 - shift)); + tmp |= g << shift; + *sp = (png_byte)(tmp & 0xff); } - if (!shift) + if (shift == 0) { shift = 6; sp++; @@ -3533,11 +3311,12 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) if ((png_uint_16)((*sp >> shift) & 0x03) == png_ptr->trans_color.gray) { - *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff); - *sp |= (png_byte)(png_ptr->background.gray << shift); + unsigned int tmp = *sp & (0x3f3f >> (6 - shift)); + tmp |= png_ptr->background.gray << shift; + *sp = (png_byte)(tmp & 0xff); } - if (!shift) + if (shift == 0) { shift = 6; sp++; @@ -3562,20 +3341,22 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) if ((png_uint_16)((*sp >> shift) & 0x0f) == png_ptr->trans_color.gray) { - *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff); - *sp |= (png_byte)(png_ptr->background.gray << shift); + unsigned int tmp = *sp & (0xf0f >> (4 - shift)); + tmp |= png_ptr->background.gray << shift; + *sp = (png_byte)(tmp & 0xff); } else { - png_byte p = (png_byte)((*sp >> shift) & 0x0f); - png_byte g = (png_byte)((gamma_table[p | - (p << 4)] >> 4) & 0x0f); - *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff); - *sp |= (png_byte)(g << shift); + unsigned int p = (*sp >> shift) & 0x0f; + unsigned int g = (gamma_table[p | (p << 4)] >> 4) & + 0x0f; + unsigned int tmp = *sp & (0xf0f >> (4 - shift)); + tmp |= g << shift; + *sp = (png_byte)(tmp & 0xff); } - if (!shift) + if (shift == 0) { shift = 4; sp++; @@ -3596,11 +3377,12 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) if ((png_uint_16)((*sp >> shift) & 0x0f) == png_ptr->trans_color.gray) { - *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff); - *sp |= (png_byte)(png_ptr->background.gray << shift); + unsigned int tmp = *sp & (0xf0f >> (4 - shift)); + tmp |= png_ptr->background.gray << shift; + *sp = (png_byte)(tmp & 0xff); } - if (!shift) + if (shift == 0) { shift = 4; sp++; @@ -3656,8 +3438,10 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) if (v == png_ptr->trans_color.gray) { /* Background is already in screen gamma */ - *sp = (png_byte)((png_ptr->background.gray >> 8) & 0xff); - *(sp + 1) = (png_byte)(png_ptr->background.gray & 0xff); + *sp = (png_byte)((png_ptr->background.gray >> 8) + & 0xff); + *(sp + 1) = (png_byte)(png_ptr->background.gray + & 0xff); } else @@ -3680,8 +3464,10 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) if (v == png_ptr->trans_color.gray) { - *sp = (png_byte)((png_ptr->background.gray >> 8) & 0xff); - *(sp + 1) = (png_byte)(png_ptr->background.gray & 0xff); + *sp = (png_byte)((png_ptr->background.gray >> 8) + & 0xff); + *(sp + 1) = (png_byte)(png_ptr->background.gray + & 0xff); } } } @@ -3761,9 +3547,12 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) /* Background is already in screen gamma */ *sp = (png_byte)((png_ptr->background.red >> 8) & 0xff); *(sp + 1) = (png_byte)(png_ptr->background.red & 0xff); - *(sp + 2) = (png_byte)((png_ptr->background.green >> 8) & 0xff); - *(sp + 3) = (png_byte)(png_ptr->background.green & 0xff); - *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8) & 0xff); + *(sp + 2) = (png_byte)((png_ptr->background.green >> 8) + & 0xff); + *(sp + 3) = (png_byte)(png_ptr->background.green + & 0xff); + *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8) + & 0xff); *(sp + 5) = (png_byte)(png_ptr->background.blue & 0xff); } @@ -3804,9 +3593,12 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) { *sp = (png_byte)((png_ptr->background.red >> 8) & 0xff); *(sp + 1) = (png_byte)(png_ptr->background.red & 0xff); - *(sp + 2) = (png_byte)((png_ptr->background.green >> 8) & 0xff); - *(sp + 3) = (png_byte)(png_ptr->background.green & 0xff); - *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8) & 0xff); + *(sp + 2) = (png_byte)((png_ptr->background.green >> 8) + & 0xff); + *(sp + 3) = (png_byte)(png_ptr->background.green + & 0xff); + *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8) + & 0xff); *(sp + 5) = (png_byte)(png_ptr->background.blue & 0xff); } } @@ -3843,7 +3635,7 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) v = gamma_to_1[*sp]; png_composite(w, v, a, png_ptr->background_1.gray); - if (!optimize) + if (optimize == 0) w = gamma_from_1[w]; *sp = w; } @@ -3861,7 +3653,7 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) *sp = (png_byte)png_ptr->background.gray; else if (a < 0xff) - png_composite(*sp, *sp, a, png_ptr->background_1.gray); + png_composite(*sp, *sp, a, png_ptr->background.gray); } } } @@ -3889,7 +3681,8 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) else if (a == 0) { /* Background is already in screen gamma */ - *sp = (png_byte)((png_ptr->background.gray >> 8) & 0xff); + *sp = (png_byte)((png_ptr->background.gray >> 8) + & 0xff); *(sp + 1) = (png_byte)(png_ptr->background.gray & 0xff); } @@ -3899,7 +3692,7 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp]; png_composite_16(v, g, a, png_ptr->background_1.gray); - if (optimize) + if (optimize != 0) w = v; else w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8]; @@ -3919,7 +3712,8 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) if (a == 0) { - *sp = (png_byte)((png_ptr->background.gray >> 8) & 0xff); + *sp = (png_byte)((png_ptr->background.gray >> 8) + & 0xff); *(sp + 1) = (png_byte)(png_ptr->background.gray & 0xff); } @@ -3928,7 +3722,7 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) png_uint_16 g, v; g = (png_uint_16)(((*sp) << 8) + *(sp + 1)); - png_composite_16(v, g, a, png_ptr->background_1.gray); + png_composite_16(v, g, a, png_ptr->background.gray); *sp = (png_byte)((v >> 8) & 0xff); *(sp + 1) = (png_byte)(v & 0xff); } @@ -3972,17 +3766,17 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) v = gamma_to_1[*sp]; png_composite(w, v, a, png_ptr->background_1.red); - if (!optimize) w = gamma_from_1[w]; + if (optimize == 0) w = gamma_from_1[w]; *sp = w; v = gamma_to_1[*(sp + 1)]; png_composite(w, v, a, png_ptr->background_1.green); - if (!optimize) w = gamma_from_1[w]; + if (optimize == 0) w = gamma_from_1[w]; *(sp + 1) = w; v = gamma_to_1[*(sp + 2)]; png_composite(w, v, a, png_ptr->background_1.blue); - if (!optimize) w = gamma_from_1[w]; + if (optimize == 0) w = gamma_from_1[w]; *(sp + 2) = w; } } @@ -4049,9 +3843,12 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) /* Background is already in screen gamma */ *sp = (png_byte)((png_ptr->background.red >> 8) & 0xff); *(sp + 1) = (png_byte)(png_ptr->background.red & 0xff); - *(sp + 2) = (png_byte)((png_ptr->background.green >> 8) & 0xff); - *(sp + 3) = (png_byte)(png_ptr->background.green & 0xff); - *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8) & 0xff); + *(sp + 2) = (png_byte)((png_ptr->background.green >> 8) + & 0xff); + *(sp + 3) = (png_byte)(png_ptr->background.green + & 0xff); + *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8) + & 0xff); *(sp + 5) = (png_byte)(png_ptr->background.blue & 0xff); } @@ -4061,23 +3858,26 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp]; png_composite_16(w, v, a, png_ptr->background_1.red); - if (!optimize) - w = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8]; + if (optimize == 0) + w = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> + 8]; *sp = (png_byte)((w >> 8) & 0xff); *(sp + 1) = (png_byte)(w & 0xff); v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)]; png_composite_16(w, v, a, png_ptr->background_1.green); - if (!optimize) - w = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8]; + if (optimize == 0) + w = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> + 8]; *(sp + 2) = (png_byte)((w >> 8) & 0xff); *(sp + 3) = (png_byte)(w & 0xff); v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)]; png_composite_16(w, v, a, png_ptr->background_1.blue); - if (!optimize) - w = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8]; + if (optimize == 0) + w = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> + 8]; *(sp + 4) = (png_byte)((w >> 8) & 0xff); *(sp + 5) = (png_byte)(w & 0xff); @@ -4098,9 +3898,12 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) { *sp = (png_byte)((png_ptr->background.red >> 8) & 0xff); *(sp + 1) = (png_byte)(png_ptr->background.red & 0xff); - *(sp + 2) = (png_byte)((png_ptr->background.green >> 8) & 0xff); - *(sp + 3) = (png_byte)(png_ptr->background.green & 0xff); - *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8) & 0xff); + *(sp + 2) = (png_byte)((png_ptr->background.green >> 8) + & 0xff); + *(sp + 3) = (png_byte)(png_ptr->background.green + & 0xff); + *(sp + 4) = (png_byte)((png_ptr->background.blue >> 8) + & 0xff); *(sp + 5) = (png_byte)(png_ptr->background.blue & 0xff); } @@ -4137,7 +3940,7 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) } } } -#endif +#endif /* READ_BACKGROUND || READ_ALPHA_MODE */ #ifdef PNG_READ_GAMMA_SUPPORTED /* Gamma correct the image, avoiding the alpha channel. Make sure @@ -4146,8 +3949,8 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structp png_ptr) * is 16, use gamma_16_table and gamma_shift. Build these with * build_gamma_table(). */ -void /* PRIVATE */ -png_do_gamma(png_row_infop row_info, png_bytep row, png_structp png_ptr) +static void +png_do_gamma(png_row_infop row_info, png_bytep row, png_structrp png_ptr) { png_const_bytep gamma_table = png_ptr->gamma_table; png_const_uint_16pp gamma_16_table = png_ptr->gamma_16_table; @@ -4347,14 +4150,14 @@ png_do_gamma(png_row_infop row_info, png_bytep row, png_structp png_ptr) * linear.) Called only with color types that have an alpha channel. Needs the * from_1 tables. */ -void /* PRIVATE */ -png_do_encode_alpha(png_row_infop row_info, png_bytep row, png_structp png_ptr) +static void +png_do_encode_alpha(png_row_infop row_info, png_bytep row, png_structrp png_ptr) { png_uint_32 row_width = row_info->width; png_debug(1, "in png_do_encode_alpha"); - if (row_info->color_type & PNG_COLOR_MASK_ALPHA) + if ((row_info->color_type & PNG_COLOR_MASK_ALPHA) != 0) { if (row_info->bit_depth == 8) { @@ -4413,7 +4216,7 @@ png_do_encode_alpha(png_row_infop row_info, png_bytep row, png_structp png_ptr) /* Expands a palette row to an RGB or RGBA row depending * upon whether you supply trans and num_trans. */ -void /* PRIVATE */ +static void png_do_expand_palette(png_row_infop row_info, png_bytep row, png_const_colorp palette, png_const_bytep trans_alpha, int num_trans) { @@ -4566,7 +4369,7 @@ png_do_expand_palette(png_row_infop row_info, png_bytep row, /* If the bit depth < 8, it is expanded to 8. Also, if the already * expanded transparency value is supplied, an alpha channel is built. */ -void /* PRIVATE */ +static void png_do_expand(png_row_infop row_info, png_bytep row, png_const_color_16p trans_color) { @@ -4580,7 +4383,7 @@ png_do_expand(png_row_infop row_info, png_bytep row, { if (row_info->color_type == PNG_COLOR_TYPE_GRAY) { - png_uint_16 gray = (png_uint_16)(trans_color ? trans_color->gray : 0); + unsigned int gray = trans_color != NULL ? trans_color->gray : 0; if (row_info->bit_depth < 8) { @@ -4588,7 +4391,7 @@ png_do_expand(png_row_infop row_info, png_bytep row, { case 1: { - gray = (png_uint_16)((gray & 0x01) * 0xff); + gray = (gray & 0x01) * 0xff; sp = row + (png_size_t)((row_width - 1) >> 3); dp = row + (png_size_t)row_width - 1; shift = 7 - (int)((row_width + 7) & 0x07); @@ -4616,7 +4419,7 @@ png_do_expand(png_row_infop row_info, png_bytep row, case 2: { - gray = (png_uint_16)((gray & 0x03) * 0x55); + gray = (gray & 0x03) * 0x55; sp = row + (png_size_t)((row_width - 1) >> 2); dp = row + (png_size_t)row_width - 1; shift = (int)((3 - ((row_width + 3) & 0x03)) << 1); @@ -4641,7 +4444,7 @@ png_do_expand(png_row_infop row_info, png_bytep row, case 4: { - gray = (png_uint_16)((gray & 0x0f) * 0x11); + gray = (gray & 0x0f) * 0x11; sp = row + (png_size_t)((row_width - 1) >> 1); dp = row + (png_size_t)row_width - 1; shift = (int)((1 - ((row_width + 1) & 0x01)) << 2); @@ -4694,8 +4497,8 @@ png_do_expand(png_row_infop row_info, png_bytep row, else if (row_info->bit_depth == 16) { - png_byte gray_high = (png_byte)((gray >> 8) & 0xff); - png_byte gray_low = (png_byte)(gray & 0xff); + unsigned int gray_high = (gray >> 8) & 0xff; + unsigned int gray_low = gray & 0xff; sp = row + row_info->rowbytes - 1; dp = row + (row_info->rowbytes << 1) - 1; for (i = 0; i < row_width; i++) @@ -4724,7 +4527,8 @@ png_do_expand(png_row_infop row_info, png_bytep row, row_width); } } - else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_color) + else if (row_info->color_type == PNG_COLOR_TYPE_RGB && + trans_color != NULL) { if (row_info->bit_depth == 8) { @@ -4793,10 +4597,10 @@ png_do_expand(png_row_infop row_info, png_bytep row, #endif #ifdef PNG_READ_EXPAND_16_SUPPORTED -/* If the bit depth is 8 and the colour type is not a palette type expand the +/* If the bit depth is 8 and the color type is not a palette type expand the * whole row to 16 bits. Has no effect otherwise. */ -void /* PRIVATE */ +static void png_do_expand_16(png_row_infop row_info, png_bytep row) { if (row_info->bit_depth == 8 && @@ -4824,7 +4628,7 @@ png_do_expand_16(png_row_infop row_info, png_bytep row) #endif #ifdef PNG_READ_QUANTIZE_SUPPORTED -void /* PRIVATE */ +static void png_do_quantize(png_row_infop row_info, png_bytep row, png_const_bytep palette_lookup, png_const_bytep quantize_lookup) { @@ -4915,70 +4719,304 @@ png_do_quantize(png_row_infop row_info, png_bytep row, } } } -#endif /* PNG_READ_QUANTIZE_SUPPORTED */ -#endif /* PNG_READ_TRANSFORMS_SUPPORTED */ +#endif /* READ_QUANTIZE */ -#ifdef PNG_MNG_FEATURES_SUPPORTED -/* Undoes intrapixel differencing */ +/* Transform the row. The order of transformations is significant, + * and is very touchy. If you add a transformation, take care to + * decide how it fits in with the other transformations here. + */ void /* PRIVATE */ -png_do_read_intrapixel(png_row_infop row_info, png_bytep row) +png_do_read_transformations(png_structrp png_ptr, png_row_infop row_info) { - png_debug(1, "in png_do_read_intrapixel"); + png_debug(1, "in png_do_read_transformations"); - if ( - (row_info->color_type & PNG_COLOR_MASK_COLOR)) + if (png_ptr->row_buf == NULL) { - int bytes_per_pixel; - png_uint_32 row_width = row_info->width; + /* Prior to 1.5.4 this output row/pass where the NULL pointer is, but this + * error is incredibly rare and incredibly easy to debug without this + * information. + */ + png_error(png_ptr, "NULL row buffer"); + } - if (row_info->bit_depth == 8) + /* The following is debugging; prior to 1.5.4 the code was never compiled in; + * in 1.5.4 PNG_FLAG_DETECT_UNINITIALIZED was added and the macro + * PNG_WARN_UNINITIALIZED_ROW removed. In 1.6 the new flag is set only for + * all transformations, however in practice the ROW_INIT always gets done on + * demand, if necessary. + */ + if ((png_ptr->flags & PNG_FLAG_DETECT_UNINITIALIZED) != 0 && + (png_ptr->flags & PNG_FLAG_ROW_INIT) == 0) + { + /* Application has failed to call either png_read_start_image() or + * png_read_update_info() after setting transforms that expand pixels. + * This check added to libpng-1.2.19 (but not enabled until 1.5.4). + */ + png_error(png_ptr, "Uninitialized row"); + } + +#ifdef PNG_READ_EXPAND_SUPPORTED + if ((png_ptr->transformations & PNG_EXPAND) != 0) + { + if (row_info->color_type == PNG_COLOR_TYPE_PALETTE) { - png_bytep rp; - png_uint_32 i; - - if (row_info->color_type == PNG_COLOR_TYPE_RGB) - bytes_per_pixel = 3; - - else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) - bytes_per_pixel = 4; - - else - return; - - for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel) - { - *(rp) = (png_byte)((256 + *rp + *(rp + 1)) & 0xff); - *(rp+2) = (png_byte)((256 + *(rp + 2) + *(rp + 1)) & 0xff); - } + png_do_expand_palette(row_info, png_ptr->row_buf + 1, + png_ptr->palette, png_ptr->trans_alpha, png_ptr->num_trans); } - else if (row_info->bit_depth == 16) + + else { - png_bytep rp; - png_uint_32 i; - - if (row_info->color_type == PNG_COLOR_TYPE_RGB) - bytes_per_pixel = 6; - - else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) - bytes_per_pixel = 8; + if (png_ptr->num_trans != 0 && + (png_ptr->transformations & PNG_EXPAND_tRNS) != 0) + png_do_expand(row_info, png_ptr->row_buf + 1, + &(png_ptr->trans_color)); else - return; - - for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel) - { - png_uint_32 s0 = (*(rp ) << 8) | *(rp + 1); - png_uint_32 s1 = (*(rp + 2) << 8) | *(rp + 3); - png_uint_32 s2 = (*(rp + 4) << 8) | *(rp + 5); - png_uint_32 red = (png_uint_32)((s0 + s1 + 65536L) & 0xffffL); - png_uint_32 blue = (png_uint_32)((s2 + s1 + 65536L) & 0xffffL); - *(rp ) = (png_byte)((red >> 8) & 0xff); - *(rp + 1) = (png_byte)(red & 0xff); - *(rp + 4) = (png_byte)((blue >> 8) & 0xff); - *(rp + 5) = (png_byte)(blue & 0xff); - } + png_do_expand(row_info, png_ptr->row_buf + 1, + NULL); } } +#endif + +#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED + if ((png_ptr->transformations & PNG_STRIP_ALPHA) != 0 && + (png_ptr->transformations & PNG_COMPOSE) == 0 && + (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA || + row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) + png_do_strip_channel(row_info, png_ptr->row_buf + 1, + 0 /* at_start == false, because SWAP_ALPHA happens later */); +#endif + +#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED + if ((png_ptr->transformations & PNG_RGB_TO_GRAY) != 0) + { + int rgb_error = + png_do_rgb_to_gray(png_ptr, row_info, + png_ptr->row_buf + 1); + + if (rgb_error != 0) + { + png_ptr->rgb_to_gray_status=1; + if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == + PNG_RGB_TO_GRAY_WARN) + png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel"); + + if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == + PNG_RGB_TO_GRAY_ERR) + png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel"); + } + } +#endif + +/* From Andreas Dilger e-mail to png-implement, 26 March 1998: + * + * In most cases, the "simple transparency" should be done prior to doing + * gray-to-RGB, or you will have to test 3x as many bytes to check if a + * pixel is transparent. You would also need to make sure that the + * transparency information is upgraded to RGB. + * + * To summarize, the current flow is: + * - Gray + simple transparency -> compare 1 or 2 gray bytes and composite + * with background "in place" if transparent, + * convert to RGB if necessary + * - Gray + alpha -> composite with gray background and remove alpha bytes, + * convert to RGB if necessary + * + * To support RGB backgrounds for gray images we need: + * - Gray + simple transparency -> convert to RGB + simple transparency, + * compare 3 or 6 bytes and composite with + * background "in place" if transparent + * (3x compare/pixel compared to doing + * composite with gray bkgrnd) + * - Gray + alpha -> convert to RGB + alpha, composite with background and + * remove alpha bytes (3x float + * operations/pixel compared with composite + * on gray background) + * + * Greg's change will do this. The reason it wasn't done before is for + * performance, as this increases the per-pixel operations. If we would check + * in advance if the background was gray or RGB, and position the gray-to-RGB + * transform appropriately, then it would save a lot of work/time. + */ + +#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED + /* If gray -> RGB, do so now only if background is non-gray; else do later + * for performance reasons + */ + if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0 && + (png_ptr->mode & PNG_BACKGROUND_IS_GRAY) == 0) + png_do_gray_to_rgb(row_info, png_ptr->row_buf + 1); +#endif + +#if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\ + defined(PNG_READ_ALPHA_MODE_SUPPORTED) + if ((png_ptr->transformations & PNG_COMPOSE) != 0) + png_do_compose(row_info, png_ptr->row_buf + 1, png_ptr); +#endif + +#ifdef PNG_READ_GAMMA_SUPPORTED + if ((png_ptr->transformations & PNG_GAMMA) != 0 && +#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED + /* Because RGB_TO_GRAY does the gamma transform. */ + (png_ptr->transformations & PNG_RGB_TO_GRAY) == 0 && +#endif +#if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\ + defined(PNG_READ_ALPHA_MODE_SUPPORTED) + /* Because PNG_COMPOSE does the gamma transform if there is something to + * do (if there is an alpha channel or transparency.) + */ + !((png_ptr->transformations & PNG_COMPOSE) && + ((png_ptr->num_trans != 0) || + (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)) && +#endif + /* Because png_init_read_transformations transforms the palette, unless + * RGB_TO_GRAY will do the transform. + */ + (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)) + png_do_gamma(row_info, png_ptr->row_buf + 1, png_ptr); +#endif + +#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED + if ((png_ptr->transformations & PNG_STRIP_ALPHA) != 0 && + (png_ptr->transformations & PNG_COMPOSE) != 0 && + (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA || + row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) + png_do_strip_channel(row_info, png_ptr->row_buf + 1, + 0 /* at_start == false, because SWAP_ALPHA happens later */); +#endif + +#ifdef PNG_READ_ALPHA_MODE_SUPPORTED + if ((png_ptr->transformations & PNG_ENCODE_ALPHA) != 0 && + (row_info->color_type & PNG_COLOR_MASK_ALPHA) != 0) + png_do_encode_alpha(row_info, png_ptr->row_buf + 1, png_ptr); +#endif + +#ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED + if ((png_ptr->transformations & PNG_SCALE_16_TO_8) != 0) + png_do_scale_16_to_8(row_info, png_ptr->row_buf + 1); +#endif + +#ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED + /* There is no harm in doing both of these because only one has any effect, + * by putting the 'scale' option first if the app asks for scale (either by + * calling the API or in a TRANSFORM flag) this is what happens. + */ + if ((png_ptr->transformations & PNG_16_TO_8) != 0) + png_do_chop(row_info, png_ptr->row_buf + 1); +#endif + +#ifdef PNG_READ_QUANTIZE_SUPPORTED + if ((png_ptr->transformations & PNG_QUANTIZE) != 0) + { + png_do_quantize(row_info, png_ptr->row_buf + 1, + png_ptr->palette_lookup, png_ptr->quantize_index); + + if (row_info->rowbytes == 0) + png_error(png_ptr, "png_do_quantize returned rowbytes=0"); + } +#endif /* READ_QUANTIZE */ + +#ifdef PNG_READ_EXPAND_16_SUPPORTED + /* Do the expansion now, after all the arithmetic has been done. Notice + * that previous transformations can handle the PNG_EXPAND_16 flag if this + * is efficient (particularly true in the case of gamma correction, where + * better accuracy results faster!) + */ + if ((png_ptr->transformations & PNG_EXPAND_16) != 0) + png_do_expand_16(row_info, png_ptr->row_buf + 1); +#endif + +#ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED + /* NOTE: moved here in 1.5.4 (from much later in this list.) */ + if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0 && + (png_ptr->mode & PNG_BACKGROUND_IS_GRAY) != 0) + png_do_gray_to_rgb(row_info, png_ptr->row_buf + 1); +#endif + +#ifdef PNG_READ_INVERT_SUPPORTED + if ((png_ptr->transformations & PNG_INVERT_MONO) != 0) + png_do_invert(row_info, png_ptr->row_buf + 1); +#endif + +#ifdef PNG_READ_INVERT_ALPHA_SUPPORTED + if ((png_ptr->transformations & PNG_INVERT_ALPHA) != 0) + png_do_read_invert_alpha(row_info, png_ptr->row_buf + 1); +#endif + +#ifdef PNG_READ_SHIFT_SUPPORTED + if ((png_ptr->transformations & PNG_SHIFT) != 0) + png_do_unshift(row_info, png_ptr->row_buf + 1, + &(png_ptr->shift)); +#endif + +#ifdef PNG_READ_PACK_SUPPORTED + if ((png_ptr->transformations & PNG_PACK) != 0) + png_do_unpack(row_info, png_ptr->row_buf + 1); +#endif + +#ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED + /* Added at libpng-1.5.10 */ + if (row_info->color_type == PNG_COLOR_TYPE_PALETTE && + png_ptr->num_palette_max >= 0) + png_do_check_palette_indexes(png_ptr, row_info); +#endif + +#ifdef PNG_READ_BGR_SUPPORTED + if ((png_ptr->transformations & PNG_BGR) != 0) + png_do_bgr(row_info, png_ptr->row_buf + 1); +#endif + +#ifdef PNG_READ_PACKSWAP_SUPPORTED + if ((png_ptr->transformations & PNG_PACKSWAP) != 0) + png_do_packswap(row_info, png_ptr->row_buf + 1); +#endif + +#ifdef PNG_READ_FILLER_SUPPORTED + if ((png_ptr->transformations & PNG_FILLER) != 0) + png_do_read_filler(row_info, png_ptr->row_buf + 1, + (png_uint_32)png_ptr->filler, png_ptr->flags); +#endif + +#ifdef PNG_READ_SWAP_ALPHA_SUPPORTED + if ((png_ptr->transformations & PNG_SWAP_ALPHA) != 0) + png_do_read_swap_alpha(row_info, png_ptr->row_buf + 1); +#endif + +#ifdef PNG_READ_16BIT_SUPPORTED +#ifdef PNG_READ_SWAP_SUPPORTED + if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0) + png_do_swap(row_info, png_ptr->row_buf + 1); +#endif +#endif + +#ifdef PNG_READ_USER_TRANSFORM_SUPPORTED + if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0) + { + if (png_ptr->read_user_transform_fn != NULL) + (*(png_ptr->read_user_transform_fn)) /* User read transform function */ + (png_ptr, /* png_ptr */ + row_info, /* row_info: */ + /* png_uint_32 width; width of row */ + /* png_size_t rowbytes; number of bytes in row */ + /* png_byte color_type; color type of pixels */ + /* png_byte bit_depth; bit depth of samples */ + /* png_byte channels; number of channels (1-4) */ + /* png_byte pixel_depth; bits per pixel (depth*channels) */ + png_ptr->row_buf + 1); /* start of pixel data for row */ +#ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED + if (png_ptr->user_transform_depth != 0) + row_info->bit_depth = png_ptr->user_transform_depth; + + if (png_ptr->user_transform_channels != 0) + row_info->channels = png_ptr->user_transform_channels; +#endif + row_info->pixel_depth = (png_byte)(row_info->bit_depth * + row_info->channels); + + row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_info->width); + } +#endif } -#endif /* PNG_MNG_FEATURES_SUPPORTED */ -#endif /* PNG_READ_SUPPORTED */ + +#endif /* READ_TRANSFORMS */ +#endif /* READ */ diff --git a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngrutil.c b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngrutil.c index 4a023090f87..68e5caff89c 100644 --- a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngrutil.c +++ b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngrutil.c @@ -29,8 +29,8 @@ * However, the following notice accompanied the original version of this * file and, per its terms, should not be removed: * - * Last changed in libpng 1.5.4 [July 7, 2011] - * Copyright (c) 1998-2011 Glenn Randers-Pehrson + * Last changed in libpng 1.6.15 [November 20, 2014] + * Copyright (c) 1998-2014 Glenn Randers-Pehrson * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) * @@ -46,10 +46,8 @@ #ifdef PNG_READ_SUPPORTED -#define png_strtod(p,a,b) strtod(a,b) - png_uint_32 PNGAPI -png_get_uint_31(png_structp png_ptr, png_const_bytep buf) +png_get_uint_31(png_const_structrp png_ptr, png_const_bytep buf) { png_uint_32 uval = png_get_uint_32(buf); @@ -68,7 +66,7 @@ png_get_uint_31(png_structp png_ptr, png_const_bytep buf) #define PNG_FIXED_ERROR (-1) static png_fixed_point /* PRIVATE */ -png_get_fixed_point(png_structp png_ptr, png_const_bytep buf) +png_get_fixed_point(png_structrp png_ptr, png_const_bytep buf) { png_uint_32 uval = png_get_uint_32(buf); @@ -115,10 +113,10 @@ png_int_32 (PNGAPI png_get_int_32)(png_const_bytep buf) { png_uint_32 uval = png_get_uint_32(buf); - if ((uval & 0x80000000L) == 0) /* non-negative */ + if ((uval & 0x80000000) == 0) /* non-negative */ return uval; - uval = (uval ^ 0xffffffffL) + 1; /* 2's complement: -x = ~x+1 */ + uval = (uval ^ 0xffffffff) + 1; /* 2's complement: -x = ~x+1 */ return -(png_int_32)uval; } @@ -126,7 +124,7 @@ png_get_int_32)(png_const_bytep buf) png_uint_16 (PNGAPI png_get_uint_16)(png_const_bytep buf) { - /* ANSI-C requires an int value to accommodate at least 16 bits so this + /* ANSI-C requires an int value to accomodate at least 16 bits so this * works and allows the compiler not to worry about possible narrowing * on 32 bit systems. (Pre-ANSI systems did not make integers smaller * than 16 bits either.) @@ -138,11 +136,11 @@ png_get_uint_16)(png_const_bytep buf) return (png_uint_16)val; } -#endif /* PNG_READ_INT_FUNCTIONS_SUPPORTED */ +#endif /* READ_INT_FUNCTIONS */ /* Read and check the PNG file signature */ void /* PRIVATE */ -png_read_sig(png_structp png_ptr, png_infop info_ptr) +png_read_sig(png_structrp png_ptr, png_inforp info_ptr) { png_size_t num_checked, num_to_check; @@ -161,7 +159,7 @@ png_read_sig(png_structp png_ptr, png_infop info_ptr) png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check); png_ptr->sig_bytes = 8; - if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check)) + if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check) != 0) { if (num_checked < 4 && png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4)) @@ -177,7 +175,7 @@ png_read_sig(png_structp png_ptr, png_infop info_ptr) * Put the type name into png_ptr->chunk_name, and return the length. */ png_uint_32 /* PRIVATE */ -png_read_chunk_header(png_structp png_ptr) +png_read_chunk_header(png_structrp png_ptr) { png_byte buf[8]; png_uint_32 length; @@ -193,14 +191,14 @@ png_read_chunk_header(png_structp png_ptr) length = png_get_uint_31(png_ptr, buf); /* Put the chunk name into png_ptr->chunk_name. */ - png_memcpy(png_ptr->chunk_name, buf + 4, 4); + png_ptr->chunk_name = PNG_CHUNK_FROM_STRING(buf+4); - png_debug2(0, "Reading %s chunk, length = %u", - png_ptr->chunk_name, length); + png_debug2(0, "Reading %lx chunk, length = %lu", + (unsigned long)png_ptr->chunk_name, (unsigned long)length); /* Reset the crc and run it over the chunk name. */ png_reset_crc(png_ptr); - png_calculate_crc(png_ptr, png_ptr->chunk_name, 4); + png_calculate_crc(png_ptr, buf + 4, 4); /* Check to see if chunk name is valid. */ png_check_chunk_name(png_ptr, png_ptr->chunk_name); @@ -214,7 +212,7 @@ png_read_chunk_header(png_structp png_ptr) /* Read data, and (optionally) run it through the CRC. */ void /* PRIVATE */ -png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length) +png_crc_read(png_structrp png_ptr, png_bytep buf, png_uint_32 length) { if (png_ptr == NULL) return; @@ -224,41 +222,40 @@ png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length) } /* Optionally skip data and then check the CRC. Depending on whether we - * are reading a ancillary or critical chunk, and how the program has set + * are reading an ancillary or critical chunk, and how the program has set * things up, we may calculate the CRC on the data and print a message. * Returns '1' if there was a CRC error, '0' otherwise. */ int /* PRIVATE */ -png_crc_finish(png_structp png_ptr, png_uint_32 skip) +png_crc_finish(png_structrp png_ptr, png_uint_32 skip) { - png_size_t i; - png_size_t istop = png_ptr->zbuf_size; - - for (i = (png_size_t)skip; i > istop; i -= istop) + /* The size of the local buffer for inflate is a good guess as to a + * reasonable size to use for buffering reads from the application. + */ + while (skip > 0) { - png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size); + png_uint_32 len; + png_byte tmpbuf[PNG_INFLATE_BUF_SIZE]; + + len = (sizeof tmpbuf); + if (len > skip) + len = skip; + skip -= len; + + png_crc_read(png_ptr, tmpbuf, len); } - if (i) + if (png_crc_error(png_ptr) != 0) { - png_crc_read(png_ptr, png_ptr->zbuf, i); - } - - if (png_crc_error(png_ptr)) - { - if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */ - !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) || - (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */ - (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE))) + if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0 ? + (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0 : + (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE) != 0) { png_chunk_warning(png_ptr, "CRC error"); } else - { - png_chunk_benign_error(png_ptr, "CRC error"); - return (0); - } + png_chunk_error(png_ptr, "CRC error"); return (1); } @@ -270,22 +267,22 @@ png_crc_finish(png_structp png_ptr, png_uint_32 skip) * the data it has read thus far. */ int /* PRIVATE */ -png_crc_error(png_structp png_ptr) +png_crc_error(png_structrp png_ptr) { png_byte crc_bytes[4]; png_uint_32 crc; int need_crc = 1; - if (png_ptr->chunk_name[0] & 0x20) /* ancillary */ + if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0) { if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) == (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN)) need_crc = 0; } - else /* critical */ + else /* critical */ { - if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) + if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0) need_crc = 0; } @@ -296,7 +293,7 @@ png_crc_error(png_structp png_ptr) /* The chunk CRC must be serialized in a single I/O call. */ png_read_data(png_ptr, crc_bytes, 4); - if (need_crc) + if (need_crc != 0) { crc = png_get_uint_32(crc_bytes); return ((int)(crc != png_ptr->crc)); @@ -306,252 +303,522 @@ png_crc_error(png_structp png_ptr) return (0); } -#ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED -static png_size_t -png_inflate(png_structp png_ptr, png_bytep data, png_size_t size, - png_bytep output, png_size_t output_size) +#if defined(PNG_READ_iCCP_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) ||\ + defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_READ_sCAL_SUPPORTED) ||\ + defined(PNG_READ_sPLT_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) ||\ + defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_SEQUENTIAL_READ_SUPPORTED) +/* Manage the read buffer; this simply reallocates the buffer if it is not small + * enough (or if it is not allocated). The routine returns a pointer to the + * buffer; if an error occurs and 'warn' is set the routine returns NULL, else + * it will call png_error (via png_malloc) on failure. (warn == 2 means + * 'silent'). + */ +static png_bytep +png_read_buffer(png_structrp png_ptr, png_alloc_size_t new_size, int warn) { - png_size_t count = 0; + png_bytep buffer = png_ptr->read_buffer; - /* zlib can't necessarily handle more than 65535 bytes at once (i.e. it can't - * even necessarily handle 65536 bytes) because the type uInt is "16 bits or - * more". Consequently it is necessary to chunk the input to zlib. This - * code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the maximum value - * that can be stored in a uInt.) It is possible to set ZLIB_IO_MAX to a - * lower value in pngpriv.h and this may sometimes have a performance - * advantage, because it forces access of the input data to be separated from - * at least some of the use by some period of time. - */ - png_ptr->zstream.next_in = data; - /* avail_in is set below from 'size' */ - png_ptr->zstream.avail_in = 0; - - while (1) + if (buffer != NULL && new_size > png_ptr->read_buffer_size) { - int ret, avail; + png_ptr->read_buffer = NULL; + png_ptr->read_buffer = NULL; + png_ptr->read_buffer_size = 0; + png_free(png_ptr, buffer); + buffer = NULL; + } - /* The setting of 'avail_in' used to be outside the loop, by setting it - * inside it is possible to chunk the input to zlib and simply rely on - * zlib to advance the 'next_in' pointer. This allows arbitrary amounts o - * data to be passed through zlib at the unavoidable cost of requiring a - * window save (memcpy of up to 32768 output bytes) every ZLIB_IO_MAX - * input bytes. - */ - if (png_ptr->zstream.avail_in == 0 && size > 0) + if (buffer == NULL) + { + buffer = png_voidcast(png_bytep, png_malloc_base(png_ptr, new_size)); + + if (buffer != NULL) { - if (size <= ZLIB_IO_MAX) - { - /* The value is less than ZLIB_IO_MAX so the cast is safe: */ - png_ptr->zstream.avail_in = (uInt)size; - size = 0; - } - - else - { - png_ptr->zstream.avail_in = ZLIB_IO_MAX; - size -= ZLIB_IO_MAX; - } + png_ptr->read_buffer = buffer; + png_ptr->read_buffer_size = new_size; } - /* Reset the output buffer each time round - we empty it - * after every inflate call. - */ - png_ptr->zstream.next_out = png_ptr->zbuf; - png_ptr->zstream.avail_out = png_ptr->zbuf_size; - - ret = inflate(&png_ptr->zstream, Z_NO_FLUSH); - avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out; - - /* First copy/count any new output - but only if we didn't - * get an error code. - */ - if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0) + else if (warn < 2) /* else silent */ { - png_size_t space = avail; /* > 0, see above */ + if (warn != 0) + png_chunk_warning(png_ptr, "insufficient memory to read chunk"); - if (output != 0 && output_size > count) - { - png_size_t copy = output_size - count; + else + png_chunk_error(png_ptr, "insufficient memory to read chunk"); + } + } - if (space < copy) - copy = space; + return buffer; +} +#endif /* READ_iCCP|iTXt|pCAL|sCAL|sPLT|tEXt|zTXt|SEQUENTIAL_READ */ - png_memcpy(output + count, png_ptr->zbuf, copy); - } - count += space; +/* png_inflate_claim: claim the zstream for some nefarious purpose that involves + * decompression. Returns Z_OK on success, else a zlib error code. It checks + * the owner but, in final release builds, just issues a warning if some other + * chunk apparently owns the stream. Prior to release it does a png_error. + */ +static int +png_inflate_claim(png_structrp png_ptr, png_uint_32 owner) +{ + if (png_ptr->zowner != 0) + { + char msg[64]; + + PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner); + /* So the message that results is " using zstream"; this is an + * internal error, but is very useful for debugging. i18n requirements + * are minimal. + */ + (void)png_safecat(msg, (sizeof msg), 4, " using zstream"); +#if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC + png_chunk_warning(png_ptr, msg); + png_ptr->zowner = 0; +#else + png_chunk_error(png_ptr, msg); +#endif + } + + /* Implementation note: unlike 'png_deflate_claim' this internal function + * does not take the size of the data as an argument. Some efficiency could + * be gained by using this when it is known *if* the zlib stream itself does + * not record the number; however, this is an illusion: the original writer + * of the PNG may have selected a lower window size, and we really must + * follow that because, for systems with with limited capabilities, we + * would otherwise reject the application's attempts to use a smaller window + * size (zlib doesn't have an interface to say "this or lower"!). + * + * inflateReset2 was added to zlib 1.2.4; before this the window could not be + * reset, therefore it is necessary to always allocate the maximum window + * size with earlier zlibs just in case later compressed chunks need it. + */ + { + int ret; /* zlib return code */ +#if PNG_ZLIB_VERNUM >= 0x1240 + +# if defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_MAXIMUM_INFLATE_WINDOW) + int window_bits; + + if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) == + PNG_OPTION_ON) + window_bits = 15; + + else + window_bits = 0; +# else +# define window_bits 0 +# endif +#endif + + /* Set this for safety, just in case the previous owner left pointers to + * memory allocations. + */ + png_ptr->zstream.next_in = NULL; + png_ptr->zstream.avail_in = 0; + png_ptr->zstream.next_out = NULL; + png_ptr->zstream.avail_out = 0; + + if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0) + { +#if PNG_ZLIB_VERNUM < 0x1240 + ret = inflateReset(&png_ptr->zstream); +#else + ret = inflateReset2(&png_ptr->zstream, window_bits); +#endif + } + + else + { +#if PNG_ZLIB_VERNUM < 0x1240 + ret = inflateInit(&png_ptr->zstream); +#else + ret = inflateInit2(&png_ptr->zstream, window_bits); +#endif + + if (ret == Z_OK) + png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED; } if (ret == Z_OK) - continue; + png_ptr->zowner = owner; - /* Termination conditions - always reset the zstream, it - * must be left in inflateInit state. + else + png_zstream_error(png_ptr, ret); + + return ret; + } + +#ifdef window_bits +# undef window_bits +#endif +} + +#ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED +/* png_inflate now returns zlib error codes including Z_OK and Z_STREAM_END to + * allow the caller to do multiple calls if required. If the 'finish' flag is + * set Z_FINISH will be passed to the final inflate() call and Z_STREAM_END must + * be returned or there has been a problem, otherwise Z_SYNC_FLUSH is used and + * Z_OK or Z_STREAM_END will be returned on success. + * + * The input and output sizes are updated to the actual amounts of data consumed + * or written, not the amount available (as in a z_stream). The data pointers + * are not changed, so the next input is (data+input_size) and the next + * available output is (output+output_size). + */ +static int +png_inflate(png_structrp png_ptr, png_uint_32 owner, int finish, + /* INPUT: */ png_const_bytep input, png_uint_32p input_size_ptr, + /* OUTPUT: */ png_bytep output, png_alloc_size_t *output_size_ptr) +{ + if (png_ptr->zowner == owner) /* Else not claimed */ + { + int ret; + png_alloc_size_t avail_out = *output_size_ptr; + png_uint_32 avail_in = *input_size_ptr; + + /* zlib can't necessarily handle more than 65535 bytes at once (i.e. it + * can't even necessarily handle 65536 bytes) because the type uInt is + * "16 bits or more". Consequently it is necessary to chunk the input to + * zlib. This code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the + * maximum value that can be stored in a uInt.) It is possible to set + * ZLIB_IO_MAX to a lower value in pngpriv.h and this may sometimes have + * a performance advantage, because it reduces the amount of data accessed + * at each step and that may give the OS more time to page it in. */ + png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input); + /* avail_in and avail_out are set below from 'size' */ png_ptr->zstream.avail_in = 0; - inflateReset(&png_ptr->zstream); + png_ptr->zstream.avail_out = 0; - if (ret == Z_STREAM_END) - return count; /* NOTE: may be zero. */ - - /* Now handle the error codes - the API always returns 0 - * and the error message is dumped into the uncompressed - * buffer if available. + /* Read directly into the output if it is available (this is set to + * a local buffer below if output is NULL). */ -# ifdef PNG_WARNINGS_SUPPORTED + if (output != NULL) + png_ptr->zstream.next_out = output; + + do { - png_const_charp msg; + uInt avail; + Byte local_buffer[PNG_INFLATE_BUF_SIZE]; - if (png_ptr->zstream.msg != 0) - msg = png_ptr->zstream.msg; + /* zlib INPUT BUFFER */ + /* The setting of 'avail_in' used to be outside the loop; by setting it + * inside it is possible to chunk the input to zlib and simply rely on + * zlib to advance the 'next_in' pointer. This allows arbitrary + * amounts of data to be passed through zlib at the unavoidable cost of + * requiring a window save (memcpy of up to 32768 output bytes) + * every ZLIB_IO_MAX input bytes. + */ + avail_in += png_ptr->zstream.avail_in; /* not consumed last time */ - else switch (ret) + avail = ZLIB_IO_MAX; + + if (avail_in < avail) + avail = (uInt)avail_in; /* safe: < than ZLIB_IO_MAX */ + + avail_in -= avail; + png_ptr->zstream.avail_in = avail; + + /* zlib OUTPUT BUFFER */ + avail_out += png_ptr->zstream.avail_out; /* not written last time */ + + avail = ZLIB_IO_MAX; /* maximum zlib can process */ + + if (output == NULL) { - case Z_BUF_ERROR: - msg = "Buffer error in compressed datastream"; - break; - - case Z_DATA_ERROR: - msg = "Data error in compressed datastream"; - break; - - default: - msg = "Incomplete compressed datastream"; - break; + /* Reset the output buffer each time round if output is NULL and + * make available the full buffer, up to 'remaining_space' + */ + png_ptr->zstream.next_out = local_buffer; + if ((sizeof local_buffer) < avail) + avail = (sizeof local_buffer); } - png_chunk_warning(png_ptr, msg); - } -# endif + if (avail_out < avail) + avail = (uInt)avail_out; /* safe: < ZLIB_IO_MAX */ - /* 0 means an error - notice that this code simply ignores - * zero length compressed chunks as a result. + png_ptr->zstream.avail_out = avail; + avail_out -= avail; + + /* zlib inflate call */ + /* In fact 'avail_out' may be 0 at this point, that happens at the end + * of the read when the final LZ end code was not passed at the end of + * the previous chunk of input data. Tell zlib if we have reached the + * end of the output buffer. + */ + ret = inflate(&png_ptr->zstream, avail_out > 0 ? Z_NO_FLUSH : + (finish ? Z_FINISH : Z_SYNC_FLUSH)); + } while (ret == Z_OK); + + /* For safety kill the local buffer pointer now */ + if (output == NULL) + png_ptr->zstream.next_out = NULL; + + /* Claw back the 'size' and 'remaining_space' byte counts. */ + avail_in += png_ptr->zstream.avail_in; + avail_out += png_ptr->zstream.avail_out; + + /* Update the input and output sizes; the updated values are the amount + * consumed or written, effectively the inverse of what zlib uses. */ - return 0; + if (avail_out > 0) + *output_size_ptr -= avail_out; + + if (avail_in > 0) + *input_size_ptr -= avail_in; + + /* Ensure png_ptr->zstream.msg is set (even in the success case!) */ + png_zstream_error(png_ptr, ret); + return ret; + } + + else + { + /* This is a bad internal error. The recovery assigns to the zstream msg + * pointer, which is not owned by the caller, but this is safe; it's only + * used on errors! + */ + png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed"); + return Z_STREAM_ERROR; } } /* - * Decompress trailing data in a chunk. The assumption is that chunkdata + * Decompress trailing data in a chunk. The assumption is that read_buffer * points at an allocated area holding the contents of a chunk with a * trailing compressed part. What we get back is an allocated area * holding the original prefix part and an uncompressed version of the * trailing part (the malloc area passed in is freed). */ -void /* PRIVATE */ -png_decompress_chunk(png_structp png_ptr, int comp_type, - png_size_t chunklength, - png_size_t prefix_size, png_size_t *newlength) +static int +png_decompress_chunk(png_structrp png_ptr, + png_uint_32 chunklength, png_uint_32 prefix_size, + png_alloc_size_t *newlength /* must be initialized to the maximum! */, + int terminate /*add a '\0' to the end of the uncompressed data*/) { - /* The caller should guarantee this */ - if (prefix_size > chunklength) + /* TODO: implement different limits for different types of chunk. + * + * The caller supplies *newlength set to the maximum length of the + * uncompressed data, but this routine allocates space for the prefix and + * maybe a '\0' terminator too. We have to assume that 'prefix_size' is + * limited only by the maximum chunk size. + */ + png_alloc_size_t limit = PNG_SIZE_MAX; + +# ifdef PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED + if (png_ptr->user_chunk_malloc_max > 0 && + png_ptr->user_chunk_malloc_max < limit) + limit = png_ptr->user_chunk_malloc_max; +# elif PNG_USER_CHUNK_MALLOC_MAX > 0 + if (PNG_USER_CHUNK_MALLOC_MAX < limit) + limit = PNG_USER_CHUNK_MALLOC_MAX; +# endif + + if (limit >= prefix_size + (terminate != 0)) { - /* The recovery is to delete the chunk. */ - png_warning(png_ptr, "invalid chunklength"); - prefix_size = 0; /* To delete everything */ - } + int ret; - else if (comp_type == PNG_COMPRESSION_TYPE_BASE) - { - png_size_t expanded_size = png_inflate(png_ptr, - (png_bytep)(png_ptr->chunkdata + prefix_size), - chunklength - prefix_size, - 0, /* output */ - 0); /* output size */ + limit -= prefix_size + (terminate != 0); - /* Now check the limits on this chunk - if the limit fails the - * compressed data will be removed, the prefix will remain. - */ -#ifdef PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED - if (png_ptr->user_chunk_malloc_max && - (prefix_size + expanded_size >= png_ptr->user_chunk_malloc_max - 1)) -#else -# ifdef PNG_USER_CHUNK_MALLOC_MAX - if ((PNG_USER_CHUNK_MALLOC_MAX > 0) && - prefix_size + expanded_size >= PNG_USER_CHUNK_MALLOC_MAX - 1) -# endif -#endif - png_warning(png_ptr, "Exceeded size limit while expanding chunk"); + if (limit < *newlength) + *newlength = limit; - /* If the size is zero either there was an error and a message - * has already been output (warning) or the size really is zero - * and we have nothing to do - the code will exit through the - * error case below. - */ -#if defined(PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED) || \ - defined(PNG_USER_CHUNK_MALLOC_MAX) - else if (expanded_size > 0) -#else - if (expanded_size > 0) -#endif + /* Now try to claim the stream. */ + ret = png_inflate_claim(png_ptr, png_ptr->chunk_name); + + if (ret == Z_OK) { - /* Success (maybe) - really uncompress the chunk. */ - png_size_t new_size = 0; - png_charp text = png_malloc_warn(png_ptr, - prefix_size + expanded_size + 1); + png_uint_32 lzsize = chunklength - prefix_size; - if (text != NULL) + ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/, + /* input: */ png_ptr->read_buffer + prefix_size, &lzsize, + /* output: */ NULL, newlength); + + if (ret == Z_STREAM_END) { - png_memcpy(text, png_ptr->chunkdata, prefix_size); - new_size = png_inflate(png_ptr, - (png_bytep)(png_ptr->chunkdata + prefix_size), - chunklength - prefix_size, - (png_bytep)(text + prefix_size), expanded_size); - text[prefix_size + expanded_size] = 0; /* just in case */ - - if (new_size == expanded_size) + /* Use 'inflateReset' here, not 'inflateReset2' because this + * preserves the previously decided window size (otherwise it would + * be necessary to store the previous window size.) In practice + * this doesn't matter anyway, because png_inflate will call inflate + * with Z_FINISH in almost all cases, so the window will not be + * maintained. + */ + if (inflateReset(&png_ptr->zstream) == Z_OK) { - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = text; - *newlength = prefix_size + expanded_size; - return; /* The success return! */ + /* Because of the limit checks above we know that the new, + * expanded, size will fit in a size_t (let alone an + * png_alloc_size_t). Use png_malloc_base here to avoid an + * extra OOM message. + */ + png_alloc_size_t new_size = *newlength; + png_alloc_size_t buffer_size = prefix_size + new_size + + (terminate != 0); + png_bytep text = png_voidcast(png_bytep, png_malloc_base(png_ptr, + buffer_size)); + + if (text != NULL) + { + ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/, + png_ptr->read_buffer + prefix_size, &lzsize, + text + prefix_size, newlength); + + if (ret == Z_STREAM_END) + { + if (new_size == *newlength) + { + if (terminate != 0) + text[prefix_size + *newlength] = 0; + + if (prefix_size > 0) + memcpy(text, png_ptr->read_buffer, prefix_size); + + { + png_bytep old_ptr = png_ptr->read_buffer; + + png_ptr->read_buffer = text; + png_ptr->read_buffer_size = buffer_size; + text = old_ptr; /* freed below */ + } + } + + else + { + /* The size changed on the second read, there can be no + * guarantee that anything is correct at this point. + * The 'msg' pointer has been set to "unexpected end of + * LZ stream", which is fine, but return an error code + * that the caller won't accept. + */ + ret = PNG_UNEXPECTED_ZLIB_RETURN; + } + } + + else if (ret == Z_OK) + ret = PNG_UNEXPECTED_ZLIB_RETURN; /* for safety */ + + /* Free the text pointer (this is the old read_buffer on + * success) + */ + png_free(png_ptr, text); + text = NULL; + + /* This really is very benign, but it's still an error because + * the extra space may otherwise be used as a Trojan Horse. + */ + if (ret == Z_STREAM_END && + chunklength - prefix_size != lzsize) + png_chunk_benign_error(png_ptr, "extra compressed data"); + } + + else + { + /* Out of memory allocating the buffer */ + ret = Z_MEM_ERROR; + png_zstream_error(png_ptr, Z_MEM_ERROR); + } } - png_warning(png_ptr, "png_inflate logic error"); - png_free(png_ptr, text); + else + { + /* inflateReset failed, store the error message */ + png_zstream_error(png_ptr, ret); + + if (ret == Z_STREAM_END) + ret = PNG_UNEXPECTED_ZLIB_RETURN; + } } - else - png_warning(png_ptr, "Not enough memory to decompress chunk"); + else if (ret == Z_OK) + ret = PNG_UNEXPECTED_ZLIB_RETURN; + + /* Release the claimed stream */ + png_ptr->zowner = 0; } + + else /* the claim failed */ if (ret == Z_STREAM_END) /* impossible! */ + ret = PNG_UNEXPECTED_ZLIB_RETURN; + + return ret; } - else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */ + else { - PNG_WARNING_PARAMETERS(p) - png_warning_parameter_signed(p, 1, PNG_NUMBER_FORMAT_d, comp_type); - png_formatted_warning(png_ptr, p, "Unknown zTXt compression type @1"); - - /* The recovery is to simply drop the data. */ + /* Application/configuration limits exceeded */ + png_zstream_error(png_ptr, Z_MEM_ERROR); + return Z_MEM_ERROR; } - - /* Generic error return - leave the prefix, delete the compressed - * data, reallocate the chunkdata to remove the potentially large - * amount of compressed data. - */ - { - png_charp text = png_malloc_warn(png_ptr, prefix_size + 1); - - if (text != NULL) - { - if (prefix_size > 0) - png_memcpy(text, png_ptr->chunkdata, prefix_size); - - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = text; - - /* This is an extra zero in the 'uncompressed' part. */ - *(png_ptr->chunkdata + prefix_size) = 0x00; - } - /* Ignore a malloc error here - it is safe. */ - } - - *newlength = prefix_size; } -#endif /* PNG_READ_COMPRESSED_TEXT_SUPPORTED */ +#endif /* READ_COMPRESSED_TEXT */ + +#ifdef PNG_READ_iCCP_SUPPORTED +/* Perform a partial read and decompress, producing 'avail_out' bytes and + * reading from the current chunk as required. + */ +static int +png_inflate_read(png_structrp png_ptr, png_bytep read_buffer, uInt read_size, + png_uint_32p chunk_bytes, png_bytep next_out, png_alloc_size_t *out_size, + int finish) +{ + if (png_ptr->zowner == png_ptr->chunk_name) + { + int ret; + + /* next_in and avail_in must have been initialized by the caller. */ + png_ptr->zstream.next_out = next_out; + png_ptr->zstream.avail_out = 0; /* set in the loop */ + + do + { + if (png_ptr->zstream.avail_in == 0) + { + if (read_size > *chunk_bytes) + read_size = (uInt)*chunk_bytes; + *chunk_bytes -= read_size; + + if (read_size > 0) + png_crc_read(png_ptr, read_buffer, read_size); + + png_ptr->zstream.next_in = read_buffer; + png_ptr->zstream.avail_in = read_size; + } + + if (png_ptr->zstream.avail_out == 0) + { + uInt avail = ZLIB_IO_MAX; + if (avail > *out_size) + avail = (uInt)*out_size; + *out_size -= avail; + + png_ptr->zstream.avail_out = avail; + } + + /* Use Z_SYNC_FLUSH when there is no more chunk data to ensure that all + * the available output is produced; this allows reading of truncated + * streams. + */ + ret = inflate(&png_ptr->zstream, + *chunk_bytes > 0 ? Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH)); + } + while (ret == Z_OK && (*out_size > 0 || png_ptr->zstream.avail_out > 0)); + + *out_size += png_ptr->zstream.avail_out; + png_ptr->zstream.avail_out = 0; /* Should not be required, but is safe */ + + /* Ensure the error message pointer is always set: */ + png_zstream_error(png_ptr, ret); + return ret; + } + + else + { + png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed"); + return Z_STREAM_ERROR; + } +} +#endif /* Read and check the IDHR chunk */ + void /* PRIVATE */ -png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_IHDR(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[13]; png_uint_32 width, height; @@ -560,12 +827,12 @@ png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) png_debug(1, "in png_handle_IHDR"); - if (png_ptr->mode & PNG_HAVE_IHDR) - png_error(png_ptr, "Out of place IHDR"); + if ((png_ptr->mode & PNG_HAVE_IHDR) != 0) + png_chunk_error(png_ptr, "out of place"); /* Check the length */ if (length != 13) - png_error(png_ptr, "Invalid IHDR chunk"); + png_chunk_error(png_ptr, "invalid"); png_ptr->mode |= PNG_HAVE_IHDR; @@ -614,8 +881,7 @@ png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) } /* Set up other useful info */ - png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth * - png_ptr->channels); + png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth * png_ptr->channels); png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->width); png_debug1(3, "bit_depth = %d", png_ptr->bit_depth); png_debug1(3, "channels = %d", png_ptr->channels); @@ -626,7 +892,7 @@ png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) /* Read and check the palette */ void /* PRIVATE */ -png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_color palette[PNG_MAX_PALETTE_LENGTH]; int num, i; @@ -636,26 +902,33 @@ png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) png_debug(1, "in png_handle_PLTE"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before PLTE"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (png_ptr->mode & PNG_HAVE_IDAT) + /* Moved to before the 'after IDAT' check below because otherwise duplicate + * PLTE chunks are potentially ignored (the spec says there shall not be more + * than one PLTE, the error is not treated as benign, so this check trumps + * the requirement that PLTE appears before IDAT.) + */ + else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0) + png_chunk_error(png_ptr, "duplicate"); + + else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { - png_warning(png_ptr, "Invalid PLTE after IDAT"); + /* This is benign because the non-benign error happened before, when an + * IDAT was encountered in a color-mapped image with no PLTE. + */ png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } - else if (png_ptr->mode & PNG_HAVE_PLTE) - png_error(png_ptr, "Duplicate PLTE chunk"); - png_ptr->mode |= PNG_HAVE_PLTE; - if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR)) + if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) { - png_warning(png_ptr, - "Ignoring PLTE chunk in grayscale PNG"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "ignored in grayscale PNG"); return; } @@ -669,19 +942,18 @@ png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3) { + png_crc_finish(png_ptr, length); + if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) - { - png_warning(png_ptr, "Invalid palette chunk"); - png_crc_finish(png_ptr, length); - return; - } + png_chunk_benign_error(png_ptr, "invalid"); else - { - png_error(png_ptr, "Invalid palette chunk"); - } + png_chunk_error(png_ptr, "invalid"); + + return; } + /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */ num = (int)length / 3; #ifdef PNG_POINTER_INDEXING_SUPPORTED @@ -720,214 +992,196 @@ png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) } #ifndef PNG_READ_OPT_PLTE_SUPPORTED - else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */ + else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */ { /* If we don't want to use the data from an ancillary chunk, * we have two options: an error abort, or a warning and we * ignore the data in this chunk (which should be OK, since * it's considered ancillary for a RGB or RGBA image). + * + * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the + * chunk type to determine whether to check the ancillary or the critical + * flags. */ - if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE)) + if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0) { - if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) - { - png_chunk_benign_error(png_ptr, "CRC error"); - } + if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0) + return; else - { - png_chunk_warning(png_ptr, "CRC error"); - return; - } + png_chunk_error(png_ptr, "CRC error"); } /* Otherwise, we (optionally) emit a warning and use the chunk. */ - else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) - { + else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0) png_chunk_warning(png_ptr, "CRC error"); - } } #endif + /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its + * own copy of the palette. This has the side effect that when png_start_row + * is called (this happens after any call to png_read_update_info) the + * info_ptr palette gets changed. This is extremely unexpected and + * confusing. + * + * Fix this by not sharing the palette in this way. + */ png_set_PLTE(png_ptr, info_ptr, palette, num); + /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before + * IDAT. Prior to 1.6.0 this was not checked; instead the code merely + * checked the apparent validity of a tRNS chunk inserted before PLTE on a + * palette PNG. 1.6.0 attempts to rigorously follow the standard and + * therefore does a benign error if the erroneous condition is detected *and* + * cancels the tRNS if the benign error returns. The alternative is to + * amend the standard since it would be rather hypocritical of the standards + * maintainers to ignore it. + */ #ifdef PNG_READ_tRNS_SUPPORTED - if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + if (png_ptr->num_trans > 0 || + (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0)) { - if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS)) - { - if (png_ptr->num_trans > (png_uint_16)num) - { - png_warning(png_ptr, "Truncating incorrect tRNS chunk length"); - png_ptr->num_trans = (png_uint_16)num; - } + /* Cancel this because otherwise it would be used if the transforms + * require it. Don't cancel the 'valid' flag because this would prevent + * detection of duplicate chunks. + */ + png_ptr->num_trans = 0; - if (info_ptr->num_trans > (png_uint_16)num) - { - png_warning(png_ptr, "Truncating incorrect info tRNS chunk length"); - info_ptr->num_trans = (png_uint_16)num; - } - } + if (info_ptr != NULL) + info_ptr->num_trans = 0; + + png_chunk_benign_error(png_ptr, "tRNS must be after"); } #endif +#ifdef PNG_READ_hIST_SUPPORTED + if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0) + png_chunk_benign_error(png_ptr, "hIST must be after"); +#endif + +#ifdef PNG_READ_bKGD_SUPPORTED + if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0) + png_chunk_benign_error(png_ptr, "bKGD must be after"); +#endif } void /* PRIVATE */ -png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_IEND(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_debug(1, "in png_handle_IEND"); - if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT)) - { - png_error(png_ptr, "No image in file"); - } + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0 || + (png_ptr->mode & PNG_HAVE_IDAT) == 0) + png_chunk_error(png_ptr, "out of place"); png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND); - if (length != 0) - { - png_warning(png_ptr, "Incorrect IEND chunk length"); - } - png_crc_finish(png_ptr, length); - PNG_UNUSED(info_ptr) /* Quiet compiler warnings about unused info_ptr */ + if (length != 0) + png_chunk_benign_error(png_ptr, "invalid"); + + PNG_UNUSED(info_ptr) } #ifdef PNG_READ_gAMA_SUPPORTED void /* PRIVATE */ -png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_gAMA(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_fixed_point igamma; png_byte buf[4]; png_debug(1, "in png_handle_gAMA"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before gAMA"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (png_ptr->mode & PNG_HAVE_IDAT) + else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { - png_warning(png_ptr, "Invalid gAMA after IDAT"); - png_crc_finish(png_ptr, length); - return; - } - - else if (png_ptr->mode & PNG_HAVE_PLTE) - /* Should be an error, but we can cope with it */ - png_warning(png_ptr, "Out of place gAMA chunk"); - - if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA) -#ifdef PNG_READ_sRGB_SUPPORTED - && !(info_ptr->valid & PNG_INFO_sRGB) -#endif - ) - { - png_warning(png_ptr, "Duplicate gAMA chunk"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } if (length != 4) { - png_warning(png_ptr, "Incorrect gAMA chunk length"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 4); - if (png_crc_finish(png_ptr, 0)) + if (png_crc_finish(png_ptr, 0) != 0) return; igamma = png_get_fixed_point(NULL, buf); - /* Check for zero gamma or an error. */ - if (igamma <= 0) - { - png_warning(png_ptr, - "Ignoring gAMA chunk with out of range gamma"); - - return; - } - -# ifdef PNG_READ_sRGB_SUPPORTED - if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)) - { - if (PNG_OUT_OF_RANGE(igamma, 45500L, 500)) - { - PNG_WARNING_PARAMETERS(p) - png_warning_parameter_signed(p, 1, PNG_NUMBER_FORMAT_fixed, igamma); - png_formatted_warning(png_ptr, p, - "Ignoring incorrect gAMA value @1 when sRGB is also present"); - return; - } - } -# endif /* PNG_READ_sRGB_SUPPORTED */ - -# ifdef PNG_READ_GAMMA_SUPPORTED - /* Gamma correction on read is supported. */ - png_ptr->gamma = igamma; -# endif - /* And set the 'info' structure members. */ - png_set_gAMA_fixed(png_ptr, info_ptr, igamma); + png_colorspace_set_gamma(png_ptr, &png_ptr->colorspace, igamma); + png_colorspace_sync(png_ptr, info_ptr); } #endif #ifdef PNG_READ_sBIT_SUPPORTED void /* PRIVATE */ -png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { - png_size_t truelen; + unsigned int truelen, i; + png_byte sample_depth; png_byte buf[4]; png_debug(1, "in png_handle_sBIT"); - buf[0] = buf[1] = buf[2] = buf[3] = 0; + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before sBIT"); - - else if (png_ptr->mode & PNG_HAVE_IDAT) + else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { - png_warning(png_ptr, "Invalid sBIT after IDAT"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } - else if (png_ptr->mode & PNG_HAVE_PLTE) + if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT) != 0) { - /* Should be an error, but we can cope with it */ - png_warning(png_ptr, "Out of place sBIT chunk"); - } - - if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)) - { - png_warning(png_ptr, "Duplicate sBIT chunk"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "duplicate"); return; } if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + { truelen = 3; + sample_depth = 8; + } else - truelen = (png_size_t)png_ptr->channels; + { + truelen = png_ptr->channels; + sample_depth = png_ptr->bit_depth; + } if (length != truelen || length > 4) { - png_warning(png_ptr, "Incorrect sBIT chunk length"); + png_chunk_benign_error(png_ptr, "invalid"); png_crc_finish(png_ptr, length); return; } + buf[0] = buf[1] = buf[2] = buf[3] = sample_depth; png_crc_read(png_ptr, buf, truelen); - if (png_crc_finish(png_ptr, 0)) + if (png_crc_finish(png_ptr, 0) != 0) return; - if (png_ptr->color_type & PNG_COLOR_MASK_COLOR) + for (i=0; i sample_depth) + { + png_chunk_benign_error(png_ptr, "invalid"); + return; + } + + if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0) { png_ptr->sig_bit.red = buf[0]; png_ptr->sig_bit.green = buf[1]; @@ -950,377 +1204,416 @@ png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) #ifdef PNG_READ_cHRM_SUPPORTED void /* PRIVATE */ -png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_cHRM(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[32]; - png_fixed_point x_white, y_white, x_red, y_red, x_green, y_green, x_blue, - y_blue; + png_xy xy; png_debug(1, "in png_handle_cHRM"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before cHRM"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (png_ptr->mode & PNG_HAVE_IDAT) + else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { - png_warning(png_ptr, "Invalid cHRM after IDAT"); - png_crc_finish(png_ptr, length); - return; - } - - else if (png_ptr->mode & PNG_HAVE_PLTE) - /* Should be an error, but we can cope with it */ - png_warning(png_ptr, "Missing PLTE before cHRM"); - - if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM) -# ifdef PNG_READ_sRGB_SUPPORTED - && !(info_ptr->valid & PNG_INFO_sRGB) -# endif - ) - { - png_warning(png_ptr, "Duplicate cHRM chunk"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } if (length != 32) { - png_warning(png_ptr, "Incorrect cHRM chunk length"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 32); - if (png_crc_finish(png_ptr, 0)) + if (png_crc_finish(png_ptr, 0) != 0) return; - x_white = png_get_fixed_point(NULL, buf); - y_white = png_get_fixed_point(NULL, buf + 4); - x_red = png_get_fixed_point(NULL, buf + 8); - y_red = png_get_fixed_point(NULL, buf + 12); - x_green = png_get_fixed_point(NULL, buf + 16); - y_green = png_get_fixed_point(NULL, buf + 20); - x_blue = png_get_fixed_point(NULL, buf + 24); - y_blue = png_get_fixed_point(NULL, buf + 28); + xy.whitex = png_get_fixed_point(NULL, buf); + xy.whitey = png_get_fixed_point(NULL, buf + 4); + xy.redx = png_get_fixed_point(NULL, buf + 8); + xy.redy = png_get_fixed_point(NULL, buf + 12); + xy.greenx = png_get_fixed_point(NULL, buf + 16); + xy.greeny = png_get_fixed_point(NULL, buf + 20); + xy.bluex = png_get_fixed_point(NULL, buf + 24); + xy.bluey = png_get_fixed_point(NULL, buf + 28); - if (x_white == PNG_FIXED_ERROR || - y_white == PNG_FIXED_ERROR || - x_red == PNG_FIXED_ERROR || - y_red == PNG_FIXED_ERROR || - x_green == PNG_FIXED_ERROR || - y_green == PNG_FIXED_ERROR || - x_blue == PNG_FIXED_ERROR || - y_blue == PNG_FIXED_ERROR) + if (xy.whitex == PNG_FIXED_ERROR || + xy.whitey == PNG_FIXED_ERROR || + xy.redx == PNG_FIXED_ERROR || + xy.redy == PNG_FIXED_ERROR || + xy.greenx == PNG_FIXED_ERROR || + xy.greeny == PNG_FIXED_ERROR || + xy.bluex == PNG_FIXED_ERROR || + xy.bluey == PNG_FIXED_ERROR) { - png_warning(png_ptr, "Ignoring cHRM chunk with negative chromaticities"); + png_chunk_benign_error(png_ptr, "invalid values"); return; } -#ifdef PNG_READ_sRGB_SUPPORTED - if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB)) + /* If a colorspace error has already been output skip this chunk */ + if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0) + return; + + if ((png_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0) { - if (PNG_OUT_OF_RANGE(x_white, 31270, 1000) || - PNG_OUT_OF_RANGE(y_white, 32900, 1000) || - PNG_OUT_OF_RANGE(x_red, 64000L, 1000) || - PNG_OUT_OF_RANGE(y_red, 33000, 1000) || - PNG_OUT_OF_RANGE(x_green, 30000, 1000) || - PNG_OUT_OF_RANGE(y_green, 60000L, 1000) || - PNG_OUT_OF_RANGE(x_blue, 15000, 1000) || - PNG_OUT_OF_RANGE(y_blue, 6000, 1000)) - { - PNG_WARNING_PARAMETERS(p) - - png_warning_parameter_signed(p, 1, PNG_NUMBER_FORMAT_fixed, x_white); - png_warning_parameter_signed(p, 2, PNG_NUMBER_FORMAT_fixed, y_white); - png_warning_parameter_signed(p, 3, PNG_NUMBER_FORMAT_fixed, x_red); - png_warning_parameter_signed(p, 4, PNG_NUMBER_FORMAT_fixed, y_red); - png_warning_parameter_signed(p, 5, PNG_NUMBER_FORMAT_fixed, x_green); - png_warning_parameter_signed(p, 6, PNG_NUMBER_FORMAT_fixed, y_green); - png_warning_parameter_signed(p, 7, PNG_NUMBER_FORMAT_fixed, x_blue); - png_warning_parameter_signed(p, 8, PNG_NUMBER_FORMAT_fixed, y_blue); - - png_formatted_warning(png_ptr, p, - "Ignoring incorrect cHRM white(@1,@2) r(@3,@4)g(@5,@6)b(@7,@8) " - "when sRGB is also present"); - } + png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID; + png_colorspace_sync(png_ptr, info_ptr); + png_chunk_benign_error(png_ptr, "duplicate"); return; } -#endif /* PNG_READ_sRGB_SUPPORTED */ -#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED - /* Store the _white values as default coefficients for the rgb to gray - * operation if it is supported. - */ - if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == 0) - { - /* png_set_background has not been called, the coefficients must be in - * range for the following to work without overflow. - */ - if (y_red <= (1<<17) && y_green <= (1<<17) && y_blue <= (1<<17)) - { - /* The y values are chromaticities: Y/X+Y+Z, the weights for the gray - * transformation are simply the normalized Y values for red, green and - * blue scaled by 32768. - */ - png_uint_32 w = y_red + y_green + y_blue; - - png_ptr->rgb_to_gray_red_coeff = (png_uint_16)(((png_uint_32)y_red * - 32768)/w); - png_ptr->rgb_to_gray_green_coeff = (png_uint_16)(((png_uint_32)y_green - * 32768)/w); - png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(((png_uint_32)y_blue * - 32768)/w); - } - } -#endif - - png_set_cHRM_fixed(png_ptr, info_ptr, x_white, y_white, x_red, y_red, - x_green, y_green, x_blue, y_blue); + png_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM; + (void)png_colorspace_set_chromaticities(png_ptr, &png_ptr->colorspace, &xy, + 1/*prefer cHRM values*/); + png_colorspace_sync(png_ptr, info_ptr); } #endif #ifdef PNG_READ_sRGB_SUPPORTED void /* PRIVATE */ -png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_sRGB(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { - int intent; - png_byte buf[1]; + png_byte intent; png_debug(1, "in png_handle_sRGB"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before sRGB"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (png_ptr->mode & PNG_HAVE_IDAT) + else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { - png_warning(png_ptr, "Invalid sRGB after IDAT"); - png_crc_finish(png_ptr, length); - return; - } - - else if (png_ptr->mode & PNG_HAVE_PLTE) - /* Should be an error, but we can cope with it */ - png_warning(png_ptr, "Out of place sRGB chunk"); - - if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)) - { - png_warning(png_ptr, "Duplicate sRGB chunk"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } if (length != 1) { - png_warning(png_ptr, "Incorrect sRGB chunk length"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid"); return; } - png_crc_read(png_ptr, buf, 1); + png_crc_read(png_ptr, &intent, 1); - if (png_crc_finish(png_ptr, 0)) + if (png_crc_finish(png_ptr, 0) != 0) return; - intent = buf[0]; + /* If a colorspace error has already been output skip this chunk */ + if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0) + return; - /* Check for bad intent */ - if (intent >= PNG_sRGB_INTENT_LAST) + /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect + * this. + */ + if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) != 0) { - png_warning(png_ptr, "Unknown sRGB intent"); + png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID; + png_colorspace_sync(png_ptr, info_ptr); + png_chunk_benign_error(png_ptr, "too many profiles"); return; } -#if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED) - if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)) - { - if (PNG_OUT_OF_RANGE(info_ptr->gamma, 45500L, 500)) - { - PNG_WARNING_PARAMETERS(p) - - png_warning_parameter_signed(p, 1, PNG_NUMBER_FORMAT_fixed, - info_ptr->gamma); - - png_formatted_warning(png_ptr, p, - "Ignoring incorrect gAMA value @1 when sRGB is also present"); - } - } -#endif /* PNG_READ_gAMA_SUPPORTED */ - -#ifdef PNG_READ_cHRM_SUPPORTED - if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)) - if (PNG_OUT_OF_RANGE(info_ptr->x_white, 31270, 1000) || - PNG_OUT_OF_RANGE(info_ptr->y_white, 32900, 1000) || - PNG_OUT_OF_RANGE(info_ptr->x_red, 64000L, 1000) || - PNG_OUT_OF_RANGE(info_ptr->y_red, 33000, 1000) || - PNG_OUT_OF_RANGE(info_ptr->x_green, 30000, 1000) || - PNG_OUT_OF_RANGE(info_ptr->y_green, 60000L, 1000) || - PNG_OUT_OF_RANGE(info_ptr->x_blue, 15000, 1000) || - PNG_OUT_OF_RANGE(info_ptr->y_blue, 6000, 1000)) - { - png_warning(png_ptr, - "Ignoring incorrect cHRM value when sRGB is also present"); - } -#endif /* PNG_READ_cHRM_SUPPORTED */ - - png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent); + (void)png_colorspace_set_sRGB(png_ptr, &png_ptr->colorspace, intent); + png_colorspace_sync(png_ptr, info_ptr); } -#endif /* PNG_READ_sRGB_SUPPORTED */ +#endif /* READ_sRGB */ #ifdef PNG_READ_iCCP_SUPPORTED void /* PRIVATE */ -png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) -/* Note: this does not properly handle chunks that are > 64K under DOS */ +png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) +/* Note: this does not properly handle profiles that are > 64K under DOS */ { - png_byte compression_type; - png_bytep pC; - png_charp profile; - png_uint_32 skip = 0; - png_uint_32 profile_size; - png_alloc_size_t profile_length; - png_size_t slength, prefix_length, data_length; + png_const_charp errmsg = NULL; /* error message output, or no error */ + int finished = 0; /* crc checked */ png_debug(1, "in png_handle_iCCP"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before iCCP"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (png_ptr->mode & PNG_HAVE_IDAT) + else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) + { + png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); + return; + } + + /* Consistent with all the above colorspace handling an obviously *invalid* + * chunk is just ignored, so does not invalidate the color space. An + * alternative is to set the 'invalid' flags at the start of this routine + * and only clear them in they were not set before and all the tests pass. + * The minimum 'deflate' stream is assumed to be just the 2 byte header and + * 4 byte checksum. The keyword must be at least one character and there is + * a terminator (0) byte and the compression method. + */ + if (length < 9) + { + png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "too short"); + return; + } + + /* If a colorspace error has already been output skip this chunk */ + if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0) { - png_warning(png_ptr, "Invalid iCCP after IDAT"); png_crc_finish(png_ptr, length); return; } - else if (png_ptr->mode & PNG_HAVE_PLTE) - /* Should be an error, but we can cope with it */ - png_warning(png_ptr, "Out of place iCCP chunk"); - - if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)) + /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect + * this. + */ + if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) == 0) { - png_warning(png_ptr, "Duplicate iCCP chunk"); + uInt read_length, keyword_length; + char keyword[81]; + + /* Find the keyword; the keyword plus separator and compression method + * bytes can be at most 81 characters long. + */ + read_length = 81; /* maximum */ + if (read_length > length) + read_length = (uInt)length; + + png_crc_read(png_ptr, (png_bytep)keyword, read_length); + length -= read_length; + + keyword_length = 0; + while (keyword_length < 80 && keyword_length < read_length && + keyword[keyword_length] != 0) + ++keyword_length; + + /* TODO: make the keyword checking common */ + if (keyword_length >= 1 && keyword_length <= 79) + { + /* We only understand '0' compression - deflate - so if we get a + * different value we can't safely decode the chunk. + */ + if (keyword_length+1 < read_length && + keyword[keyword_length+1] == PNG_COMPRESSION_TYPE_BASE) + { + read_length -= keyword_length+2; + + if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK) + { + Byte profile_header[132]; + Byte local_buffer[PNG_INFLATE_BUF_SIZE]; + png_alloc_size_t size = (sizeof profile_header); + + png_ptr->zstream.next_in = (Bytef*)keyword + (keyword_length+2); + png_ptr->zstream.avail_in = read_length; + (void)png_inflate_read(png_ptr, local_buffer, + (sizeof local_buffer), &length, profile_header, &size, + 0/*finish: don't, because the output is too small*/); + + if (size == 0) + { + /* We have the ICC profile header; do the basic header checks. + */ + const png_uint_32 profile_length = + png_get_uint_32(profile_header); + + if (png_icc_check_length(png_ptr, &png_ptr->colorspace, + keyword, profile_length) != 0) + { + /* The length is apparently ok, so we can check the 132 + * byte header. + */ + if (png_icc_check_header(png_ptr, &png_ptr->colorspace, + keyword, profile_length, profile_header, + png_ptr->color_type) != 0) + { + /* Now read the tag table; a variable size buffer is + * needed at this point, allocate one for the whole + * profile. The header check has already validated + * that none of these stuff will overflow. + */ + const png_uint_32 tag_count = png_get_uint_32( + profile_header+128); + png_bytep profile = png_read_buffer(png_ptr, + profile_length, 2/*silent*/); + + if (profile != NULL) + { + memcpy(profile, profile_header, + (sizeof profile_header)); + + size = 12 * tag_count; + + (void)png_inflate_read(png_ptr, local_buffer, + (sizeof local_buffer), &length, + profile + (sizeof profile_header), &size, 0); + + /* Still expect a buffer error because we expect + * there to be some tag data! + */ + if (size == 0) + { + if (png_icc_check_tag_table(png_ptr, + &png_ptr->colorspace, keyword, profile_length, + profile) != 0) + { + /* The profile has been validated for basic + * security issues, so read the whole thing in. + */ + size = profile_length - (sizeof profile_header) + - 12 * tag_count; + + (void)png_inflate_read(png_ptr, local_buffer, + (sizeof local_buffer), &length, + profile + (sizeof profile_header) + + 12 * tag_count, &size, 1/*finish*/); + + if (length > 0 && !(png_ptr->flags & + PNG_FLAG_BENIGN_ERRORS_WARN)) + errmsg = "extra compressed data"; + + /* But otherwise allow extra data: */ + else if (size == 0) + { + if (length > 0) + { + /* This can be handled completely, so + * keep going. + */ + png_chunk_warning(png_ptr, + "extra compressed data"); + } + + png_crc_finish(png_ptr, length); + finished = 1; + +# ifdef PNG_sRGB_SUPPORTED + /* Check for a match against sRGB */ + png_icc_set_sRGB(png_ptr, + &png_ptr->colorspace, profile, + png_ptr->zstream.adler); +# endif + + /* Steal the profile for info_ptr. */ + if (info_ptr != NULL) + { + png_free_data(png_ptr, info_ptr, + PNG_FREE_ICCP, 0); + + info_ptr->iccp_name = png_voidcast(char*, + png_malloc_base(png_ptr, + keyword_length+1)); + if (info_ptr->iccp_name != NULL) + { + memcpy(info_ptr->iccp_name, keyword, + keyword_length+1); + info_ptr->iccp_proflen = + profile_length; + info_ptr->iccp_profile = profile; + png_ptr->read_buffer = NULL; /*steal*/ + info_ptr->free_me |= PNG_FREE_ICCP; + info_ptr->valid |= PNG_INFO_iCCP; + } + + else + { + png_ptr->colorspace.flags |= + PNG_COLORSPACE_INVALID; + errmsg = "out of memory"; + } + } + + /* else the profile remains in the read + * buffer which gets reused for subsequent + * chunks. + */ + + if (info_ptr != NULL) + png_colorspace_sync(png_ptr, info_ptr); + + if (errmsg == NULL) + { + png_ptr->zowner = 0; + return; + } + } + + else if (size > 0) + errmsg = "truncated"; + + else + errmsg = png_ptr->zstream.msg; + } + + /* else png_icc_check_tag_table output an error */ + } + + else /* profile truncated */ + errmsg = png_ptr->zstream.msg; + } + + else + errmsg = "out of memory"; + } + + /* else png_icc_check_header output an error */ + } + + /* else png_icc_check_length output an error */ + } + + else /* profile truncated */ + errmsg = png_ptr->zstream.msg; + + /* Release the stream */ + png_ptr->zowner = 0; + } + + else /* png_inflate_claim failed */ + errmsg = png_ptr->zstream.msg; + } + + else + errmsg = "bad compression method"; /* or missing */ + } + + else + errmsg = "bad keyword"; + } + + else + errmsg = "too many profiles"; + + /* Failure: the reason is in 'errmsg' */ + if (finished == 0) png_crc_finish(png_ptr, length); - return; - } -#ifdef PNG_MAX_MALLOC_64K - if (length > (png_uint_32)65535L) - { - png_warning(png_ptr, "iCCP chunk too large to fit in memory"); - skip = length - (png_uint_32)65535L; - length = (png_uint_32)65535L; - } -#endif - - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = (png_charp)png_malloc(png_ptr, length + 1); - slength = (png_size_t)length; - png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); - - if (png_crc_finish(png_ptr, skip)) - { - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - return; - } - - png_ptr->chunkdata[slength] = 0x00; - - for (profile = png_ptr->chunkdata; *profile; profile++) - /* Empty loop to find end of name */ ; - - ++profile; - - /* There should be at least one zero (the compression type byte) - * following the separator, and we should be on it - */ - if (profile >= png_ptr->chunkdata + slength - 1) - { - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - png_warning(png_ptr, "Malformed iCCP chunk"); - return; - } - - /* Compression_type should always be zero */ - compression_type = *profile++; - - if (compression_type) - { - png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk"); - compression_type = 0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8 - wrote nonzero) */ - } - - prefix_length = profile - png_ptr->chunkdata; - png_decompress_chunk(png_ptr, compression_type, - slength, prefix_length, &data_length); - - profile_length = data_length - prefix_length; - - if (prefix_length > data_length || profile_length < 4) - { - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - png_warning(png_ptr, "Profile size field missing from iCCP chunk"); - return; - } - - /* Check the profile_size recorded in the first 32 bits of the ICC profile */ - pC = (png_bytep)(png_ptr->chunkdata + prefix_length); - profile_size = ((*(pC )) << 24) | - ((*(pC + 1)) << 16) | - ((*(pC + 2)) << 8) | - ((*(pC + 3)) ); - - /* NOTE: the following guarantees that 'profile_length' fits into 32 bits, - * because profile_size is a 32 bit value. - */ - if (profile_size < profile_length) - profile_length = profile_size; - - /* And the following guarantees that profile_size == profile_length. */ - if (profile_size > profile_length) - { - PNG_WARNING_PARAMETERS(p) - - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - - png_warning_parameter_unsigned(p, 1, PNG_NUMBER_FORMAT_u, profile_size); - png_warning_parameter_unsigned(p, 2, PNG_NUMBER_FORMAT_u, profile_length); - png_formatted_warning(png_ptr, p, - "Ignoring iCCP chunk with declared size = @1 and actual length = @2"); - return; - } - - png_set_iCCP(png_ptr, info_ptr, png_ptr->chunkdata, - compression_type, (png_bytep)png_ptr->chunkdata + prefix_length, - profile_size); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; + png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID; + png_colorspace_sync(png_ptr, info_ptr); + if (errmsg != NULL) /* else already output */ + png_chunk_benign_error(png_ptr, errmsg); } -#endif /* PNG_READ_iCCP_SUPPORTED */ +#endif /* READ_iCCP */ #ifdef PNG_READ_sPLT_SUPPORTED void /* PRIVATE */ -png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) /* Note: this does not properly handle chunks that are > 64K under DOS */ { - png_bytep entry_start; + png_bytep entry_start, buffer; png_sPLT_t new_palette; png_sPLT_entryp pp; png_uint_32 data_length; int entry_size, i; png_uint_32 skip = 0; - png_size_t slength; png_uint_32 dl; png_size_t max_dl; png_debug(1, "in png_handle_sPLT"); #ifdef PNG_USER_LIMITS_SUPPORTED - if (png_ptr->user_chunk_cache_max != 0) { if (png_ptr->user_chunk_cache_max == 1) @@ -1338,55 +1631,53 @@ png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) } #endif - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before sPLT"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (png_ptr->mode & PNG_HAVE_IDAT) + else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { - png_warning(png_ptr, "Invalid sPLT after IDAT"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } #ifdef PNG_MAX_MALLOC_64K - if (length > (png_uint_32)65535L) + if (length > 65535U) { - png_warning(png_ptr, "sPLT chunk too large to fit in memory"); - skip = length - (png_uint_32)65535L; - length = (png_uint_32)65535L; + png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "too large to fit in memory"); + return; } #endif - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = (png_charp)png_malloc(png_ptr, length + 1); + buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/); + if (buffer == NULL) + { + png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of memory"); + return; + } + /* WARNING: this may break if size_t is less than 32 bits; it is assumed * that the PNG_MAX_MALLOC_64K test is enabled in this case, but this is a * potential breakage point if the types in pngconf.h aren't exactly right. */ - slength = (png_size_t)length; - png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); + png_crc_read(png_ptr, buffer, length); - if (png_crc_finish(png_ptr, skip)) - { - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; + if (png_crc_finish(png_ptr, skip) != 0) return; - } - png_ptr->chunkdata[slength] = 0x00; + buffer[length] = 0; - for (entry_start = (png_bytep)png_ptr->chunkdata; *entry_start; - entry_start++) + for (entry_start = buffer; *entry_start; entry_start++) /* Empty loop to find end of name */ ; ++entry_start; /* A sample depth should follow the separator, and we should be on it */ - if (entry_start > (png_bytep)png_ptr->chunkdata + slength - 2) + if (entry_start > buffer + length - 2) { - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; png_warning(png_ptr, "malformed sPLT chunk"); return; } @@ -1394,23 +1685,19 @@ png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) new_palette.depth = *entry_start++; entry_size = (new_palette.depth == 8 ? 6 : 10); /* This must fit in a png_uint_32 because it is derived from the original - * chunk data length (and use 'length', not 'slength' here for clarity - - * they are guaranteed to be the same, see the tests above.) + * chunk data length. */ - data_length = length - (png_uint_32)(entry_start - - (png_bytep)png_ptr->chunkdata); + data_length = length - (png_uint_32)(entry_start - buffer); /* Integrity-check the data length */ - if (data_length % entry_size) + if ((data_length % entry_size) != 0) { - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; png_warning(png_ptr, "sPLT chunk has bad length"); return; } dl = (png_int_32)(data_length / entry_size); - max_dl = PNG_SIZE_MAX / png_sizeof(png_sPLT_entry); + max_dl = PNG_SIZE_MAX / (sizeof (png_sPLT_entry)); if (dl > max_dl) { @@ -1421,7 +1708,7 @@ png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) new_palette.nentries = (png_int_32)(data_length / entry_size); new_palette.entries = (png_sPLT_entryp)png_malloc_warn( - png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry)); + png_ptr, new_palette.nentries * (sizeof (png_sPLT_entry))); if (new_palette.entries == NULL) { @@ -1479,38 +1766,36 @@ png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) #endif /* Discard all chunk data except the name and stash that */ - new_palette.name = png_ptr->chunkdata; + new_palette.name = (png_charp)buffer; png_set_sPLT(png_ptr, info_ptr, &new_palette, 1); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; png_free(png_ptr, new_palette.entries); } -#endif /* PNG_READ_sPLT_SUPPORTED */ +#endif /* READ_sPLT */ #ifdef PNG_READ_tRNS_SUPPORTED void /* PRIVATE */ -png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte readbuf[PNG_MAX_PALETTE_LENGTH]; png_debug(1, "in png_handle_tRNS"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before tRNS"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (png_ptr->mode & PNG_HAVE_IDAT) + else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { - png_warning(png_ptr, "Invalid tRNS after IDAT"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } - else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS)) + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0) { - png_warning(png_ptr, "Duplicate tRNS chunk"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "duplicate"); return; } @@ -1520,8 +1805,8 @@ png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) if (length != 2) { - png_warning(png_ptr, "Incorrect tRNS chunk length"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid"); return; } @@ -1536,12 +1821,12 @@ png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) if (length != 6) { - png_warning(png_ptr, "Incorrect tRNS chunk length"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid"); return; } - png_crc_read(png_ptr, buf, (png_size_t)length); + png_crc_read(png_ptr, buf, length); png_ptr->num_trans = 1; png_ptr->trans_color.red = png_get_uint_16(buf); png_ptr->trans_color.green = png_get_uint_16(buf + 2); @@ -1550,44 +1835,43 @@ png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { - if (!(png_ptr->mode & PNG_HAVE_PLTE)) + if ((png_ptr->mode & PNG_HAVE_PLTE) == 0) { - /* Should be an error, but we can cope with it. */ - png_warning(png_ptr, "Missing PLTE before tRNS"); - } - - if (length > (png_uint_32)png_ptr->num_palette || - length > PNG_MAX_PALETTE_LENGTH) - { - png_warning(png_ptr, "Incorrect tRNS chunk length"); + /* TODO: is this actually an error in the ISO spec? */ png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } - if (length == 0) + if (length > png_ptr->num_palette || length > PNG_MAX_PALETTE_LENGTH || + length == 0) { - png_warning(png_ptr, "Zero length tRNS chunk"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid"); return; } - png_crc_read(png_ptr, readbuf, (png_size_t)length); + png_crc_read(png_ptr, readbuf, length); png_ptr->num_trans = (png_uint_16)length; } else { - png_warning(png_ptr, "tRNS chunk not allowed with alpha channel"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid with alpha channel"); return; } - if (png_crc_finish(png_ptr, 0)) + if (png_crc_finish(png_ptr, 0) != 0) { png_ptr->num_trans = 0; return; } + /* TODO: this is a horrible side effect in the palette case because the + * png_struct ends up with a pointer to the tRNS buffer owned by the + * png_info. Fix this. + */ png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans, &(png_ptr->trans_color)); } @@ -1595,43 +1879,37 @@ png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) #ifdef PNG_READ_bKGD_SUPPORTED void /* PRIVATE */ -png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_bKGD(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { - png_size_t truelen; + unsigned int truelen; png_byte buf[6]; png_color_16 background; png_debug(1, "in png_handle_bKGD"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before bKGD"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (png_ptr->mode & PNG_HAVE_IDAT) + else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 || + (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE && + (png_ptr->mode & PNG_HAVE_PLTE) == 0)) { - png_warning(png_ptr, "Invalid bKGD after IDAT"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } - else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE && - !(png_ptr->mode & PNG_HAVE_PLTE)) + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0) { - png_warning(png_ptr, "Missing PLTE before bKGD"); - png_crc_finish(png_ptr, length); - return; - } - - else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)) - { - png_warning(png_ptr, "Duplicate bKGD chunk"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "duplicate"); return; } if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) truelen = 1; - else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR) + else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0) truelen = 6; else @@ -1639,14 +1917,14 @@ png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) if (length != truelen) { - png_warning(png_ptr, "Incorrect bKGD chunk length"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, truelen); - if (png_crc_finish(png_ptr, 0)) + if (png_crc_finish(png_ptr, 0) != 0) return; /* We convert the index value into RGB components so that we can allow @@ -1658,11 +1936,11 @@ png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) { background.index = buf[0]; - if (info_ptr && info_ptr->num_palette) + if (info_ptr != NULL && info_ptr->num_palette != 0) { if (buf[0] >= info_ptr->num_palette) { - png_warning(png_ptr, "Incorrect bKGD chunk index value"); + png_chunk_benign_error(png_ptr, "invalid index"); return; } @@ -1677,7 +1955,7 @@ png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) background.gray = 0; } - else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */ + else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) /* GRAY */ { background.index = 0; background.red = @@ -1701,44 +1979,37 @@ png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) #ifdef PNG_READ_hIST_SUPPORTED void /* PRIVATE */ -png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { unsigned int num, i; png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH]; png_debug(1, "in png_handle_hIST"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before hIST"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (png_ptr->mode & PNG_HAVE_IDAT) + else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 || + (png_ptr->mode & PNG_HAVE_PLTE) == 0) { - png_warning(png_ptr, "Invalid hIST after IDAT"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } - else if (!(png_ptr->mode & PNG_HAVE_PLTE)) + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0) { - png_warning(png_ptr, "Missing PLTE before hIST"); - png_crc_finish(png_ptr, length); - return; - } - - else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)) - { - png_warning(png_ptr, "Duplicate hIST chunk"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "duplicate"); return; } num = length / 2 ; - if (num != (unsigned int)png_ptr->num_palette || num > - (unsigned int)PNG_MAX_PALETTE_LENGTH) + if (num != png_ptr->num_palette || num > PNG_MAX_PALETTE_LENGTH) { - png_warning(png_ptr, "Incorrect hIST chunk length"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid"); return; } @@ -1750,7 +2021,7 @@ png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) readbuf[i] = png_get_uint_16(buf); } - if (png_crc_finish(png_ptr, 0)) + if (png_crc_finish(png_ptr, 0) != 0) return; png_set_hIST(png_ptr, info_ptr, readbuf); @@ -1759,7 +2030,7 @@ png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) #ifdef PNG_READ_pHYs_SUPPORTED void /* PRIVATE */ -png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_pHYs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[9]; png_uint_32 res_x, res_y; @@ -1767,33 +2038,33 @@ png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) png_debug(1, "in png_handle_pHYs"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before pHYs"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (png_ptr->mode & PNG_HAVE_IDAT) + else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { - png_warning(png_ptr, "Invalid pHYs after IDAT"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } - else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs)) + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs) != 0) { - png_warning(png_ptr, "Duplicate pHYs chunk"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "duplicate"); return; } if (length != 9) { - png_warning(png_ptr, "Incorrect pHYs chunk length"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 9); - if (png_crc_finish(png_ptr, 0)) + if (png_crc_finish(png_ptr, 0) != 0) return; res_x = png_get_uint_32(buf); @@ -1805,7 +2076,7 @@ png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) #ifdef PNG_READ_oFFs_SUPPORTED void /* PRIVATE */ -png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_oFFs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[9]; png_int_32 offset_x, offset_y; @@ -1813,33 +2084,33 @@ png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) png_debug(1, "in png_handle_oFFs"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before oFFs"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (png_ptr->mode & PNG_HAVE_IDAT) + else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { - png_warning(png_ptr, "Invalid oFFs after IDAT"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } - else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)) + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs) != 0) { - png_warning(png_ptr, "Duplicate oFFs chunk"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "duplicate"); return; } if (length != 9) { - png_warning(png_ptr, "Incorrect oFFs chunk length"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 9); - if (png_crc_finish(png_ptr, 0)) + if (png_crc_finish(png_ptr, 0) != 0) return; offset_x = png_get_int_32(buf); @@ -1852,71 +2123,64 @@ png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) #ifdef PNG_READ_pCAL_SUPPORTED /* Read the pCAL chunk (described in the PNG Extensions document) */ void /* PRIVATE */ -png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_pCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_int_32 X0, X1; png_byte type, nparams; - png_charp buf, units, endptr; + png_bytep buffer, buf, units, endptr; png_charpp params; - png_size_t slength; int i; png_debug(1, "in png_handle_pCAL"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before pCAL"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (png_ptr->mode & PNG_HAVE_IDAT) + else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { - png_warning(png_ptr, "Invalid pCAL after IDAT"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } - else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)) + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL) != 0) { - png_warning(png_ptr, "Duplicate pCAL chunk"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "duplicate"); return; } png_debug1(2, "Allocating and reading pCAL chunk data (%u bytes)", length + 1); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1); - if (png_ptr->chunkdata == NULL) + buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/); + + if (buffer == NULL) { - png_warning(png_ptr, "No memory for pCAL purpose"); + png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of memory"); return; } - slength = (png_size_t)length; - png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); + png_crc_read(png_ptr, buffer, length); - if (png_crc_finish(png_ptr, 0)) - { - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; + if (png_crc_finish(png_ptr, 0) != 0) return; - } - png_ptr->chunkdata[slength] = 0x00; /* Null terminate the last string */ + buffer[length] = 0; /* Null terminate the last string */ png_debug(3, "Finding end of pCAL purpose string"); - for (buf = png_ptr->chunkdata; *buf; buf++) + for (buf = buffer; *buf; buf++) /* Empty loop */ ; - endptr = png_ptr->chunkdata + slength; + endptr = buffer + length; /* We need to have at least 12 bytes after the purpose string * in order to get the parameter information. */ if (endptr <= buf + 12) { - png_warning(png_ptr, "Invalid pCAL data"); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; + png_chunk_benign_error(png_ptr, "invalid"); return; } @@ -1936,15 +2200,13 @@ png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) (type == PNG_EQUATION_ARBITRARY && nparams != 3) || (type == PNG_EQUATION_HYPERBOLIC && nparams != 4)) { - png_warning(png_ptr, "Invalid pCAL parameters for equation type"); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; + png_chunk_benign_error(png_ptr, "invalid parameter count"); return; } else if (type >= PNG_EQUATION_LAST) { - png_warning(png_ptr, "Unrecognized equation type for pCAL chunk"); + png_chunk_benign_error(png_ptr, "unrecognized equation type"); } for (buf = units; *buf; buf++) @@ -1952,43 +2214,37 @@ png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) png_debug(3, "Allocating pCAL parameters array"); - params = (png_charpp)png_malloc_warn(png_ptr, - (png_size_t)(nparams * png_sizeof(png_charp))); + params = png_voidcast(png_charpp, png_malloc_warn(png_ptr, + nparams * (sizeof (png_charp)))); if (params == NULL) { - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - png_warning(png_ptr, "No memory for pCAL params"); + png_chunk_benign_error(png_ptr, "out of memory"); return; } /* Get pointers to the start of each parameter string. */ - for (i = 0; i < (int)nparams; i++) + for (i = 0; i < nparams; i++) { buf++; /* Skip the null string terminator from previous parameter. */ png_debug1(3, "Reading pCAL parameter %d", i); - for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++) + for (params[i] = (png_charp)buf; buf <= endptr && *buf != 0; buf++) /* Empty loop to move past each parameter string */ ; /* Make sure we haven't run out of data yet */ if (buf > endptr) { - png_warning(png_ptr, "Invalid pCAL data"); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; png_free(png_ptr, params); + png_chunk_benign_error(png_ptr, "invalid data"); return; } } - png_set_pCAL(png_ptr, info_ptr, png_ptr->chunkdata, X0, X1, type, nparams, - units, params); + png_set_pCAL(png_ptr, info_ptr, (png_charp)buffer, X0, X1, type, nparams, + (png_charp)units, params); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; png_free(png_ptr, params); } #endif @@ -1996,67 +2252,61 @@ png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) #ifdef PNG_READ_sCAL_SUPPORTED /* Read the sCAL chunk */ void /* PRIVATE */ -png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { - png_size_t slength, i; + png_bytep buffer; + png_size_t i; int state; png_debug(1, "in png_handle_sCAL"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before sCAL"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (png_ptr->mode & PNG_HAVE_IDAT) + else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { - png_warning(png_ptr, "Invalid sCAL after IDAT"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "out of place"); return; } - else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL)) + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL) != 0) { - png_warning(png_ptr, "Duplicate sCAL chunk"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "duplicate"); return; } /* Need unit type, width, \0, height: minimum 4 bytes */ else if (length < 4) { - png_warning(png_ptr, "sCAL chunk too short"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid"); return; } png_debug1(2, "Allocating and reading sCAL chunk data (%u bytes)", length + 1); - png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1); + buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/); - if (png_ptr->chunkdata == NULL) + if (buffer == NULL) { - png_warning(png_ptr, "Out of memory while processing sCAL chunk"); + png_chunk_benign_error(png_ptr, "out of memory"); png_crc_finish(png_ptr, length); return; } - slength = (png_size_t)length; - png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); - png_ptr->chunkdata[slength] = 0x00; /* Null terminate the last string */ + png_crc_read(png_ptr, buffer, length); + buffer[length] = 0; /* Null terminate the last string */ - if (png_crc_finish(png_ptr, 0)) - { - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; + if (png_crc_finish(png_ptr, 0) != 0) return; - } /* Validate the unit. */ - if (png_ptr->chunkdata[0] != 1 && png_ptr->chunkdata[0] != 2) + if (buffer[0] != 1 && buffer[0] != 2) { - png_warning(png_ptr, "Invalid sCAL ignored: invalid unit"); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; + png_chunk_benign_error(png_ptr, "invalid unit"); return; } @@ -2066,70 +2316,65 @@ png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) i = 1; state = 0; - if (!png_check_fp_number(png_ptr->chunkdata, slength, &state, &i) || - i >= slength || png_ptr->chunkdata[i++] != 0) - png_warning(png_ptr, "Invalid sCAL chunk ignored: bad width format"); + if (png_check_fp_number((png_const_charp)buffer, length, &state, &i) == 0 || + i >= length || buffer[i++] != 0) + png_chunk_benign_error(png_ptr, "bad width format"); - else if (!PNG_FP_IS_POSITIVE(state)) - png_warning(png_ptr, "Invalid sCAL chunk ignored: non-positive width"); + else if (PNG_FP_IS_POSITIVE(state) == 0) + png_chunk_benign_error(png_ptr, "non-positive width"); else { png_size_t heighti = i; state = 0; - if (!png_check_fp_number(png_ptr->chunkdata, slength, &state, &i) || - i != slength) - png_warning(png_ptr, "Invalid sCAL chunk ignored: bad height format"); + if (png_check_fp_number((png_const_charp)buffer, length, + &state, &i) == 0 || i != length) + png_chunk_benign_error(png_ptr, "bad height format"); - else if (!PNG_FP_IS_POSITIVE(state)) - png_warning(png_ptr, - "Invalid sCAL chunk ignored: non-positive height"); + else if (PNG_FP_IS_POSITIVE(state) == 0) + png_chunk_benign_error(png_ptr, "non-positive height"); else /* This is the (only) success case. */ - png_set_sCAL_s(png_ptr, info_ptr, png_ptr->chunkdata[0], - png_ptr->chunkdata+1, png_ptr->chunkdata+heighti); + png_set_sCAL_s(png_ptr, info_ptr, buffer[0], + (png_charp)buffer+1, (png_charp)buffer+heighti); } - - /* Clean up - just free the temporarily allocated buffer. */ - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; } #endif #ifdef PNG_READ_tIME_SUPPORTED void /* PRIVATE */ -png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_tIME(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[7]; png_time mod_time; png_debug(1, "in png_handle_tIME"); - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Out of place tIME chunk"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)) + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME) != 0) { - png_warning(png_ptr, "Duplicate tIME chunk"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "duplicate"); return; } - if (png_ptr->mode & PNG_HAVE_IDAT) + if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) png_ptr->mode |= PNG_AFTER_IDAT; if (length != 7) { - png_warning(png_ptr, "Incorrect tIME chunk length"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 7); - if (png_crc_finish(png_ptr, 0)) + if (png_crc_finish(png_ptr, 0) != 0) return; mod_time.second = buf[6]; @@ -2146,14 +2391,13 @@ png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) #ifdef PNG_READ_tEXt_SUPPORTED /* Note: this does not properly handle chunks that are > 64K under DOS */ void /* PRIVATE */ -png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_tEXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { - png_textp text_ptr; + png_text text_info; + png_bytep buffer; png_charp key; png_charp text; png_uint_32 skip = 0; - png_size_t slength; - int ret; png_debug(1, "in png_handle_tEXt"); @@ -2168,84 +2412,59 @@ png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) if (--png_ptr->user_chunk_cache_max == 1) { - png_warning(png_ptr, "No space in chunk cache for tEXt"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "no space in chunk cache"); return; } } #endif - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before tEXt"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - if (png_ptr->mode & PNG_HAVE_IDAT) + if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) png_ptr->mode |= PNG_AFTER_IDAT; #ifdef PNG_MAX_MALLOC_64K - if (length > (png_uint_32)65535L) + if (length > 65535U) { - png_warning(png_ptr, "tEXt chunk too large to fit in memory"); - skip = length - (png_uint_32)65535L; - length = (png_uint_32)65535L; + png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "too large to fit in memory"); + return; } #endif - png_free(png_ptr, png_ptr->chunkdata); + buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/); - png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1); - - if (png_ptr->chunkdata == NULL) + if (buffer == NULL) { - png_warning(png_ptr, "No memory to process text chunk"); + png_chunk_benign_error(png_ptr, "out of memory"); return; } - slength = (png_size_t)length; - png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); + png_crc_read(png_ptr, buffer, length); - if (png_crc_finish(png_ptr, skip)) - { - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; + if (png_crc_finish(png_ptr, skip) != 0) return; - } - key = png_ptr->chunkdata; - - key[slength] = 0x00; + key = (png_charp)buffer; + key[length] = 0; for (text = key; *text; text++) /* Empty loop to find end of key */ ; - if (text != key + slength) + if (text != key + length) text++; - text_ptr = (png_textp)png_malloc_warn(png_ptr, - png_sizeof(png_text)); + text_info.compression = PNG_TEXT_COMPRESSION_NONE; + text_info.key = key; + text_info.lang = NULL; + text_info.lang_key = NULL; + text_info.itxt_length = 0; + text_info.text = text; + text_info.text_length = strlen(text); - if (text_ptr == NULL) - { - png_warning(png_ptr, "Not enough memory to process text chunk"); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - return; - } - - text_ptr->compression = PNG_TEXT_COMPRESSION_NONE; - text_ptr->key = key; - text_ptr->lang = NULL; - text_ptr->lang_key = NULL; - text_ptr->itxt_length = 0; - text_ptr->text = text; - text_ptr->text_length = png_strlen(text); - - ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1); - - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - png_free(png_ptr, text_ptr); - - if (ret) + if (png_set_text_2(png_ptr, info_ptr, &text_info, 1) != 0) png_warning(png_ptr, "Insufficient memory to process text chunk"); } #endif @@ -2253,13 +2472,11 @@ png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) #ifdef PNG_READ_zTXt_SUPPORTED /* Note: this does not correctly handle chunks that are > 64K under DOS */ void /* PRIVATE */ -png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_zTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { - png_textp text_ptr; - png_charp text; - int comp_type; - int ret; - png_size_t slength, prefix_len, data_len; + png_const_charp errmsg = NULL; + png_bytep buffer; + png_uint_32 keyword_length; png_debug(1, "in png_handle_zTXt"); @@ -2274,123 +2491,101 @@ png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) if (--png_ptr->user_chunk_cache_max == 1) { - png_warning(png_ptr, "No space in chunk cache for zTXt"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "no space in chunk cache"); return; } } #endif - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before zTXt"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - if (png_ptr->mode & PNG_HAVE_IDAT) + if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) png_ptr->mode |= PNG_AFTER_IDAT; -#ifdef PNG_MAX_MALLOC_64K - /* We will no doubt have problems with chunks even half this size, but - * there is no hard and fast rule to tell us where to stop. - */ - if (length > (png_uint_32)65535L) + buffer = png_read_buffer(png_ptr, length, 2/*silent*/); + + if (buffer == NULL) { - png_warning(png_ptr, "zTXt chunk too large to fit in memory"); png_crc_finish(png_ptr, length); - return; - } -#endif - - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1); - - if (png_ptr->chunkdata == NULL) - { - png_warning(png_ptr, "Out of memory processing zTXt chunk"); + png_chunk_benign_error(png_ptr, "out of memory"); return; } - slength = (png_size_t)length; - png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); + png_crc_read(png_ptr, buffer, length); - if (png_crc_finish(png_ptr, 0)) - { - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; + if (png_crc_finish(png_ptr, 0) != 0) return; - } - png_ptr->chunkdata[slength] = 0x00; + /* TODO: also check that the keyword contents match the spec! */ + for (keyword_length = 0; + keyword_length < length && buffer[keyword_length] != 0; + ++keyword_length) + /* Empty loop to find end of name */ ; - for (text = png_ptr->chunkdata; *text; text++) - /* Empty loop */ ; + if (keyword_length > 79 || keyword_length < 1) + errmsg = "bad keyword"; - /* zTXt must have some text after the chunkdataword */ - if (text >= png_ptr->chunkdata + slength - 2) - { - png_warning(png_ptr, "Truncated zTXt chunk"); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - return; - } + /* zTXt must have some LZ data after the keyword, although it may expand to + * zero bytes; we need a '\0' at the end of the keyword, the compression type + * then the LZ data: + */ + else if (keyword_length + 3 > length) + errmsg = "truncated"; + + else if (buffer[keyword_length+1] != PNG_COMPRESSION_TYPE_BASE) + errmsg = "unknown compression type"; else { - comp_type = *(++text); + png_alloc_size_t uncompressed_length = PNG_SIZE_MAX; - if (comp_type != PNG_TEXT_COMPRESSION_zTXt) - { - png_warning(png_ptr, "Unknown compression type in zTXt chunk"); - comp_type = PNG_TEXT_COMPRESSION_zTXt; - } + /* TODO: at present png_decompress_chunk imposes a single application + * level memory limit, this should be split to different values for iCCP + * and text chunks. + */ + if (png_decompress_chunk(png_ptr, length, keyword_length+2, + &uncompressed_length, 1/*terminate*/) == Z_STREAM_END) + { + png_text text; - text++; /* Skip the compression_method byte */ + /* It worked; png_ptr->read_buffer now looks like a tEXt chunk except + * for the extra compression type byte and the fact that it isn't + * necessarily '\0' terminated. + */ + buffer = png_ptr->read_buffer; + buffer[uncompressed_length+(keyword_length+2)] = 0; + + text.compression = PNG_TEXT_COMPRESSION_zTXt; + text.key = (png_charp)buffer; + text.text = (png_charp)(buffer + keyword_length+2); + text.text_length = uncompressed_length; + text.itxt_length = 0; + text.lang = NULL; + text.lang_key = NULL; + + if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0) + errmsg = "insufficient memory"; + } + + else + errmsg = png_ptr->zstream.msg; } - prefix_len = text - png_ptr->chunkdata; - - png_decompress_chunk(png_ptr, comp_type, - (png_size_t)length, prefix_len, &data_len); - - text_ptr = (png_textp)png_malloc_warn(png_ptr, - png_sizeof(png_text)); - - if (text_ptr == NULL) - { - png_warning(png_ptr, "Not enough memory to process zTXt chunk"); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - return; - } - - text_ptr->compression = comp_type; - text_ptr->key = png_ptr->chunkdata; - text_ptr->lang = NULL; - text_ptr->lang_key = NULL; - text_ptr->itxt_length = 0; - text_ptr->text = png_ptr->chunkdata + prefix_len; - text_ptr->text_length = data_len; - - ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1); - - png_free(png_ptr, text_ptr); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - - if (ret) - png_error(png_ptr, "Insufficient memory to store zTXt chunk"); + if (errmsg != NULL) + png_chunk_benign_error(png_ptr, errmsg); } #endif #ifdef PNG_READ_iTXt_SUPPORTED /* Note: this does not correctly handle chunks that are > 64K under DOS */ void /* PRIVATE */ -png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { - png_textp text_ptr; - png_charp key, lang, text, lang_key; - int comp_flag; - int comp_type = 0; - int ret; - png_size_t slength, prefix_len, data_len; + png_const_charp errmsg = NULL; + png_bytep buffer; + png_uint_32 prefix_length; png_debug(1, "in png_handle_iTXt"); @@ -2405,274 +2600,393 @@ png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) if (--png_ptr->user_chunk_cache_max == 1) { - png_warning(png_ptr, "No space in chunk cache for iTXt"); png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "no space in chunk cache"); return; } } #endif - if (!(png_ptr->mode & PNG_HAVE_IHDR)) - png_error(png_ptr, "Missing IHDR before iTXt"); + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, "missing IHDR"); - if (png_ptr->mode & PNG_HAVE_IDAT) + if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) png_ptr->mode |= PNG_AFTER_IDAT; -#ifdef PNG_MAX_MALLOC_64K - /* We will no doubt have problems with chunks even half this size, but - * there is no hard and fast rule to tell us where to stop. - */ - if (length > (png_uint_32)65535L) + buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/); + + if (buffer == NULL) { - png_warning(png_ptr, "iTXt chunk too large to fit in memory"); png_crc_finish(png_ptr, length); - return; - } -#endif - - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1); - - if (png_ptr->chunkdata == NULL) - { - png_warning(png_ptr, "No memory to process iTXt chunk"); + png_chunk_benign_error(png_ptr, "out of memory"); return; } - slength = (png_size_t)length; - png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); + png_crc_read(png_ptr, buffer, length); - if (png_crc_finish(png_ptr, 0)) - { - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; + if (png_crc_finish(png_ptr, 0) != 0) return; - } - png_ptr->chunkdata[slength] = 0x00; - - for (lang = png_ptr->chunkdata; *lang; lang++) + /* First the keyword. */ + for (prefix_length=0; + prefix_length < length && buffer[prefix_length] != 0; + ++prefix_length) /* Empty loop */ ; - lang++; /* Skip NUL separator */ + /* Perform a basic check on the keyword length here. */ + if (prefix_length > 79 || prefix_length < 1) + errmsg = "bad keyword"; - /* iTXt must have a language tag (possibly empty), two compression bytes, - * translated keyword (possibly empty), and possibly some text after the - * keyword + /* Expect keyword, compression flag, compression type, language, translated + * keyword (both may be empty but are 0 terminated) then the text, which may + * be empty. */ + else if (prefix_length + 5 > length) + errmsg = "truncated"; - if (lang >= png_ptr->chunkdata + slength - 3) + else if (buffer[prefix_length+1] == 0 || + (buffer[prefix_length+1] == 1 && + buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE)) { - png_warning(png_ptr, "Truncated iTXt chunk"); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - return; + int compressed = buffer[prefix_length+1] != 0; + png_uint_32 language_offset, translated_keyword_offset; + png_alloc_size_t uncompressed_length = 0; + + /* Now the language tag */ + prefix_length += 3; + language_offset = prefix_length; + + for (; prefix_length < length && buffer[prefix_length] != 0; + ++prefix_length) + /* Empty loop */ ; + + /* WARNING: the length may be invalid here, this is checked below. */ + translated_keyword_offset = ++prefix_length; + + for (; prefix_length < length && buffer[prefix_length] != 0; + ++prefix_length) + /* Empty loop */ ; + + /* prefix_length should now be at the trailing '\0' of the translated + * keyword, but it may already be over the end. None of this arithmetic + * can overflow because chunks are at most 2^31 bytes long, but on 16-bit + * systems the available allocation may overflow. + */ + ++prefix_length; + + if (compressed == 0 && prefix_length <= length) + uncompressed_length = length - prefix_length; + + else if (compressed != 0 && prefix_length < length) + { + uncompressed_length = PNG_SIZE_MAX; + + /* TODO: at present png_decompress_chunk imposes a single application + * level memory limit, this should be split to different values for + * iCCP and text chunks. + */ + if (png_decompress_chunk(png_ptr, length, prefix_length, + &uncompressed_length, 1/*terminate*/) == Z_STREAM_END) + buffer = png_ptr->read_buffer; + + else + errmsg = png_ptr->zstream.msg; + } + + else + errmsg = "truncated"; + + if (errmsg == NULL) + { + png_text text; + + buffer[uncompressed_length+prefix_length] = 0; + + if (compressed == 0) + text.compression = PNG_ITXT_COMPRESSION_NONE; + + else + text.compression = PNG_ITXT_COMPRESSION_zTXt; + + text.key = (png_charp)buffer; + text.lang = (png_charp)buffer + language_offset; + text.lang_key = (png_charp)buffer + translated_keyword_offset; + text.text = (png_charp)buffer + prefix_length; + text.text_length = 0; + text.itxt_length = uncompressed_length; + + if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0) + errmsg = "insufficient memory"; + } } else - { - comp_flag = *lang++; - comp_type = *lang++; - } + errmsg = "bad compression info"; - for (lang_key = lang; *lang_key; lang_key++) - /* Empty loop */ ; - - lang_key++; /* Skip NUL separator */ - - if (lang_key >= png_ptr->chunkdata + slength) - { - png_warning(png_ptr, "Truncated iTXt chunk"); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - return; - } - - for (text = lang_key; *text; text++) - /* Empty loop */ ; - - text++; /* Skip NUL separator */ - - if (text >= png_ptr->chunkdata + slength) - { - png_warning(png_ptr, "Malformed iTXt chunk"); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - return; - } - - prefix_len = text - png_ptr->chunkdata; - - key=png_ptr->chunkdata; - - if (comp_flag) - png_decompress_chunk(png_ptr, comp_type, - (size_t)length, prefix_len, &data_len); - - else - data_len = png_strlen(png_ptr->chunkdata + prefix_len); - - text_ptr = (png_textp)png_malloc_warn(png_ptr, - png_sizeof(png_text)); - - if (text_ptr == NULL) - { - png_warning(png_ptr, "Not enough memory to process iTXt chunk"); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - return; - } - - text_ptr->compression = (int)comp_flag + 1; - text_ptr->lang_key = png_ptr->chunkdata + (lang_key - key); - text_ptr->lang = png_ptr->chunkdata + (lang - key); - text_ptr->itxt_length = data_len; - text_ptr->text_length = 0; - text_ptr->key = png_ptr->chunkdata; - text_ptr->text = png_ptr->chunkdata + prefix_len; - - ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1); - - png_free(png_ptr, text_ptr); - png_free(png_ptr, png_ptr->chunkdata); - png_ptr->chunkdata = NULL; - - if (ret) - png_error(png_ptr, "Insufficient memory to store iTXt chunk"); + if (errmsg != NULL) + png_chunk_benign_error(png_ptr, errmsg); } #endif -/* This function is called when we haven't found a handler for a - * chunk. If there isn't a problem with the chunk itself (ie bad - * chunk name, CRC, or a critical chunk), the chunk is silently ignored - * -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which - * case it will be saved away to be written out later. - */ -void /* PRIVATE */ -png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) -{ - png_uint_32 skip = 0; - - png_debug(1, "in png_handle_unknown"); - -#ifdef PNG_USER_LIMITS_SUPPORTED - if (png_ptr->user_chunk_cache_max != 0) - { - if (png_ptr->user_chunk_cache_max == 1) - { - png_crc_finish(png_ptr, length); - return; - } - - if (--png_ptr->user_chunk_cache_max == 1) - { - png_warning(png_ptr, "No space in chunk cache for unknown chunk"); - png_crc_finish(png_ptr, length); - return; - } - } -#endif - - if (png_ptr->mode & PNG_HAVE_IDAT) - { - PNG_IDAT; - - if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* Not an IDAT */ - png_ptr->mode |= PNG_AFTER_IDAT; - } - - if (!(png_ptr->chunk_name[0] & 0x20)) - { -#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED - if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name) != - PNG_HANDLE_CHUNK_ALWAYS -#ifdef PNG_READ_USER_CHUNKS_SUPPORTED - && png_ptr->read_user_chunk_fn == NULL -#endif - ) -#endif - png_chunk_error(png_ptr, "unknown critical chunk"); - } - #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED - if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) -#ifdef PNG_READ_USER_CHUNKS_SUPPORTED - || (png_ptr->read_user_chunk_fn != NULL) -#endif - ) +/* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */ +static int +png_cache_unknown_chunk(png_structrp png_ptr, png_uint_32 length) +{ + png_alloc_size_t limit = PNG_SIZE_MAX; + + if (png_ptr->unknown_chunk.data != NULL) { -#ifdef PNG_MAX_MALLOC_64K - if (length > (png_uint_32)65535L) - { - png_warning(png_ptr, "unknown chunk too large to fit in memory"); - skip = length - (png_uint_32)65535L; - length = (png_uint_32)65535L; - } -#endif + png_free(png_ptr, png_ptr->unknown_chunk.data); + png_ptr->unknown_chunk.data = NULL; + } - png_memcpy((png_charp)png_ptr->unknown_chunk.name, - (png_charp)png_ptr->chunk_name, - png_sizeof(png_ptr->unknown_chunk.name)); +# ifdef PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED + if (png_ptr->user_chunk_malloc_max > 0 && + png_ptr->user_chunk_malloc_max < limit) + limit = png_ptr->user_chunk_malloc_max; - png_ptr->unknown_chunk.name[png_sizeof(png_ptr->unknown_chunk.name)-1] - = '\0'; +# elif PNG_USER_CHUNK_MALLOC_MAX > 0 + if (PNG_USER_CHUNK_MALLOC_MAX < limit) + limit = PNG_USER_CHUNK_MALLOC_MAX; +# endif - png_ptr->unknown_chunk.size = (png_size_t)length; + if (length <= limit) + { + PNG_CSTRING_FROM_CHUNK(png_ptr->unknown_chunk.name, png_ptr->chunk_name); + /* The following is safe because of the PNG_SIZE_MAX init above */ + png_ptr->unknown_chunk.size = (png_size_t)length/*SAFE*/; + /* 'mode' is a flag array, only the bottom four bits matter here */ + png_ptr->unknown_chunk.location = (png_byte)png_ptr->mode/*SAFE*/; if (length == 0) png_ptr->unknown_chunk.data = NULL; else { - png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length); - png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length); + /* Do a 'warn' here - it is handled below. */ + png_ptr->unknown_chunk.data = png_voidcast(png_bytep, + png_malloc_warn(png_ptr, length)); } + } -#ifdef PNG_READ_USER_CHUNKS_SUPPORTED - if (png_ptr->read_user_chunk_fn != NULL) - { - /* Callback to user unknown chunk handler */ - int ret; - - ret = (*(png_ptr->read_user_chunk_fn)) - (png_ptr, &png_ptr->unknown_chunk); - - if (ret < 0) - png_chunk_error(png_ptr, "error in user chunk"); - - if (ret == 0) - { - if (!(png_ptr->chunk_name[0] & 0x20)) - { -#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED - if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name) != - PNG_HANDLE_CHUNK_ALWAYS) -#endif - png_chunk_error(png_ptr, "unknown critical chunk"); - } - - png_set_unknown_chunks(png_ptr, info_ptr, - &png_ptr->unknown_chunk, 1); - } - } - - else -#endif - png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1); - - png_free(png_ptr, png_ptr->unknown_chunk.data); - png_ptr->unknown_chunk.data = NULL; + if (png_ptr->unknown_chunk.data == NULL && length > 0) + { + /* This is benign because we clean up correctly */ + png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, "unknown chunk exceeds memory limits"); + return 0; } else -#endif - skip = length; + { + if (length > 0) + png_crc_read(png_ptr, png_ptr->unknown_chunk.data, length); + png_crc_finish(png_ptr, 0); + return 1; + } +} +#endif /* READ_UNKNOWN_CHUNKS */ - png_crc_finish(png_ptr, skip); +/* Handle an unknown, or known but disabled, chunk */ +void /* PRIVATE */ +png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr, + png_uint_32 length, int keep) +{ + int handled = 0; /* the chunk was handled */ -#ifndef PNG_READ_USER_CHUNKS_SUPPORTED - PNG_UNUSED(info_ptr) /* Quiet compiler warnings about unused info_ptr */ -#endif + png_debug(1, "in png_handle_unknown"); + +#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED + /* NOTE: this code is based on the code in libpng-1.4.12 except for fixing + * the bug which meant that setting a non-default behavior for a specific + * chunk would be ignored (the default was always used unless a user + * callback was installed). + * + * 'keep' is the value from the png_chunk_unknown_handling, the setting for + * this specific chunk_name, if PNG_HANDLE_AS_UNKNOWN_SUPPORTED, if not it + * will always be PNG_HANDLE_CHUNK_AS_DEFAULT and it needs to be set here. + * This is just an optimization to avoid multiple calls to the lookup + * function. + */ +# ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED +# ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED + keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name); +# endif +# endif + + /* One of the following methods will read the chunk or skip it (at least one + * of these is always defined because this is the only way to switch on + * PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) + */ +# ifdef PNG_READ_USER_CHUNKS_SUPPORTED + /* The user callback takes precedence over the chunk keep value, but the + * keep value is still required to validate a save of a critical chunk. + */ + if (png_ptr->read_user_chunk_fn != NULL) + { + if (png_cache_unknown_chunk(png_ptr, length) != 0) + { + /* Callback to user unknown chunk handler */ + int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr, + &png_ptr->unknown_chunk); + + /* ret is: + * negative: An error occured, png_chunk_error will be called. + * zero: The chunk was not handled, the chunk will be discarded + * unless png_set_keep_unknown_chunks has been used to set + * a 'keep' behavior for this particular chunk, in which + * case that will be used. A critical chunk will cause an + * error at this point unless it is to be saved. + * positive: The chunk was handled, libpng will ignore/discard it. + */ + if (ret < 0) + png_chunk_error(png_ptr, "error in user chunk"); + + else if (ret == 0) + { + /* If the keep value is 'default' or 'never' override it, but + * still error out on critical chunks unless the keep value is + * 'always' While this is weird it is the behavior in 1.4.12. + * A possible improvement would be to obey the value set for the + * chunk, but this would be an API change that would probably + * damage some applications. + * + * The png_app_warning below catches the case that matters, where + * the application has not set specific save or ignore for this + * chunk or global save or ignore. + */ + if (keep < PNG_HANDLE_CHUNK_IF_SAFE) + { +# ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED + if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE) + { + png_chunk_warning(png_ptr, "Saving unknown chunk:"); + png_app_warning(png_ptr, + "forcing save of an unhandled chunk;" + " please call png_set_keep_unknown_chunks"); + /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */ + } +# endif + keep = PNG_HANDLE_CHUNK_IF_SAFE; + } + } + + else /* chunk was handled */ + { + handled = 1; + /* Critical chunks can be safely discarded at this point. */ + keep = PNG_HANDLE_CHUNK_NEVER; + } + } + + else + keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */ + } + + else + /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */ +# endif /* READ_USER_CHUNKS */ + +# ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED + { + /* keep is currently just the per-chunk setting, if there was no + * setting change it to the global default now (not that this may + * still be AS_DEFAULT) then obtain the cache of the chunk if required, + * if not simply skip the chunk. + */ + if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT) + keep = png_ptr->unknown_default; + + if (keep == PNG_HANDLE_CHUNK_ALWAYS || + (keep == PNG_HANDLE_CHUNK_IF_SAFE && + PNG_CHUNK_ANCILLARY(png_ptr->chunk_name))) + { + if (png_cache_unknown_chunk(png_ptr, length) == 0) + keep = PNG_HANDLE_CHUNK_NEVER; + } + + else + png_crc_finish(png_ptr, length); + } +# else +# ifndef PNG_READ_USER_CHUNKS_SUPPORTED +# error no method to support READ_UNKNOWN_CHUNKS +# endif + + { + /* If here there is no read callback pointer set and no support is + * compiled in to just save the unknown chunks, so simply skip this + * chunk. If 'keep' is something other than AS_DEFAULT or NEVER then + * the app has erroneously asked for unknown chunk saving when there + * is no support. + */ + if (keep > PNG_HANDLE_CHUNK_NEVER) + png_app_error(png_ptr, "no unknown chunk support available"); + + png_crc_finish(png_ptr, length); + } +# endif + +# ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED + /* Now store the chunk in the chunk list if appropriate, and if the limits + * permit it. + */ + if (keep == PNG_HANDLE_CHUNK_ALWAYS || + (keep == PNG_HANDLE_CHUNK_IF_SAFE && + PNG_CHUNK_ANCILLARY(png_ptr->chunk_name))) + { +# ifdef PNG_USER_LIMITS_SUPPORTED + switch (png_ptr->user_chunk_cache_max) + { + case 2: + png_ptr->user_chunk_cache_max = 1; + png_chunk_benign_error(png_ptr, "no space in chunk cache"); + /* FALL THROUGH */ + case 1: + /* NOTE: prior to 1.6.0 this case resulted in an unknown critical + * chunk being skipped, now there will be a hard error below. + */ + break; + + default: /* not at limit */ + --(png_ptr->user_chunk_cache_max); + /* FALL THROUGH */ + case 0: /* no limit */ +# endif /* USER_LIMITS */ + /* Here when the limit isn't reached or when limits are compiled + * out; store the chunk. + */ + png_set_unknown_chunks(png_ptr, info_ptr, + &png_ptr->unknown_chunk, 1); + handled = 1; +# ifdef PNG_USER_LIMITS_SUPPORTED + break; + } +# endif + } +# else /* no store support: the chunk must be handled by the user callback */ + PNG_UNUSED(info_ptr) +# endif + + /* Regardless of the error handling below the cached data (if any) can be + * freed now. Notice that the data is not freed if there is a png_error, but + * it will be freed by destroy_read_struct. + */ + if (png_ptr->unknown_chunk.data != NULL) + png_free(png_ptr, png_ptr->unknown_chunk.data); + png_ptr->unknown_chunk.data = NULL; + +#else /* !PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */ + /* There is no support to read an unknown chunk, so just skip it. */ + png_crc_finish(png_ptr, length); + PNG_UNUSED(info_ptr) + PNG_UNUSED(keep) +#endif /* !READ_UNKNOWN_CHUNKS */ + + /* Check for unhandled critical chunks */ + if (handled == 0 && PNG_CHUNK_CRITICAL(png_ptr->chunk_name)) + png_chunk_error(png_ptr, "unhandled critical chunk"); } /* This function is called to verify that a chunk name is valid. @@ -2682,267 +2996,527 @@ png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) * the chunk name itself is valid. */ -#define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97)) - -void /* PRIVATE */ -png_check_chunk_name(png_structp png_ptr, png_const_bytep chunk_name) -{ - png_debug(1, "in png_check_chunk_name"); - if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) || - isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3])) - { - png_chunk_error(png_ptr, "invalid chunk type"); - } -} - -/* Combines the row recently read in with the existing pixels in the - * row. This routine takes care of alpha and transparency if requested. - * This routine also handles the two methods of progressive display - * of interlaced images, depending on the mask value. - * The mask value describes which pixels are to be combined with - * the row. The pattern always repeats every 8 pixels, so just 8 - * bits are needed. A one indicates the pixel is to be combined, - * a zero indicates the pixel is to be skipped. This is in addition - * to any alpha or transparency value associated with the pixel. If - * you want all pixels to be combined, pass 0xff (255) in mask. +/* Bit hacking: the test for an invalid byte in the 4 byte chunk name is: + * + * ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97)) */ void /* PRIVATE */ -png_combine_row(png_structp png_ptr, png_bytep row, int mask) +png_check_chunk_name(png_structrp png_ptr, png_uint_32 chunk_name) { + int i; + + png_debug(1, "in png_check_chunk_name"); + + for (i=1; i<=4; ++i) + { + int c = chunk_name & 0xff; + + if (c < 65 || c > 122 || (c > 90 && c < 97)) + png_chunk_error(png_ptr, "invalid chunk type"); + + chunk_name >>= 8; + } +} + +/* Combines the row recently read in with the existing pixels in the row. This + * routine takes care of alpha and transparency if requested. This routine also + * handles the two methods of progressive display of interlaced images, + * depending on the 'display' value; if 'display' is true then the whole row + * (dp) is filled from the start by replicating the available pixels. If + * 'display' is false only those pixels present in the pass are filled in. + */ +void /* PRIVATE */ +png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display) +{ + unsigned int pixel_depth = png_ptr->transformed_pixel_depth; + png_const_bytep sp = png_ptr->row_buf + 1; + png_alloc_size_t row_width = png_ptr->width; + unsigned int pass = png_ptr->pass; + png_bytep end_ptr = 0; + png_byte end_byte = 0; + unsigned int end_mask; + png_debug(1, "in png_combine_row"); - /* Added in 1.5.4: the row_info should match the information returned by any - * call to png_read_update_info at this point. Do not continue if we got + /* Added in 1.5.6: it should not be possible to enter this routine until at + * least one row has been read from the PNG data and transformed. + */ + if (pixel_depth == 0) + png_error(png_ptr, "internal row logic error"); + + /* Added in 1.5.4: the pixel depth should match the information returned by + * any call to png_read_update_info at this point. Do not continue if we got * this wrong. */ if (png_ptr->info_rowbytes != 0 && png_ptr->info_rowbytes != - PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width)) + PNG_ROWBYTES(pixel_depth, row_width)) png_error(png_ptr, "internal row size calculation error"); - if (mask == 0xff) + /* Don't expect this to ever happen: */ + if (row_width == 0) + png_error(png_ptr, "internal row width error"); + + /* Preserve the last byte in cases where only part of it will be overwritten, + * the multiply below may overflow, we don't care because ANSI-C guarantees + * we get the low bits. + */ + end_mask = (pixel_depth * row_width) & 7; + if (end_mask != 0) { - png_memcpy(row, png_ptr->row_buf + 1, - PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width)); + /* end_ptr == NULL is a flag to say do nothing */ + end_ptr = dp + PNG_ROWBYTES(pixel_depth, row_width) - 1; + end_byte = *end_ptr; +# ifdef PNG_READ_PACKSWAP_SUPPORTED + if ((png_ptr->transformations & PNG_PACKSWAP) != 0) + /* little-endian byte */ + end_mask = 0xff << end_mask; + + else /* big-endian byte */ +# endif + end_mask = 0xff >> end_mask; + /* end_mask is now the bits to *keep* from the destination row */ } - else + /* For non-interlaced images this reduces to a memcpy(). A memcpy() + * will also happen if interlacing isn't supported or if the application + * does not call png_set_interlace_handling(). In the latter cases the + * caller just gets a sequence of the unexpanded rows from each interlace + * pass. + */ +#ifdef PNG_READ_INTERLACING_SUPPORTED + if (png_ptr->interlaced != 0 && + (png_ptr->transformations & PNG_INTERLACE) != 0 && + pass < 6 && (display == 0 || + /* The following copies everything for 'display' on passes 0, 2 and 4. */ + (display == 1 && (pass & 1) != 0))) { - switch (png_ptr->row_info.pixel_depth) + /* Narrow images may have no bits in a pass; the caller should handle + * this, but this test is cheap: + */ + if (row_width <= PNG_PASS_START_COL(pass)) + return; + + if (pixel_depth < 8) { - case 1: - { - png_bytep sp = png_ptr->row_buf + 1; - png_bytep dp = row; - int s_inc, s_start, s_end; - int m = 0x80; - int shift; - png_uint_32 i; - png_uint_32 row_width = png_ptr->width; + /* For pixel depths up to 4 bpp the 8-pixel mask can be expanded to fit + * into 32 bits, then a single loop over the bytes using the four byte + * values in the 32-bit mask can be used. For the 'display' option the + * expanded mask may also not require any masking within a byte. To + * make this work the PACKSWAP option must be taken into account - it + * simply requires the pixels to be reversed in each byte. + * + * The 'regular' case requires a mask for each of the first 6 passes, + * the 'display' case does a copy for the even passes in the range + * 0..6. This has already been handled in the test above. + * + * The masks are arranged as four bytes with the first byte to use in + * the lowest bits (little-endian) regardless of the order (PACKSWAP or + * not) of the pixels in each byte. + * + * NOTE: the whole of this logic depends on the caller of this function + * only calling it on rows appropriate to the pass. This function only + * understands the 'x' logic; the 'y' logic is handled by the caller. + * + * The following defines allow generation of compile time constant bit + * masks for each pixel depth and each possibility of swapped or not + * swapped bytes. Pass 'p' is in the range 0..6; 'x', a pixel index, + * is in the range 0..7; and the result is 1 if the pixel is to be + * copied in the pass, 0 if not. 'S' is for the sparkle method, 'B' + * for the block method. + * + * With some compilers a compile time expression of the general form: + * + * (shift >= 32) ? (a >> (shift-32)) : (b >> shift) + * + * Produces warnings with values of 'shift' in the range 33 to 63 + * because the right hand side of the ?: expression is evaluated by + * the compiler even though it isn't used. Microsoft Visual C (various + * versions) and the Intel C compiler are known to do this. To avoid + * this the following macros are used in 1.5.6. This is a temporary + * solution to avoid destabilizing the code during the release process. + */ +# if PNG_USE_COMPILE_TIME_MASKS +# define PNG_LSR(x,s) ((x)>>((s) & 0x1f)) +# define PNG_LSL(x,s) ((x)<<((s) & 0x1f)) +# else +# define PNG_LSR(x,s) ((x)>>(s)) +# define PNG_LSL(x,s) ((x)<<(s)) +# endif +# define S_COPY(p,x) (((p)<4 ? PNG_LSR(0x80088822,(3-(p))*8+(7-(x))) :\ + PNG_LSR(0xaa55ff00,(7-(p))*8+(7-(x)))) & 1) +# define B_COPY(p,x) (((p)<4 ? PNG_LSR(0xff0fff33,(3-(p))*8+(7-(x))) :\ + PNG_LSR(0xff55ff00,(7-(p))*8+(7-(x)))) & 1) -#ifdef PNG_READ_PACKSWAP_SUPPORTED - if (png_ptr->transformations & PNG_PACKSWAP) - { - s_start = 0; - s_end = 7; - s_inc = 1; - } + /* Return a mask for pass 'p' pixel 'x' at depth 'd'. The mask is + * little endian - the first pixel is at bit 0 - however the extra + * parameter 's' can be set to cause the mask position to be swapped + * within each byte, to match the PNG format. This is done by XOR of + * the shift with 7, 6 or 4 for bit depths 1, 2 and 4. + */ +# define PIXEL_MASK(p,x,d,s) \ + (PNG_LSL(((PNG_LSL(1U,(d)))-1),(((x)*(d))^((s)?8-(d):0)))) + + /* Hence generate the appropriate 'block' or 'sparkle' pixel copy mask. + */ +# define S_MASKx(p,x,d,s) (S_COPY(p,x)?PIXEL_MASK(p,x,d,s):0) +# define B_MASKx(p,x,d,s) (B_COPY(p,x)?PIXEL_MASK(p,x,d,s):0) + + /* Combine 8 of these to get the full mask. For the 1-bpp and 2-bpp + * cases the result needs replicating, for the 4-bpp case the above + * generates a full 32 bits. + */ +# define MASK_EXPAND(m,d) ((m)*((d)==1?0x01010101:((d)==2?0x00010001:1))) + +# define S_MASK(p,d,s) MASK_EXPAND(S_MASKx(p,0,d,s) + S_MASKx(p,1,d,s) +\ + S_MASKx(p,2,d,s) + S_MASKx(p,3,d,s) + S_MASKx(p,4,d,s) +\ + S_MASKx(p,5,d,s) + S_MASKx(p,6,d,s) + S_MASKx(p,7,d,s), d) + +# define B_MASK(p,d,s) MASK_EXPAND(B_MASKx(p,0,d,s) + B_MASKx(p,1,d,s) +\ + B_MASKx(p,2,d,s) + B_MASKx(p,3,d,s) + B_MASKx(p,4,d,s) +\ + B_MASKx(p,5,d,s) + B_MASKx(p,6,d,s) + B_MASKx(p,7,d,s), d) + +#if PNG_USE_COMPILE_TIME_MASKS + /* Utility macros to construct all the masks for a depth/swap + * combination. The 's' parameter says whether the format is PNG + * (big endian bytes) or not. Only the three odd-numbered passes are + * required for the display/block algorithm. + */ +# define S_MASKS(d,s) { S_MASK(0,d,s), S_MASK(1,d,s), S_MASK(2,d,s),\ + S_MASK(3,d,s), S_MASK(4,d,s), S_MASK(5,d,s) } + +# define B_MASKS(d,s) { B_MASK(1,d,s), B_MASK(3,d,s), B_MASK(5,d,s) } + +# define DEPTH_INDEX(d) ((d)==1?0:((d)==2?1:2)) + + /* Hence the pre-compiled masks indexed by PACKSWAP (or not), depth and + * then pass: + */ + static PNG_CONST png_uint_32 row_mask[2/*PACKSWAP*/][3/*depth*/][6] = + { + /* Little-endian byte masks for PACKSWAP */ + { S_MASKS(1,0), S_MASKS(2,0), S_MASKS(4,0) }, + /* Normal (big-endian byte) masks - PNG format */ + { S_MASKS(1,1), S_MASKS(2,1), S_MASKS(4,1) } + }; + + /* display_mask has only three entries for the odd passes, so index by + * pass>>1. + */ + static PNG_CONST png_uint_32 display_mask[2][3][3] = + { + /* Little-endian byte masks for PACKSWAP */ + { B_MASKS(1,0), B_MASKS(2,0), B_MASKS(4,0) }, + /* Normal (big-endian byte) masks - PNG format */ + { B_MASKS(1,1), B_MASKS(2,1), B_MASKS(4,1) } + }; + +# define MASK(pass,depth,display,png)\ + ((display)?display_mask[png][DEPTH_INDEX(depth)][pass>>1]:\ + row_mask[png][DEPTH_INDEX(depth)][pass]) + +#else /* !PNG_USE_COMPILE_TIME_MASKS */ + /* This is the runtime alternative: it seems unlikely that this will + * ever be either smaller or faster than the compile time approach. + */ +# define MASK(pass,depth,display,png)\ + ((display)?B_MASK(pass,depth,png):S_MASK(pass,depth,png)) +#endif /* !USE_COMPILE_TIME_MASKS */ + + /* Use the appropriate mask to copy the required bits. In some cases + * the byte mask will be 0 or 0xff; optimize these cases. row_width is + * the number of pixels, but the code copies bytes, so it is necessary + * to special case the end. + */ + png_uint_32 pixels_per_byte = 8 / pixel_depth; + png_uint_32 mask; + +# ifdef PNG_READ_PACKSWAP_SUPPORTED + if ((png_ptr->transformations & PNG_PACKSWAP) != 0) + mask = MASK(pass, pixel_depth, display, 0); else -#endif - { - s_start = 7; - s_end = 0; - s_inc = -1; - } +# endif + mask = MASK(pass, pixel_depth, display, 1); - shift = s_start; - - for (i = 0; i < row_width; i++) - { - if (m & mask) - { - int value; - - value = (*sp >> shift) & 0x01; - *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff); - *dp |= (png_byte)(value << shift); - } - - if (shift == s_end) - { - shift = s_start; - sp++; - dp++; - } - - else - shift += s_inc; - - if (m == 1) - m = 0x80; - - else - m >>= 1; - } - break; - } - - case 2: + for (;;) { - png_bytep sp = png_ptr->row_buf + 1; - png_bytep dp = row; - int s_start, s_end, s_inc; - int m = 0x80; - int shift; - png_uint_32 i; - png_uint_32 row_width = png_ptr->width; - int value; + png_uint_32 m; -#ifdef PNG_READ_PACKSWAP_SUPPORTED - if (png_ptr->transformations & PNG_PACKSWAP) + /* It doesn't matter in the following if png_uint_32 has more than + * 32 bits because the high bits always match those in m<<24; it is, + * however, essential to use OR here, not +, because of this. + */ + m = mask; + mask = (m >> 8) | (m << 24); /* rotate right to good compilers */ + m &= 0xff; + + if (m != 0) /* something to copy */ { - s_start = 0; - s_end = 6; - s_inc = 2; - } - - else -#endif - { - s_start = 6; - s_end = 0; - s_inc = -2; - } - - shift = s_start; - - for (i = 0; i < row_width; i++) - { - if (m & mask) - { - value = (*sp >> shift) & 0x03; - *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff); - *dp |= (png_byte)(value << shift); - } - - if (shift == s_end) - { - shift = s_start; - sp++; - dp++; - } - + if (m != 0xff) + *dp = (png_byte)((*dp & ~m) | (*sp & m)); else - shift += s_inc; - - if (m == 1) - m = 0x80; - - else - m >>= 1; - } - break; - } - - case 4: - { - png_bytep sp = png_ptr->row_buf + 1; - png_bytep dp = row; - int s_start, s_end, s_inc; - int m = 0x80; - int shift; - png_uint_32 i; - png_uint_32 row_width = png_ptr->width; - int value; - -#ifdef PNG_READ_PACKSWAP_SUPPORTED - if (png_ptr->transformations & PNG_PACKSWAP) - { - s_start = 0; - s_end = 4; - s_inc = 4; + *dp = *sp; } - else -#endif - { - s_start = 4; - s_end = 0; - s_inc = -4; - } - shift = s_start; + /* NOTE: this may overwrite the last byte with garbage if the image + * is not an exact number of bytes wide; libpng has always done + * this. + */ + if (row_width <= pixels_per_byte) + break; /* May need to restore part of the last byte */ - for (i = 0; i < row_width; i++) - { - if (m & mask) - { - value = (*sp >> shift) & 0xf; - *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff); - *dp |= (png_byte)(value << shift); - } - - if (shift == s_end) - { - shift = s_start; - sp++; - dp++; - } - - else - shift += s_inc; - - if (m == 1) - m = 0x80; - - else - m >>= 1; - } - break; - } - - default: - { - png_bytep sp = png_ptr->row_buf + 1; - png_bytep dp = row; - png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3); - png_uint_32 i; - png_uint_32 row_width = png_ptr->width; - png_byte m = 0x80; - - for (i = 0; i < row_width; i++) - { - if (m & mask) - { - png_memcpy(dp, sp, pixel_bytes); - } - - sp += pixel_bytes; - dp += pixel_bytes; - - if (m == 1) - m = 0x80; - - else - m >>= 1; - } - break; + row_width -= pixels_per_byte; + ++dp; + ++sp; } } + + else /* pixel_depth >= 8 */ + { + unsigned int bytes_to_copy, bytes_to_jump; + + /* Validate the depth - it must be a multiple of 8 */ + if (pixel_depth & 7) + png_error(png_ptr, "invalid user transform pixel depth"); + + pixel_depth >>= 3; /* now in bytes */ + row_width *= pixel_depth; + + /* Regardless of pass number the Adam 7 interlace always results in a + * fixed number of pixels to copy then to skip. There may be a + * different number of pixels to skip at the start though. + */ + { + unsigned int offset = PNG_PASS_START_COL(pass) * pixel_depth; + + row_width -= offset; + dp += offset; + sp += offset; + } + + /* Work out the bytes to copy. */ + if (display != 0) + { + /* When doing the 'block' algorithm the pixel in the pass gets + * replicated to adjacent pixels. This is why the even (0,2,4,6) + * passes are skipped above - the entire expanded row is copied. + */ + bytes_to_copy = (1<<((6-pass)>>1)) * pixel_depth; + + /* But don't allow this number to exceed the actual row width. */ + if (bytes_to_copy > row_width) + bytes_to_copy = (unsigned int)/*SAFE*/row_width; + } + + else /* normal row; Adam7 only ever gives us one pixel to copy. */ + bytes_to_copy = pixel_depth; + + /* In Adam7 there is a constant offset between where the pixels go. */ + bytes_to_jump = PNG_PASS_COL_OFFSET(pass) * pixel_depth; + + /* And simply copy these bytes. Some optimization is possible here, + * depending on the value of 'bytes_to_copy'. Special case the low + * byte counts, which we know to be frequent. + * + * Notice that these cases all 'return' rather than 'break' - this + * avoids an unnecessary test on whether to restore the last byte + * below. + */ + switch (bytes_to_copy) + { + case 1: + for (;;) + { + *dp = *sp; + + if (row_width <= bytes_to_jump) + return; + + dp += bytes_to_jump; + sp += bytes_to_jump; + row_width -= bytes_to_jump; + } + + case 2: + /* There is a possibility of a partial copy at the end here; this + * slows the code down somewhat. + */ + do + { + dp[0] = sp[0], dp[1] = sp[1]; + + if (row_width <= bytes_to_jump) + return; + + sp += bytes_to_jump; + dp += bytes_to_jump; + row_width -= bytes_to_jump; + } + while (row_width > 1); + + /* And there can only be one byte left at this point: */ + *dp = *sp; + return; + + case 3: + /* This can only be the RGB case, so each copy is exactly one + * pixel and it is not necessary to check for a partial copy. + */ + for (;;) + { + dp[0] = sp[0], dp[1] = sp[1], dp[2] = sp[2]; + + if (row_width <= bytes_to_jump) + return; + + sp += bytes_to_jump; + dp += bytes_to_jump; + row_width -= bytes_to_jump; + } + + default: +#if PNG_ALIGN_TYPE != PNG_ALIGN_NONE + /* Check for double byte alignment and, if possible, use a + * 16-bit copy. Don't attempt this for narrow images - ones that + * are less than an interlace panel wide. Don't attempt it for + * wide bytes_to_copy either - use the memcpy there. + */ + if (bytes_to_copy < 16 /*else use memcpy*/ && + png_isaligned(dp, png_uint_16) && + png_isaligned(sp, png_uint_16) && + bytes_to_copy % (sizeof (png_uint_16)) == 0 && + bytes_to_jump % (sizeof (png_uint_16)) == 0) + { + /* Everything is aligned for png_uint_16 copies, but try for + * png_uint_32 first. + */ + if (png_isaligned(dp, png_uint_32) != 0 && + png_isaligned(sp, png_uint_32) != 0 && + bytes_to_copy % (sizeof (png_uint_32)) == 0 && + bytes_to_jump % (sizeof (png_uint_32)) == 0) + { + png_uint_32p dp32 = png_aligncast(png_uint_32p,dp); + png_const_uint_32p sp32 = png_aligncastconst( + png_const_uint_32p, sp); + size_t skip = (bytes_to_jump-bytes_to_copy) / + (sizeof (png_uint_32)); + + do + { + size_t c = bytes_to_copy; + do + { + *dp32++ = *sp32++; + c -= (sizeof (png_uint_32)); + } + while (c > 0); + + if (row_width <= bytes_to_jump) + return; + + dp32 += skip; + sp32 += skip; + row_width -= bytes_to_jump; + } + while (bytes_to_copy <= row_width); + + /* Get to here when the row_width truncates the final copy. + * There will be 1-3 bytes left to copy, so don't try the + * 16-bit loop below. + */ + dp = (png_bytep)dp32; + sp = (png_const_bytep)sp32; + do + *dp++ = *sp++; + while (--row_width > 0); + return; + } + + /* Else do it in 16-bit quantities, but only if the size is + * not too large. + */ + else + { + png_uint_16p dp16 = png_aligncast(png_uint_16p, dp); + png_const_uint_16p sp16 = png_aligncastconst( + png_const_uint_16p, sp); + size_t skip = (bytes_to_jump-bytes_to_copy) / + (sizeof (png_uint_16)); + + do + { + size_t c = bytes_to_copy; + do + { + *dp16++ = *sp16++; + c -= (sizeof (png_uint_16)); + } + while (c > 0); + + if (row_width <= bytes_to_jump) + return; + + dp16 += skip; + sp16 += skip; + row_width -= bytes_to_jump; + } + while (bytes_to_copy <= row_width); + + /* End of row - 1 byte left, bytes_to_copy > row_width: */ + dp = (png_bytep)dp16; + sp = (png_const_bytep)sp16; + do + *dp++ = *sp++; + while (--row_width > 0); + return; + } + } +#endif /* ALIGN_TYPE code */ + + /* The true default - use a memcpy: */ + for (;;) + { + memcpy(dp, sp, bytes_to_copy); + + if (row_width <= bytes_to_jump) + return; + + sp += bytes_to_jump; + dp += bytes_to_jump; + row_width -= bytes_to_jump; + if (bytes_to_copy > row_width) + bytes_to_copy = (unsigned int)/*SAFE*/row_width; + } + } + + /* NOT REACHED*/ + } /* pixel_depth >= 8 */ + + /* Here if pixel_depth < 8 to check 'end_ptr' below. */ } + else +#endif /* READ_INTERLACING */ + + /* If here then the switch above wasn't used so just memcpy the whole row + * from the temporary row buffer (notice that this overwrites the end of the + * destination row if it is a partial byte.) + */ + memcpy(dp, sp, PNG_ROWBYTES(pixel_depth, row_width)); + + /* Restore the overwritten bits from the last byte if necessary. */ + if (end_ptr != NULL) + *end_ptr = (png_byte)((end_byte & end_mask) | (*end_ptr & ~end_mask)); } #ifdef PNG_READ_INTERLACING_SUPPORTED void /* PRIVATE */ -png_do_read_interlace(png_structp png_ptr) +png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass, + png_uint_32 transformations /* Because these may affect the byte layout */) { - png_row_infop row_info = &(png_ptr->row_info); - png_bytep row = png_ptr->row_buf + 1; - int pass = png_ptr->pass; - png_uint_32 transformations = png_ptr->transformations; /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Offset to next interlace block */ - PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; + static PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; png_debug(1, "in png_do_read_interlace"); if (row != NULL && row_info != NULL) @@ -2965,7 +3539,7 @@ png_do_read_interlace(png_structp png_ptr) int j; #ifdef PNG_READ_PACKSWAP_SUPPORTED - if (transformations & PNG_PACKSWAP) + if ((transformations & PNG_PACKSWAP) != 0) { sshift = (int)((row_info->width + 7) & 0x07); dshift = (int)((final_width + 7) & 0x07); @@ -2989,8 +3563,9 @@ png_do_read_interlace(png_structp png_ptr) v = (png_byte)((*sp >> sshift) & 0x01); for (j = 0; j < jstop; j++) { - *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff); - *dp |= (png_byte)(v << dshift); + unsigned int tmp = *dp & (0x7f7f >> (7 - dshift)); + tmp |= v << dshift; + *dp = (png_byte)(tmp & 0xff); if (dshift == s_end) { @@ -3024,7 +3599,7 @@ png_do_read_interlace(png_structp png_ptr) png_uint_32 i; #ifdef PNG_READ_PACKSWAP_SUPPORTED - if (transformations & PNG_PACKSWAP) + if ((transformations & PNG_PACKSWAP) != 0) { sshift = (int)(((row_info->width + 3) & 0x03) << 1); dshift = (int)(((final_width + 3) & 0x03) << 1); @@ -3051,8 +3626,9 @@ png_do_read_interlace(png_structp png_ptr) v = (png_byte)((*sp >> sshift) & 0x03); for (j = 0; j < jstop; j++) { - *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff); - *dp |= (png_byte)(v << dshift); + unsigned int tmp = *dp & (0x3f3f >> (6 - dshift)); + tmp |= v << dshift; + *dp = (png_byte)(tmp & 0xff); if (dshift == s_end) { @@ -3086,7 +3662,7 @@ png_do_read_interlace(png_structp png_ptr) int jstop = png_pass_inc[pass]; #ifdef PNG_READ_PACKSWAP_SUPPORTED - if (transformations & PNG_PACKSWAP) + if ((transformations & PNG_PACKSWAP) != 0) { sshift = (int)(((row_info->width + 1) & 0x01) << 2); dshift = (int)(((final_width + 1) & 0x01) << 2); @@ -3107,13 +3683,14 @@ png_do_read_interlace(png_structp png_ptr) for (i = 0; i < row_info->width; i++) { - png_byte v = (png_byte)((*sp >> sshift) & 0xf); + png_byte v = (png_byte)((*sp >> sshift) & 0x0f); int j; for (j = 0; j < jstop; j++) { - *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff); - *dp |= (png_byte)(v << dshift); + unsigned int tmp = *dp & (0xf0f >> (4 - dshift)); + tmp |= v << dshift; + *dp = (png_byte)(tmp & 0xff); if (dshift == s_end) { @@ -3136,6 +3713,7 @@ png_do_read_interlace(png_structp png_ptr) } break; } + default: { png_size_t pixel_bytes = (row_info->pixel_depth >> 3); @@ -3150,14 +3728,14 @@ png_do_read_interlace(png_structp png_ptr) for (i = 0; i < row_info->width; i++) { - png_byte v[8]; + png_byte v[8]; /* SAFE; pixel_depth does not exceed 64 */ int j; - png_memcpy(v, sp, pixel_bytes); + memcpy(v, sp, pixel_bytes); for (j = 0; j < jstop; j++) { - png_memcpy(dp, v, pixel_bytes); + memcpy(dp, v, pixel_bytes); dp -= pixel_bytes; } @@ -3166,6 +3744,7 @@ png_do_read_interlace(png_structp png_ptr) break; } } + row_info->width = final_width; row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width); } @@ -3173,167 +3752,427 @@ png_do_read_interlace(png_structp png_ptr) PNG_UNUSED(transformations) /* Silence compiler warning */ #endif } -#endif /* PNG_READ_INTERLACING_SUPPORTED */ +#endif /* READ_INTERLACING */ + +static void +png_read_filter_row_sub(png_row_infop row_info, png_bytep row, + png_const_bytep prev_row) +{ + png_size_t i; + png_size_t istop = row_info->rowbytes; + unsigned int bpp = (row_info->pixel_depth + 7) >> 3; + png_bytep rp = row + bpp; + + PNG_UNUSED(prev_row) + + for (i = bpp; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff); + rp++; + } +} + +static void +png_read_filter_row_up(png_row_infop row_info, png_bytep row, + png_const_bytep prev_row) +{ + png_size_t i; + png_size_t istop = row_info->rowbytes; + png_bytep rp = row; + png_const_bytep pp = prev_row; + + for (i = 0; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); + rp++; + } +} + +static void +png_read_filter_row_avg(png_row_infop row_info, png_bytep row, + png_const_bytep prev_row) +{ + png_size_t i; + png_bytep rp = row; + png_const_bytep pp = prev_row; + unsigned int bpp = (row_info->pixel_depth + 7) >> 3; + png_size_t istop = row_info->rowbytes - bpp; + + for (i = 0; i < bpp; i++) + { + *rp = (png_byte)(((int)(*rp) + + ((int)(*pp++) / 2 )) & 0xff); + + rp++; + } + + for (i = 0; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + + (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff); + + rp++; + } +} + +static void +png_read_filter_row_paeth_1byte_pixel(png_row_infop row_info, png_bytep row, + png_const_bytep prev_row) +{ + png_bytep rp_end = row + row_info->rowbytes; + int a, c; + + /* First pixel/byte */ + c = *prev_row++; + a = *row + c; + *row++ = (png_byte)a; + + /* Remainder */ + while (row < rp_end) + { + int b, pa, pb, pc, p; + + a &= 0xff; /* From previous iteration or start */ + b = *prev_row++; + + p = b - c; + pc = a - c; + +# ifdef PNG_USE_ABS + pa = abs(p); + pb = abs(pc); + pc = abs(p + pc); +# else + pa = p < 0 ? -p : p; + pb = pc < 0 ? -pc : pc; + pc = (p + pc) < 0 ? -(p + pc) : p + pc; +# endif + + /* Find the best predictor, the least of pa, pb, pc favoring the earlier + * ones in the case of a tie. + */ + if (pb < pa) pa = pb, a = b; + if (pc < pa) a = c; + + /* Calculate the current pixel in a, and move the previous row pixel to c + * for the next time round the loop + */ + c = b; + a += *row; + *row++ = (png_byte)a; + } +} + +static void +png_read_filter_row_paeth_multibyte_pixel(png_row_infop row_info, png_bytep row, + png_const_bytep prev_row) +{ + int bpp = (row_info->pixel_depth + 7) >> 3; + png_bytep rp_end = row + bpp; + + /* Process the first pixel in the row completely (this is the same as 'up' + * because there is only one candidate predictor for the first row). + */ + while (row < rp_end) + { + int a = *row + *prev_row++; + *row++ = (png_byte)a; + } + + /* Remainder */ + rp_end += row_info->rowbytes - bpp; + + while (row < rp_end) + { + int a, b, c, pa, pb, pc, p; + + c = *(prev_row - bpp); + a = *(row - bpp); + b = *prev_row++; + + p = b - c; + pc = a - c; + +# ifdef PNG_USE_ABS + pa = abs(p); + pb = abs(pc); + pc = abs(p + pc); +# else + pa = p < 0 ? -p : p; + pb = pc < 0 ? -pc : pc; + pc = (p + pc) < 0 ? -(p + pc) : p + pc; +# endif + + if (pb < pa) pa = pb, a = b; + if (pc < pa) a = c; + + a += *row; + *row++ = (png_byte)a; + } +} + +static void +png_init_filter_functions(png_structrp pp) + /* This function is called once for every PNG image (except for PNG images + * that only use PNG_FILTER_VALUE_NONE for all rows) to set the + * implementations required to reverse the filtering of PNG rows. Reversing + * the filter is the first transformation performed on the row data. It is + * performed in place, therefore an implementation can be selected based on + * the image pixel format. If the implementation depends on image width then + * take care to ensure that it works correctly if the image is interlaced - + * interlacing causes the actual row width to vary. + */ +{ + unsigned int bpp = (pp->pixel_depth + 7) >> 3; + + pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub; + pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up; + pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg; + if (bpp == 1) + pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = + png_read_filter_row_paeth_1byte_pixel; + else + pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = + png_read_filter_row_paeth_multibyte_pixel; + +#ifdef PNG_FILTER_OPTIMIZATIONS + /* To use this define PNG_FILTER_OPTIMIZATIONS as the name of a function to + * call to install hardware optimizations for the above functions; simply + * replace whatever elements of the pp->read_filter[] array with a hardware + * specific (or, for that matter, generic) optimization. + * + * To see an example of this examine what configure.ac does when + * --enable-arm-neon is specified on the command line. + */ + PNG_FILTER_OPTIMIZATIONS(pp, bpp); +#endif +} void /* PRIVATE */ -png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row, - png_const_bytep prev_row, int filter) +png_read_filter_row(png_structrp pp, png_row_infop row_info, png_bytep row, + png_const_bytep prev_row, int filter) { - png_debug(1, "in png_read_filter_row"); - png_debug2(2, "row = %u, filter = %d", png_ptr->row_number, filter); - switch (filter) + /* OPTIMIZATION: DO NOT MODIFY THIS FUNCTION, instead #define + * PNG_FILTER_OPTIMIZATIONS to a function that overrides the generic + * implementations. See png_init_filter_functions above. + */ + if (filter > PNG_FILTER_VALUE_NONE && filter < PNG_FILTER_VALUE_LAST) { - case PNG_FILTER_VALUE_NONE: - break; + if (pp->read_filter[0] == NULL) + png_init_filter_functions(pp); - case PNG_FILTER_VALUE_SUB: - { - png_size_t i; - png_size_t istop = row_info->rowbytes; - unsigned int bpp = (row_info->pixel_depth + 7) >> 3; - png_bytep rp = row + bpp; - png_bytep lp = row; - - for (i = bpp; i < istop; i++) - { - *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff); - rp++; - } - break; - } - case PNG_FILTER_VALUE_UP: - { - png_size_t i; - png_size_t istop = row_info->rowbytes; - png_bytep rp = row; - png_const_bytep pp = prev_row; - - for (i = 0; i < istop; i++) - { - *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); - rp++; - } - break; - } - case PNG_FILTER_VALUE_AVG: - { - png_size_t i; - png_bytep rp = row; - png_const_bytep pp = prev_row; - png_bytep lp = row; - unsigned int bpp = (row_info->pixel_depth + 7) >> 3; - png_size_t istop = row_info->rowbytes - bpp; - - for (i = 0; i < bpp; i++) - { - *rp = (png_byte)(((int)(*rp) + - ((int)(*pp++) / 2 )) & 0xff); - - rp++; - } - - for (i = 0; i < istop; i++) - { - *rp = (png_byte)(((int)(*rp) + - (int)(*pp++ + *lp++) / 2 ) & 0xff); - - rp++; - } - break; - } - case PNG_FILTER_VALUE_PAETH: - { - png_size_t i; - png_bytep rp = row; - png_const_bytep pp = prev_row; - png_bytep lp = row; - png_const_bytep cp = prev_row; - unsigned int bpp = (row_info->pixel_depth + 7) >> 3; - png_size_t istop=row_info->rowbytes - bpp; - - for (i = 0; i < bpp; i++) - { - *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); - rp++; - } - - for (i = 0; i < istop; i++) /* Use leftover rp,pp */ - { - int a, b, c, pa, pb, pc, p; - - a = *lp++; - b = *pp++; - c = *cp++; - - p = b - c; - pc = a - c; - -#ifdef PNG_USE_ABS - pa = abs(p); - pb = abs(pc); - pc = abs(p + pc); -#else - pa = p < 0 ? -p : p; - pb = pc < 0 ? -pc : pc; - pc = (p + pc) < 0 ? -(p + pc) : p + pc; -#endif - - /* - if (pa <= pb && pa <= pc) - p = a; - - else if (pb <= pc) - p = b; - - else - p = c; - */ - - p = (pa <= pb && pa <= pc) ? a : (pb <= pc) ? b : c; - - *rp = (png_byte)(((int)(*rp) + p) & 0xff); - rp++; - } - break; - } - default: - png_error(png_ptr, "Ignoring bad adaptive filter type"); - /*NOT REACHED */ - break; + pp->read_filter[filter-1](row_info, row, prev_row); } } #ifdef PNG_SEQUENTIAL_READ_SUPPORTED void /* PRIVATE */ -png_read_finish_row(png_structp png_ptr) +png_read_IDAT_data(png_structrp png_ptr, png_bytep output, + png_alloc_size_t avail_out) +{ + /* Loop reading IDATs and decompressing the result into output[avail_out] */ + png_ptr->zstream.next_out = output; + png_ptr->zstream.avail_out = 0; /* safety: set below */ + + if (output == NULL) + avail_out = 0; + + do + { + int ret; + png_byte tmpbuf[PNG_INFLATE_BUF_SIZE]; + + if (png_ptr->zstream.avail_in == 0) + { + uInt avail_in; + png_bytep buffer; + + while (png_ptr->idat_size == 0) + { + png_crc_finish(png_ptr, 0); + + png_ptr->idat_size = png_read_chunk_header(png_ptr); + /* This is an error even in the 'check' case because the code just + * consumed a non-IDAT header. + */ + if (png_ptr->chunk_name != png_IDAT) + png_error(png_ptr, "Not enough image data"); + } + + avail_in = png_ptr->IDAT_read_size; + + if (avail_in > png_ptr->idat_size) + avail_in = (uInt)png_ptr->idat_size; + + /* A PNG with a gradually increasing IDAT size will defeat this attempt + * to minimize memory usage by causing lots of re-allocs, but + * realistically doing IDAT_read_size re-allocs is not likely to be a + * big problem. + */ + buffer = png_read_buffer(png_ptr, avail_in, 0/*error*/); + + png_crc_read(png_ptr, buffer, avail_in); + png_ptr->idat_size -= avail_in; + + png_ptr->zstream.next_in = buffer; + png_ptr->zstream.avail_in = avail_in; + } + + /* And set up the output side. */ + if (output != NULL) /* standard read */ + { + uInt out = ZLIB_IO_MAX; + + if (out > avail_out) + out = (uInt)avail_out; + + avail_out -= out; + png_ptr->zstream.avail_out = out; + } + + else /* after last row, checking for end */ + { + png_ptr->zstream.next_out = tmpbuf; + png_ptr->zstream.avail_out = (sizeof tmpbuf); + } + + /* Use NO_FLUSH; this gives zlib the maximum opportunity to optimize the + * process. If the LZ stream is truncated the sequential reader will + * terminally damage the stream, above, by reading the chunk header of the + * following chunk (it then exits with png_error). + * + * TODO: deal more elegantly with truncated IDAT lists. + */ + ret = inflate(&png_ptr->zstream, Z_NO_FLUSH); + + /* Take the unconsumed output back. */ + if (output != NULL) + avail_out += png_ptr->zstream.avail_out; + + else /* avail_out counts the extra bytes */ + avail_out += (sizeof tmpbuf) - png_ptr->zstream.avail_out; + + png_ptr->zstream.avail_out = 0; + + if (ret == Z_STREAM_END) + { + /* Do this for safety; we won't read any more into this row. */ + png_ptr->zstream.next_out = NULL; + + png_ptr->mode |= PNG_AFTER_IDAT; + png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED; + + if (png_ptr->zstream.avail_in > 0 || png_ptr->idat_size > 0) + png_chunk_benign_error(png_ptr, "Extra compressed data"); + break; + } + + if (ret != Z_OK) + { + png_zstream_error(png_ptr, ret); + + if (output != NULL) + png_chunk_error(png_ptr, png_ptr->zstream.msg); + + else /* checking */ + { + png_chunk_benign_error(png_ptr, png_ptr->zstream.msg); + return; + } + } + } while (avail_out > 0); + + if (avail_out > 0) + { + /* The stream ended before the image; this is the same as too few IDATs so + * should be handled the same way. + */ + if (output != NULL) + png_error(png_ptr, "Not enough image data"); + + else /* the deflate stream contained extra data */ + png_chunk_benign_error(png_ptr, "Too much image data"); + } +} + +void /* PRIVATE */ +png_read_finish_IDAT(png_structrp png_ptr) +{ + /* We don't need any more data and the stream should have ended, however the + * LZ end code may actually not have been processed. In this case we must + * read it otherwise stray unread IDAT data or, more likely, an IDAT chunk + * may still remain to be consumed. + */ + if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0) + { + /* The NULL causes png_read_IDAT_data to swallow any remaining bytes in + * the compressed stream, but the stream may be damaged too, so even after + * this call we may need to terminate the zstream ownership. + */ + png_read_IDAT_data(png_ptr, NULL, 0); + png_ptr->zstream.next_out = NULL; /* safety */ + + /* Now clear everything out for safety; the following may not have been + * done. + */ + if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0) + { + png_ptr->mode |= PNG_AFTER_IDAT; + png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED; + } + } + + /* If the zstream has not been released do it now *and* terminate the reading + * of the final IDAT chunk. + */ + if (png_ptr->zowner == png_IDAT) + { + /* Always do this; the pointers otherwise point into the read buffer. */ + png_ptr->zstream.next_in = NULL; + png_ptr->zstream.avail_in = 0; + + /* Now we no longer own the zstream. */ + png_ptr->zowner = 0; + + /* The slightly weird semantics of the sequential IDAT reading is that we + * are always in or at the end of an IDAT chunk, so we always need to do a + * crc_finish here. If idat_size is non-zero we also need to read the + * spurious bytes at the end of the chunk now. + */ + (void)png_crc_finish(png_ptr, png_ptr->idat_size); + } +} + +void /* PRIVATE */ +png_read_finish_row(png_structrp png_ptr) { -#ifdef PNG_READ_INTERLACING_SUPPORTED /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ - PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; + static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ - PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; + static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ - PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; + static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ - PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; -#endif /* PNG_READ_INTERLACING_SUPPORTED */ + static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; png_debug(1, "in png_read_finish_row"); png_ptr->row_number++; if (png_ptr->row_number < png_ptr->num_rows) return; -#ifdef PNG_READ_INTERLACING_SUPPORTED - if (png_ptr->interlaced) + if (png_ptr->interlaced != 0) { png_ptr->row_number = 0; - png_memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1); + /* TO DO: don't do this if prev_row isn't needed (requires + * read-ahead of the next row's filter byte. + */ + memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1); do { @@ -3347,7 +4186,7 @@ png_read_finish_row(png_structp png_ptr) png_pass_start[png_ptr->pass]) / png_pass_inc[png_ptr->pass]; - if (!(png_ptr->transformations & PNG_INTERLACE)) + if ((png_ptr->transformations & PNG_INTERLACE) == 0) { png_ptr->num_rows = (png_ptr->height + png_pass_yinc[png_ptr->pass] - 1 - @@ -3363,108 +4202,40 @@ png_read_finish_row(png_structp png_ptr) if (png_ptr->pass < 7) return; } -#endif /* PNG_READ_INTERLACING_SUPPORTED */ - if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED)) - { - PNG_IDAT; - char extra; - int ret; - - png_ptr->zstream.next_out = (Byte *)&extra; - png_ptr->zstream.avail_out = (uInt)1; - - for (;;) - { - if (!(png_ptr->zstream.avail_in)) - { - while (!png_ptr->idat_size) - { - png_crc_finish(png_ptr, 0); - png_ptr->idat_size = png_read_chunk_header(png_ptr); - if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) - png_error(png_ptr, "Not enough image data"); - } - - png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size; - png_ptr->zstream.next_in = png_ptr->zbuf; - - if (png_ptr->zbuf_size > png_ptr->idat_size) - png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size; - - png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in); - png_ptr->idat_size -= png_ptr->zstream.avail_in; - } - - ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH); - - if (ret == Z_STREAM_END) - { - if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in || - png_ptr->idat_size) - png_warning(png_ptr, "Extra compressed data"); - - png_ptr->mode |= PNG_AFTER_IDAT; - png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED; - break; - } - - if (ret != Z_OK) - png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg : - "Decompression Error"); - - if (!(png_ptr->zstream.avail_out)) - { - png_warning(png_ptr, "Extra compressed data"); - png_ptr->mode |= PNG_AFTER_IDAT; - png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED; - break; - } - - } - png_ptr->zstream.avail_out = 0; - } - - if (png_ptr->idat_size || png_ptr->zstream.avail_in) - png_warning(png_ptr, "Extra compression data"); - - inflateReset(&png_ptr->zstream); - - png_ptr->mode |= PNG_AFTER_IDAT; + /* Here after at the end of the last row of the last pass. */ + png_read_finish_IDAT(png_ptr); } -#endif /* PNG_SEQUENTIAL_READ_SUPPORTED */ +#endif /* SEQUENTIAL_READ */ void /* PRIVATE */ -png_read_start_row(png_structp png_ptr) +png_read_start_row(png_structrp png_ptr) { -#ifdef PNG_READ_INTERLACING_SUPPORTED /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ - PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; + static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ - PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; + static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ - PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; + static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ - PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; -#endif + static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; int max_pixel_depth; png_size_t row_bytes; png_debug(1, "in png_read_start_row"); - png_ptr->zstream.avail_in = 0; + #ifdef PNG_READ_TRANSFORMS_SUPPORTED png_init_read_transformations(png_ptr); #endif -#ifdef PNG_READ_INTERLACING_SUPPORTED - if (png_ptr->interlaced) + if (png_ptr->interlaced != 0) { - if (!(png_ptr->transformations & PNG_INTERLACE)) + if ((png_ptr->transformations & PNG_INTERLACE) == 0) png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 - png_pass_ystart[0]) / png_pass_yinc[0]; @@ -3478,7 +4249,6 @@ png_read_start_row(png_structp png_ptr) } else -#endif /* PNG_READ_INTERLACING_SUPPORTED */ { png_ptr->num_rows = png_ptr->height; png_ptr->iwidth = png_ptr->width; @@ -3486,17 +4256,27 @@ png_read_start_row(png_structp png_ptr) max_pixel_depth = png_ptr->pixel_depth; + /* WARNING: * png_read_transform_info (pngrtran.c) performs a simpler set of + * calculations to calculate the final pixel depth, then + * png_do_read_transforms actually does the transforms. This means that the + * code which effectively calculates this value is actually repeated in three + * separate places. They must all match. Innocent changes to the order of + * transformations can and will break libpng in a way that causes memory + * overwrites. + * + * TODO: fix this. + */ #ifdef PNG_READ_PACK_SUPPORTED - if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8) + if ((png_ptr->transformations & PNG_PACK) != 0 && png_ptr->bit_depth < 8) max_pixel_depth = 8; #endif #ifdef PNG_READ_EXPAND_SUPPORTED - if (png_ptr->transformations & PNG_EXPAND) + if ((png_ptr->transformations & PNG_EXPAND) != 0) { if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { - if (png_ptr->num_trans) + if (png_ptr->num_trans != 0) max_pixel_depth = 32; else @@ -3508,13 +4288,13 @@ png_read_start_row(png_structp png_ptr) if (max_pixel_depth < 8) max_pixel_depth = 8; - if (png_ptr->num_trans) + if (png_ptr->num_trans != 0) max_pixel_depth *= 2; } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) { - if (png_ptr->num_trans) + if (png_ptr->num_trans != 0) { max_pixel_depth *= 4; max_pixel_depth /= 3; @@ -3524,13 +4304,13 @@ png_read_start_row(png_structp png_ptr) #endif #ifdef PNG_READ_EXPAND_16_SUPPORTED - if (png_ptr->transformations & PNG_EXPAND_16) + if ((png_ptr->transformations & PNG_EXPAND_16) != 0) { # ifdef PNG_READ_EXPAND_SUPPORTED /* In fact it is an error if it isn't supported, but checking is * the safe way. */ - if (png_ptr->transformations & PNG_EXPAND) + if ((png_ptr->transformations & PNG_EXPAND) != 0) { if (png_ptr->bit_depth < 16) max_pixel_depth *= 2; @@ -3542,12 +4322,9 @@ png_read_start_row(png_structp png_ptr) #endif #ifdef PNG_READ_FILLER_SUPPORTED - if (png_ptr->transformations & (PNG_FILLER)) + if ((png_ptr->transformations & (PNG_FILLER)) != 0) { - if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) - max_pixel_depth = 32; - - else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) + if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) { if (max_pixel_depth <= 8) max_pixel_depth = 16; @@ -3556,7 +4333,8 @@ png_read_start_row(png_structp png_ptr) max_pixel_depth = 32; } - else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) + else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB || + png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { if (max_pixel_depth <= 32) max_pixel_depth = 32; @@ -3568,14 +4346,15 @@ png_read_start_row(png_structp png_ptr) #endif #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED - if (png_ptr->transformations & PNG_GRAY_TO_RGB) + if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0) { if ( #ifdef PNG_READ_EXPAND_SUPPORTED - (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) || + (png_ptr->num_trans != 0 && + (png_ptr->transformations & PNG_EXPAND) != 0) || #endif #ifdef PNG_READ_FILLER_SUPPORTED - (png_ptr->transformations & (PNG_FILLER)) || + (png_ptr->transformations & (PNG_FILLER)) != 0 || #endif png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { @@ -3608,16 +4387,22 @@ png_read_start_row(png_structp png_ptr) #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \ defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) - if (png_ptr->transformations & PNG_USER_TRANSFORM) + if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0) { - int user_pixel_depth = png_ptr->user_transform_depth* + int user_pixel_depth = png_ptr->user_transform_depth * png_ptr->user_transform_channels; if (user_pixel_depth > max_pixel_depth) - max_pixel_depth=user_pixel_depth; + max_pixel_depth = user_pixel_depth; } #endif + /* This value is stored in png_struct and double checked in the row read + * code. + */ + png_ptr->maximum_pixel_depth = (png_byte)max_pixel_depth; + png_ptr->transformed_pixel_depth = 0; /* calculated on demand */ + /* Align the width on the next larger 8 pixels. Mainly used * for interlacing */ @@ -3636,28 +4421,39 @@ defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) if (row_bytes + 48 > png_ptr->old_big_row_buf_size) { png_free(png_ptr, png_ptr->big_row_buf); + png_free(png_ptr, png_ptr->big_prev_row); - if (png_ptr->interlaced) + if (png_ptr->interlaced != 0) png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr, row_bytes + 48); else - png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, - row_bytes + 48); + png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes + 48); - png_ptr->old_big_row_buf_size = row_bytes + 48; + png_ptr->big_prev_row = (png_bytep)png_malloc(png_ptr, row_bytes + 48); #ifdef PNG_ALIGNED_MEMORY_SUPPORTED /* Use 16-byte aligned memory for row_buf with at least 16 bytes - * of padding before and after row_buf. + * of padding before and after row_buf; treat prev_row similarly. + * NOTE: the alignment is to the start of the pixels, one beyond the start + * of the buffer, because of the filter byte. Prior to libpng 1.5.6 this + * was incorrect; the filter byte was aligned, which had the exact + * opposite effect of that intended. */ - png_ptr->row_buf = png_ptr->big_row_buf + 32 - - (((png_alloc_size_t)png_ptr->big_row_buf + 15) & 0x0F); + { + png_bytep temp = png_ptr->big_row_buf + 32; + int extra = (int)((temp - (png_bytep)0) & 0x0f); + png_ptr->row_buf = temp - extra - 1/*filter byte*/; + + temp = png_ptr->big_prev_row + 32; + extra = (int)((temp - (png_bytep)0) & 0x0f); + png_ptr->prev_row = temp - extra - 1/*filter byte*/; + } - png_ptr->old_big_row_buf_size = row_bytes + 48; #else - /* Use 32 bytes of padding before and 16 bytes after row_buf. */ - png_ptr->row_buf = png_ptr->big_row_buf + 32; + /* Use 31 bytes of padding before and 17 bytes after row_buf. */ + png_ptr->row_buf = png_ptr->big_row_buf + 31; + png_ptr->prev_row = png_ptr->big_prev_row + 31; #endif png_ptr->old_big_row_buf_size = row_bytes + 48; } @@ -3670,16 +4466,7 @@ defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) if (png_ptr->rowbytes > (PNG_SIZE_MAX - 1)) png_error(png_ptr, "Row has too many bytes to allocate in memory"); - if (png_ptr->rowbytes + 1 > png_ptr->old_prev_row_size) - { - png_free(png_ptr, png_ptr->prev_row); - - png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, png_ptr->rowbytes + 1); - - png_ptr->old_prev_row_size = png_ptr->rowbytes + 1; - } - - png_memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1); + memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1); png_debug1(3, "width = %u,", png_ptr->width); png_debug1(3, "height = %u,", png_ptr->height); @@ -3689,6 +4476,27 @@ defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) png_debug1(3, "irowbytes = %lu", (unsigned long)PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1); + /* The sequential reader needs a buffer for IDAT, but the progressive reader + * does not, so free the read buffer now regardless; the sequential reader + * reallocates it on demand. + */ + if (png_ptr->read_buffer != 0) + { + png_bytep buffer = png_ptr->read_buffer; + + png_ptr->read_buffer_size = 0; + png_ptr->read_buffer = NULL; + png_free(png_ptr, buffer); + } + + /* Finally claim the zstream for the inflate of the IDAT data, use the bits + * value from the stream (note that this will result in a fatal error if the + * IDAT stream has a bogus deflate header window_bits value, but this should + * not be happening any longer!) + */ + if (png_inflate_claim(png_ptr, png_IDAT) != Z_OK) + png_error(png_ptr, png_ptr->zstream.msg); + png_ptr->flags |= PNG_FLAG_ROW_INIT; } -#endif /* PNG_READ_SUPPORTED */ +#endif /* READ */ diff --git a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngset.c b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngset.c index 819605f5025..d2c89b2a55f 100644 --- a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngset.c +++ b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngset.c @@ -29,8 +29,8 @@ * However, the following notice accompanied the original version of this * file and, per its terms, should not be removed: * - * Last changed in libpng 1.5.4 [July 7, 2011] - * Copyright (c) 1998-2011 Glenn Randers-Pehrson + * Last changed in libpng 1.6.15 [November 20, 2014] + * Copyright (c) 1998-2014 Glenn Randers-Pehrson * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) * @@ -50,51 +50,84 @@ #ifdef PNG_bKGD_SUPPORTED void PNGAPI -png_set_bKGD(png_structp png_ptr, png_infop info_ptr, +png_set_bKGD(png_const_structrp png_ptr, png_inforp info_ptr, png_const_color_16p background) { png_debug1(1, "in %s storage function", "bKGD"); - if (png_ptr == NULL || info_ptr == NULL) + if (png_ptr == NULL || info_ptr == NULL || background == NULL) return; - png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16)); + info_ptr->background = *background; info_ptr->valid |= PNG_INFO_bKGD; } #endif #ifdef PNG_cHRM_SUPPORTED void PNGFAPI -png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr, +png_set_cHRM_fixed(png_const_structrp png_ptr, png_inforp info_ptr, png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x, png_fixed_point blue_y) { + png_xy xy; + png_debug1(1, "in %s storage function", "cHRM fixed"); if (png_ptr == NULL || info_ptr == NULL) return; -# ifdef PNG_CHECK_cHRM_SUPPORTED - if (png_check_cHRM_fixed(png_ptr, - white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y)) -# endif - { - info_ptr->x_white = white_x; - info_ptr->y_white = white_y; - info_ptr->x_red = red_x; - info_ptr->y_red = red_y; - info_ptr->x_green = green_x; - info_ptr->y_green = green_y; - info_ptr->x_blue = blue_x; - info_ptr->y_blue = blue_y; - info_ptr->valid |= PNG_INFO_cHRM; - } + xy.redx = red_x; + xy.redy = red_y; + xy.greenx = green_x; + xy.greeny = green_y; + xy.bluex = blue_x; + xy.bluey = blue_y; + xy.whitex = white_x; + xy.whitey = white_y; + + if (png_colorspace_set_chromaticities(png_ptr, &info_ptr->colorspace, &xy, + 2/* override with app values*/) != 0) + info_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM; + + png_colorspace_sync_info(png_ptr, info_ptr); +} + +void PNGFAPI +png_set_cHRM_XYZ_fixed(png_const_structrp png_ptr, png_inforp info_ptr, + png_fixed_point int_red_X, png_fixed_point int_red_Y, + png_fixed_point int_red_Z, png_fixed_point int_green_X, + png_fixed_point int_green_Y, png_fixed_point int_green_Z, + png_fixed_point int_blue_X, png_fixed_point int_blue_Y, + png_fixed_point int_blue_Z) +{ + png_XYZ XYZ; + + png_debug1(1, "in %s storage function", "cHRM XYZ fixed"); + + if (png_ptr == NULL || info_ptr == NULL) + return; + + XYZ.red_X = int_red_X; + XYZ.red_Y = int_red_Y; + XYZ.red_Z = int_red_Z; + XYZ.green_X = int_green_X; + XYZ.green_Y = int_green_Y; + XYZ.green_Z = int_green_Z; + XYZ.blue_X = int_blue_X; + XYZ.blue_Y = int_blue_Y; + XYZ.blue_Z = int_blue_Z; + + if (png_colorspace_set_endpoints(png_ptr, &info_ptr->colorspace, + &XYZ, 2) != 0) + info_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM; + + png_colorspace_sync_info(png_ptr, info_ptr); } # ifdef PNG_FLOATING_POINT_SUPPORTED void PNGAPI -png_set_cHRM(png_structp png_ptr, png_infop info_ptr, +png_set_cHRM(png_const_structrp png_ptr, png_inforp info_ptr, double white_x, double white_y, double red_x, double red_y, double green_x, double green_y, double blue_x, double blue_y) { @@ -108,41 +141,44 @@ png_set_cHRM(png_structp png_ptr, png_infop info_ptr, png_fixed(png_ptr, blue_x, "cHRM Blue X"), png_fixed(png_ptr, blue_y, "cHRM Blue Y")); } -# endif /* PNG_FLOATING_POINT_SUPPORTED */ -#endif /* PNG_cHRM_SUPPORTED */ +void PNGAPI +png_set_cHRM_XYZ(png_const_structrp png_ptr, png_inforp info_ptr, double red_X, + double red_Y, double red_Z, double green_X, double green_Y, double green_Z, + double blue_X, double blue_Y, double blue_Z) +{ + png_set_cHRM_XYZ_fixed(png_ptr, info_ptr, + png_fixed(png_ptr, red_X, "cHRM Red X"), + png_fixed(png_ptr, red_Y, "cHRM Red Y"), + png_fixed(png_ptr, red_Z, "cHRM Red Z"), + png_fixed(png_ptr, green_X, "cHRM Red X"), + png_fixed(png_ptr, green_Y, "cHRM Red Y"), + png_fixed(png_ptr, green_Z, "cHRM Red Z"), + png_fixed(png_ptr, blue_X, "cHRM Red X"), + png_fixed(png_ptr, blue_Y, "cHRM Red Y"), + png_fixed(png_ptr, blue_Z, "cHRM Red Z")); +} +# endif /* FLOATING_POINT */ + +#endif /* cHRM */ #ifdef PNG_gAMA_SUPPORTED void PNGFAPI -png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point - file_gamma) +png_set_gAMA_fixed(png_const_structrp png_ptr, png_inforp info_ptr, + png_fixed_point file_gamma) { png_debug1(1, "in %s storage function", "gAMA"); if (png_ptr == NULL || info_ptr == NULL) return; - /* Changed in libpng-1.5.4 to limit the values to ensure overflow can't - * occur. Since the fixed point representation is assymetrical it is - * possible for 1/gamma to overflow the limit of 21474 and this means the - * gamma value must be at least 5/100000 and hence at most 20000.0. For - * safety the limits here are a little narrower. The values are 0.00016 to - * 6250.0, which are truely ridiculous gammma values (and will produce - * displays that are all black or all white.) - */ - if (file_gamma < 16 || file_gamma > 625000000) - png_warning(png_ptr, "Out of range gamma value ignored"); - - else - { - info_ptr->gamma = file_gamma; - info_ptr->valid |= PNG_INFO_gAMA; - } + png_colorspace_set_gamma(png_ptr, &info_ptr->colorspace, file_gamma); + png_colorspace_sync_info(png_ptr, info_ptr); } # ifdef PNG_FLOATING_POINT_SUPPORTED void PNGAPI -png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma) +png_set_gAMA(png_const_structrp png_ptr, png_inforp info_ptr, double file_gamma) { png_set_gAMA_fixed(png_ptr, info_ptr, png_fixed(png_ptr, file_gamma, "png_set_gAMA")); @@ -152,7 +188,8 @@ png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma) #ifdef PNG_hIST_SUPPORTED void PNGAPI -png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_const_uint_16p hist) +png_set_hIST(png_const_structrp png_ptr, png_inforp info_ptr, + png_const_uint_16p hist) { int i; @@ -175,26 +212,26 @@ png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_const_uint_16p hist) /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in * version 1.2.1 */ - png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr, - PNG_MAX_PALETTE_LENGTH * png_sizeof(png_uint_16)); + info_ptr->hist = png_voidcast(png_uint_16p, png_malloc_warn(png_ptr, + PNG_MAX_PALETTE_LENGTH * (sizeof (png_uint_16)))); - if (png_ptr->hist == NULL) + if (info_ptr->hist == NULL) { png_warning(png_ptr, "Insufficient memory for hIST chunk data"); return; } - for (i = 0; i < info_ptr->num_palette; i++) - png_ptr->hist[i] = hist[i]; - - info_ptr->hist = png_ptr->hist; - info_ptr->valid |= PNG_INFO_hIST; info_ptr->free_me |= PNG_FREE_HIST; + + for (i = 0; i < info_ptr->num_palette; i++) + info_ptr->hist[i] = hist[i]; + + info_ptr->valid |= PNG_INFO_hIST; } #endif void PNGAPI -png_set_IHDR(png_structp png_ptr, png_infop info_ptr, +png_set_IHDR(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth, int color_type, int interlace_type, int compression_type, int filter_type) @@ -219,32 +256,23 @@ png_set_IHDR(png_structp png_ptr, png_infop info_ptr, if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) info_ptr->channels = 1; - else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) + else if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0) info_ptr->channels = 3; else info_ptr->channels = 1; - if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA) + if ((info_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0) info_ptr->channels++; info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth); - /* Check for potential overflow */ - if (width > - (PNG_UINT_32_MAX >> 3) /* 8-byte RRGGBBAA pixels */ - - 48 /* bigrowbuf hack */ - - 1 /* filter byte */ - - 7*8 /* rounding of width to multiple of 8 pixels */ - - 8) /* extra max_pixel_depth pad */ - info_ptr->rowbytes = 0; - else - info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, width); + info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, width); } #ifdef PNG_oFFs_SUPPORTED void PNGAPI -png_set_oFFs(png_structp png_ptr, png_infop info_ptr, +png_set_oFFs(png_const_structrp png_ptr, png_inforp info_ptr, png_int_32 offset_x, png_int_32 offset_y, int unit_type) { png_debug1(1, "in %s storage function", "oFFs"); @@ -261,7 +289,7 @@ png_set_oFFs(png_structp png_ptr, png_infop info_ptr, #ifdef PNG_pCAL_SUPPORTED void PNGAPI -png_set_pCAL(png_structp png_ptr, png_infop info_ptr, +png_set_pCAL(png_const_structrp png_ptr, png_inforp info_ptr, png_const_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams, png_const_charp units, png_charpp params) { @@ -270,10 +298,11 @@ png_set_pCAL(png_structp png_ptr, png_infop info_ptr, png_debug1(1, "in %s storage function", "pCAL"); - if (png_ptr == NULL || info_ptr == NULL) + if (png_ptr == NULL || info_ptr == NULL || purpose == NULL || units == NULL + || (nparams > 0 && params == NULL)) return; - length = png_strlen(purpose) + 1; + length = strlen(purpose) + 1; png_debug1(3, "allocating purpose for info (%lu bytes)", (unsigned long)length); @@ -283,12 +312,19 @@ png_set_pCAL(png_structp png_ptr, png_infop info_ptr, if (type < 0 || type > 3) png_error(png_ptr, "Invalid pCAL equation type"); + if (nparams < 0 || nparams > 255) + png_error(png_ptr, "Invalid pCAL parameter count"); + /* Validate params[nparams] */ for (i=0; ipcal_purpose = (png_charp)png_malloc_warn(png_ptr, length); + info_ptr->pcal_purpose = png_voidcast(png_charp, + png_malloc_warn(png_ptr, length)); if (info_ptr->pcal_purpose == NULL) { @@ -296,7 +332,7 @@ png_set_pCAL(png_structp png_ptr, png_infop info_ptr, return; } - png_memcpy(info_ptr->pcal_purpose, purpose, length); + memcpy(info_ptr->pcal_purpose, purpose, length); png_debug(3, "storing X0, X1, type, and nparams in info"); info_ptr->pcal_X0 = X0; @@ -304,11 +340,12 @@ png_set_pCAL(png_structp png_ptr, png_infop info_ptr, info_ptr->pcal_type = (png_byte)type; info_ptr->pcal_nparams = (png_byte)nparams; - length = png_strlen(units) + 1; + length = strlen(units) + 1; png_debug1(3, "allocating units for info (%lu bytes)", (unsigned long)length); - info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length); + info_ptr->pcal_units = png_voidcast(png_charp, + png_malloc_warn(png_ptr, length)); if (info_ptr->pcal_units == NULL) { @@ -316,10 +353,10 @@ png_set_pCAL(png_structp png_ptr, png_infop info_ptr, return; } - png_memcpy(info_ptr->pcal_units, units, length); + memcpy(info_ptr->pcal_units, units, length); - info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr, - (png_size_t)((nparams + 1) * png_sizeof(png_charp))); + info_ptr->pcal_params = png_voidcast(png_charpp, png_malloc_warn(png_ptr, + (png_size_t)((nparams + 1) * (sizeof (png_charp))))); if (info_ptr->pcal_params == NULL) { @@ -327,11 +364,11 @@ png_set_pCAL(png_structp png_ptr, png_infop info_ptr, return; } - png_memset(info_ptr->pcal_params, 0, (nparams + 1) * png_sizeof(png_charp)); + memset(info_ptr->pcal_params, 0, (nparams + 1) * (sizeof (png_charp))); for (i = 0; i < nparams; i++) { - length = png_strlen(params[i]) + 1; + length = strlen(params[i]) + 1; png_debug2(3, "allocating parameter %d for info (%lu bytes)", i, (unsigned long)length); @@ -343,7 +380,7 @@ png_set_pCAL(png_structp png_ptr, png_infop info_ptr, return; } - png_memcpy(info_ptr->pcal_params[i], params[i], length); + memcpy(info_ptr->pcal_params[i], params[i], length); } info_ptr->valid |= PNG_INFO_pCAL; @@ -353,7 +390,7 @@ png_set_pCAL(png_structp png_ptr, png_infop info_ptr, #ifdef PNG_sCAL_SUPPORTED void PNGAPI -png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr, +png_set_sCAL_s(png_const_structrp png_ptr, png_inforp info_ptr, int unit, png_const_charp swidth, png_const_charp sheight) { png_size_t lengthw = 0, lengthh = 0; @@ -369,11 +406,11 @@ png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr, if (unit != 1 && unit != 2) png_error(png_ptr, "Invalid sCAL unit"); - if (swidth == NULL || (lengthw = png_strlen(swidth)) == 0 || + if (swidth == NULL || (lengthw = strlen(swidth)) == 0 || swidth[0] == 45 /* '-' */ || !png_check_fp_string(swidth, lengthw)) png_error(png_ptr, "Invalid sCAL width"); - if (sheight == NULL || (lengthh = png_strlen(sheight)) == 0 || + if (sheight == NULL || (lengthh = strlen(sheight)) == 0 || sheight[0] == 45 /* '-' */ || !png_check_fp_string(sheight, lengthh)) png_error(png_ptr, "Invalid sCAL height"); @@ -383,7 +420,8 @@ png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr, png_debug1(3, "allocating unit for info (%u bytes)", (unsigned int)lengthw); - info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, lengthw); + info_ptr->scal_s_width = png_voidcast(png_charp, + png_malloc_warn(png_ptr, lengthw)); if (info_ptr->scal_s_width == NULL) { @@ -391,13 +429,14 @@ png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr, return; } - png_memcpy(info_ptr->scal_s_width, swidth, lengthw); + memcpy(info_ptr->scal_s_width, swidth, lengthw); ++lengthh; png_debug1(3, "allocating unit for info (%u bytes)", (unsigned int)lengthh); - info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, lengthh); + info_ptr->scal_s_height = png_voidcast(png_charp, + png_malloc_warn(png_ptr, lengthh)); if (info_ptr->scal_s_height == NULL) { @@ -408,7 +447,7 @@ png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr, return; } - png_memcpy(info_ptr->scal_s_height, sheight, lengthh); + memcpy(info_ptr->scal_s_height, sheight, lengthh); info_ptr->valid |= PNG_INFO_sCAL; info_ptr->free_me |= PNG_FREE_SCAL; @@ -416,8 +455,8 @@ png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr, # ifdef PNG_FLOATING_POINT_SUPPORTED void PNGAPI -png_set_sCAL(png_structp png_ptr, png_infop info_ptr, int unit, double width, - double height) +png_set_sCAL(png_const_structrp png_ptr, png_inforp info_ptr, int unit, + double width, double height) { png_debug1(1, "in %s storage function", "sCAL"); @@ -434,9 +473,9 @@ png_set_sCAL(png_structp png_ptr, png_infop info_ptr, int unit, double width, char swidth[PNG_sCAL_MAX_DIGITS+1]; char sheight[PNG_sCAL_MAX_DIGITS+1]; - png_ascii_from_fp(png_ptr, swidth, sizeof swidth, width, + png_ascii_from_fp(png_ptr, swidth, (sizeof swidth), width, PNG_sCAL_PRECISION); - png_ascii_from_fp(png_ptr, sheight, sizeof sheight, height, + png_ascii_from_fp(png_ptr, sheight, (sizeof sheight), height, PNG_sCAL_PRECISION); png_set_sCAL_s(png_ptr, info_ptr, unit, swidth, sheight); @@ -446,7 +485,7 @@ png_set_sCAL(png_structp png_ptr, png_infop info_ptr, int unit, double width, # ifdef PNG_FIXED_POINT_SUPPORTED void PNGAPI -png_set_sCAL_fixed(png_structp png_ptr, png_infop info_ptr, int unit, +png_set_sCAL_fixed(png_const_structrp png_ptr, png_inforp info_ptr, int unit, png_fixed_point width, png_fixed_point height) { png_debug1(1, "in %s storage function", "sCAL"); @@ -464,8 +503,8 @@ png_set_sCAL_fixed(png_structp png_ptr, png_infop info_ptr, int unit, char swidth[PNG_sCAL_MAX_DIGITS+1]; char sheight[PNG_sCAL_MAX_DIGITS+1]; - png_ascii_from_fixed(png_ptr, swidth, sizeof swidth, width); - png_ascii_from_fixed(png_ptr, sheight, sizeof sheight, height); + png_ascii_from_fixed(png_ptr, swidth, (sizeof swidth), width); + png_ascii_from_fixed(png_ptr, sheight, (sizeof sheight), height); png_set_sCAL_s(png_ptr, info_ptr, unit, swidth, sheight); } @@ -475,7 +514,7 @@ png_set_sCAL_fixed(png_structp png_ptr, png_infop info_ptr, int unit, #ifdef PNG_pHYs_SUPPORTED void PNGAPI -png_set_pHYs(png_structp png_ptr, png_infop info_ptr, +png_set_pHYs(png_const_structrp png_ptr, png_inforp info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type) { png_debug1(1, "in %s storage function", "pHYs"); @@ -491,7 +530,7 @@ png_set_pHYs(png_structp png_ptr, png_infop info_ptr, #endif void PNGAPI -png_set_PLTE(png_structp png_ptr, png_infop info_ptr, +png_set_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_const_colorp palette, int num_palette) { @@ -526,6 +565,9 @@ png_set_PLTE(png_structp png_ptr, png_infop info_ptr, /* It may not actually be necessary to set png_ptr->palette here; * we do it for backward compatibility with the way the png_handle_tRNS * function used to do the allocation. + * + * 1.6.0: the above statement appears to be incorrect; something has to set + * the palette inside png_struct on read. */ png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0); @@ -533,10 +575,11 @@ png_set_PLTE(png_structp png_ptr, png_infop info_ptr, * of num_palette entries, in case of an invalid PNG file that has * too-large sample values. */ - png_ptr->palette = (png_colorp)png_calloc(png_ptr, - PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color)); + png_ptr->palette = png_voidcast(png_colorp, png_calloc(png_ptr, + PNG_MAX_PALETTE_LENGTH * (sizeof (png_color)))); - png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof(png_color)); + if (num_palette > 0) + memcpy(png_ptr->palette, palette, num_palette * (sizeof (png_color))); info_ptr->palette = png_ptr->palette; info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette; @@ -547,34 +590,34 @@ png_set_PLTE(png_structp png_ptr, png_infop info_ptr, #ifdef PNG_sBIT_SUPPORTED void PNGAPI -png_set_sBIT(png_structp png_ptr, png_infop info_ptr, +png_set_sBIT(png_const_structrp png_ptr, png_inforp info_ptr, png_const_color_8p sig_bit) { png_debug1(1, "in %s storage function", "sBIT"); - if (png_ptr == NULL || info_ptr == NULL) + if (png_ptr == NULL || info_ptr == NULL || sig_bit == NULL) return; - png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof(png_color_8)); + info_ptr->sig_bit = *sig_bit; info_ptr->valid |= PNG_INFO_sBIT; } #endif #ifdef PNG_sRGB_SUPPORTED void PNGAPI -png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int srgb_intent) +png_set_sRGB(png_const_structrp png_ptr, png_inforp info_ptr, int srgb_intent) { png_debug1(1, "in %s storage function", "sRGB"); if (png_ptr == NULL || info_ptr == NULL) return; - info_ptr->srgb_intent = (png_byte)srgb_intent; - info_ptr->valid |= PNG_INFO_sRGB; + (void)png_colorspace_set_sRGB(png_ptr, &info_ptr->colorspace, srgb_intent); + png_colorspace_sync_info(png_ptr, info_ptr); } void PNGAPI -png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr, +png_set_sRGB_gAMA_and_cHRM(png_const_structrp png_ptr, png_inforp info_ptr, int srgb_intent) { png_debug1(1, "in %s storage function", "sRGB_gAMA_and_cHRM"); @@ -582,71 +625,87 @@ png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr, if (png_ptr == NULL || info_ptr == NULL) return; - png_set_sRGB(png_ptr, info_ptr, srgb_intent); + if (png_colorspace_set_sRGB(png_ptr, &info_ptr->colorspace, + srgb_intent) != 0) + { + /* This causes the gAMA and cHRM to be written too */ + info_ptr->colorspace.flags |= + PNG_COLORSPACE_FROM_gAMA|PNG_COLORSPACE_FROM_cHRM; + } -# ifdef PNG_gAMA_SUPPORTED - png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_sRGB_INVERSE); -# endif - -# ifdef PNG_cHRM_SUPPORTED - png_set_cHRM_fixed(png_ptr, info_ptr, - /* color x y */ - /* white */ 31270L, 32900L, - /* red */ 64000L, 33000L, - /* green */ 30000L, 60000L, - /* blue */ 15000L, 6000L - ); -# endif /* cHRM */ + png_colorspace_sync_info(png_ptr, info_ptr); } #endif /* sRGB */ #ifdef PNG_iCCP_SUPPORTED void PNGAPI -png_set_iCCP(png_structp png_ptr, png_infop info_ptr, +png_set_iCCP(png_const_structrp png_ptr, png_inforp info_ptr, png_const_charp name, int compression_type, png_const_bytep profile, png_uint_32 proflen) { png_charp new_iccp_name; png_bytep new_iccp_profile; - png_uint_32 length; + png_size_t length; png_debug1(1, "in %s storage function", "iCCP"); if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL) return; - length = png_strlen(name)+1; - new_iccp_name = (png_charp)png_malloc_warn(png_ptr, length); + if (compression_type != PNG_COMPRESSION_TYPE_BASE) + png_app_error(png_ptr, "Invalid iCCP compression method"); + + /* Set the colorspace first because this validates the profile; do not + * override previously set app cHRM or gAMA here (because likely as not the + * application knows better than libpng what the correct values are.) Pass + * the info_ptr color_type field to png_colorspace_set_ICC because in the + * write case it has not yet been stored in png_ptr. + */ + { + int result = png_colorspace_set_ICC(png_ptr, &info_ptr->colorspace, name, + proflen, profile, info_ptr->color_type); + + png_colorspace_sync_info(png_ptr, info_ptr); + + /* Don't do any of the copying if the profile was bad, or inconsistent. */ + if (result == 0) + return; + + /* But do write the gAMA and cHRM chunks from the profile. */ + info_ptr->colorspace.flags |= + PNG_COLORSPACE_FROM_gAMA|PNG_COLORSPACE_FROM_cHRM; + } + + length = strlen(name)+1; + new_iccp_name = png_voidcast(png_charp, png_malloc_warn(png_ptr, length)); if (new_iccp_name == NULL) { - png_warning(png_ptr, "Insufficient memory to process iCCP chunk"); + png_benign_error(png_ptr, "Insufficient memory to process iCCP chunk"); return; } - png_memcpy(new_iccp_name, name, length); - new_iccp_profile = (png_bytep)png_malloc_warn(png_ptr, proflen); + memcpy(new_iccp_name, name, length); + new_iccp_profile = png_voidcast(png_bytep, + png_malloc_warn(png_ptr, proflen)); if (new_iccp_profile == NULL) { - png_free (png_ptr, new_iccp_name); - png_warning(png_ptr, + png_free(png_ptr, new_iccp_name); + new_iccp_name = NULL; + png_benign_error(png_ptr, "Insufficient memory to process iCCP profile"); return; } - png_memcpy(new_iccp_profile, profile, (png_size_t)proflen); + memcpy(new_iccp_profile, profile, proflen); png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0); info_ptr->iccp_proflen = proflen; info_ptr->iccp_name = new_iccp_name; info_ptr->iccp_profile = new_iccp_profile; - /* Compression is always zero but is here so the API and info structure - * does not have to change if we introduce multiple compression types - */ - info_ptr->iccp_compression = (png_byte)compression_type; info_ptr->free_me |= PNG_FREE_ICCP; info_ptr->valid |= PNG_INFO_iCCP; } @@ -654,74 +713,81 @@ png_set_iCCP(png_structp png_ptr, png_infop info_ptr, #ifdef PNG_TEXT_SUPPORTED void PNGAPI -png_set_text(png_structp png_ptr, png_infop info_ptr, png_const_textp text_ptr, - int num_text) +png_set_text(png_const_structrp png_ptr, png_inforp info_ptr, + png_const_textp text_ptr, int num_text) { int ret; ret = png_set_text_2(png_ptr, info_ptr, text_ptr, num_text); - if (ret) + if (ret != 0) png_error(png_ptr, "Insufficient memory to store text"); } int /* PRIVATE */ -png_set_text_2(png_structp png_ptr, png_infop info_ptr, +png_set_text_2(png_const_structrp png_ptr, png_inforp info_ptr, png_const_textp text_ptr, int num_text) { int i; - png_debug1(1, "in %s storage function", ((png_ptr == NULL || - png_ptr->chunk_name[0] == '\0') ? - "text" : (png_const_charp)png_ptr->chunk_name)); + png_debug1(1, "in %lx storage function", png_ptr == NULL ? "unexpected" : + (unsigned long)png_ptr->chunk_name); - if (png_ptr == NULL || info_ptr == NULL || num_text == 0) + if (png_ptr == NULL || info_ptr == NULL || num_text <= 0 || text_ptr == NULL) return(0); /* Make sure we have enough space in the "text" array in info_struct - * to hold all of the incoming text_ptr objects. + * to hold all of the incoming text_ptr objects. This compare can't overflow + * because max_text >= num_text (anyway, subtract of two positive integers + * can't overflow in any case.) */ - if (info_ptr->num_text + num_text > info_ptr->max_text) + if (num_text > info_ptr->max_text - info_ptr->num_text) { - if (info_ptr->text != NULL) + int old_num_text = info_ptr->num_text; + int max_text; + png_textp new_text = NULL; + + /* Calculate an appropriate max_text, checking for overflow. */ + max_text = old_num_text; + if (num_text <= INT_MAX - max_text) { - png_textp old_text; - int old_max; + max_text += num_text; - old_max = info_ptr->max_text; - info_ptr->max_text = info_ptr->num_text + num_text + 8; - old_text = info_ptr->text; - info_ptr->text = (png_textp)png_malloc_warn(png_ptr, - (png_size_t)(info_ptr->max_text * png_sizeof(png_text))); + /* Round up to a multiple of 8 */ + if (max_text < INT_MAX-8) + max_text = (max_text + 8) & ~0x7; - if (info_ptr->text == NULL) - { - png_free(png_ptr, old_text); - return(1); - } + else + max_text = INT_MAX; - png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max * - png_sizeof(png_text))); - png_free(png_ptr, old_text); + /* Now allocate a new array and copy the old members in; this does all + * the overflow checks. + */ + new_text = png_voidcast(png_textp,png_realloc_array(png_ptr, + info_ptr->text, old_num_text, max_text-old_num_text, + sizeof *new_text)); } - else + if (new_text == NULL) { - info_ptr->max_text = num_text + 8; - info_ptr->num_text = 0; - info_ptr->text = (png_textp)png_malloc_warn(png_ptr, - (png_size_t)(info_ptr->max_text * png_sizeof(png_text))); - if (info_ptr->text == NULL) - return(1); - info_ptr->free_me |= PNG_FREE_TEXT; + png_chunk_report(png_ptr, "too many text chunks", + PNG_CHUNK_WRITE_ERROR); + return 1; } - png_debug1(3, "allocated %d entries for info_ptr->text", - info_ptr->max_text); + png_free(png_ptr, info_ptr->text); + + info_ptr->text = new_text; + info_ptr->free_me |= PNG_FREE_TEXT; + info_ptr->max_text = max_text; + /* num_text is adjusted below as the entries are copied in */ + + png_debug1(3, "allocated %d entries for info_ptr->text", max_text); } + for (i = 0; i < num_text; i++) { - png_size_t text_length, key_len; - png_size_t lang_len, lang_key_len; + size_t text_length, key_len; + size_t lang_len, lang_key_len; png_textp textp = &(info_ptr->text[info_ptr->num_text]); if (text_ptr[i].key == NULL) @@ -730,11 +796,12 @@ png_set_text_2(png_structp png_ptr, png_infop info_ptr, if (text_ptr[i].compression < PNG_TEXT_COMPRESSION_NONE || text_ptr[i].compression >= PNG_TEXT_COMPRESSION_LAST) { - png_warning(png_ptr, "text compression mode is out of range"); + png_chunk_report(png_ptr, "text compression mode is out of range", + PNG_CHUNK_WRITE_ERROR); continue; } - key_len = png_strlen(text_ptr[i].key); + key_len = strlen(text_ptr[i].key); if (text_ptr[i].compression <= 0) { @@ -748,20 +815,21 @@ png_set_text_2(png_structp png_ptr, png_infop info_ptr, /* Set iTXt data */ if (text_ptr[i].lang != NULL) - lang_len = png_strlen(text_ptr[i].lang); + lang_len = strlen(text_ptr[i].lang); else lang_len = 0; if (text_ptr[i].lang_key != NULL) - lang_key_len = png_strlen(text_ptr[i].lang_key); + lang_key_len = strlen(text_ptr[i].lang_key); else lang_key_len = 0; } # else /* PNG_iTXt_SUPPORTED */ { - png_warning(png_ptr, "iTXt chunk not supported"); + png_chunk_report(png_ptr, "iTXt chunk not supported", + PNG_CHUNK_WRITE_ERROR); continue; } # endif @@ -780,32 +848,35 @@ png_set_text_2(png_structp png_ptr, png_infop info_ptr, else { - text_length = png_strlen(text_ptr[i].text); + text_length = strlen(text_ptr[i].text); textp->compression = text_ptr[i].compression; } - textp->key = (png_charp)png_malloc_warn(png_ptr, - (png_size_t) - (key_len + text_length + lang_len + lang_key_len + 4)); + textp->key = png_voidcast(png_charp,png_malloc_base(png_ptr, + key_len + text_length + lang_len + lang_key_len + 4)); if (textp->key == NULL) - return(1); + { + png_chunk_report(png_ptr, "text chunk: out of memory", + PNG_CHUNK_WRITE_ERROR); + return 1; + } png_debug2(2, "Allocated %lu bytes at %p in png_set_text", (unsigned long)(png_uint_32) (key_len + lang_len + lang_key_len + text_length + 4), textp->key); - png_memcpy(textp->key, text_ptr[i].key,(png_size_t)(key_len)); + memcpy(textp->key, text_ptr[i].key, key_len); *(textp->key + key_len) = '\0'; if (text_ptr[i].compression > 0) { textp->lang = textp->key + key_len + 1; - png_memcpy(textp->lang, text_ptr[i].lang, lang_len); + memcpy(textp->lang, text_ptr[i].lang, lang_len); *(textp->lang + lang_len) = '\0'; textp->lang_key = textp->lang + lang_len + 1; - png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len); + memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len); *(textp->lang_key + lang_key_len) = '\0'; textp->text = textp->lang_key + lang_key_len + 1; } @@ -817,9 +888,8 @@ png_set_text_2(png_structp png_ptr, png_infop info_ptr, textp->text = textp->key + key_len + 1; } - if (text_length) - png_memcpy(textp->text, text_ptr[i].text, - (png_size_t)(text_length)); + if (text_length != 0) + memcpy(textp->text, text_ptr[i].text, text_length); *(textp->text + text_length) = '\0'; @@ -840,28 +910,39 @@ png_set_text_2(png_structp png_ptr, png_infop info_ptr, info_ptr->num_text++; png_debug1(3, "transferred text chunk %d", info_ptr->num_text); } + return(0); } #endif #ifdef PNG_tIME_SUPPORTED void PNGAPI -png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_const_timep mod_time) +png_set_tIME(png_const_structrp png_ptr, png_inforp info_ptr, + png_const_timep mod_time) { png_debug1(1, "in %s storage function", "tIME"); - if (png_ptr == NULL || info_ptr == NULL || - (png_ptr->mode & PNG_WROTE_tIME)) + if (png_ptr == NULL || info_ptr == NULL || mod_time == NULL || + (png_ptr->mode & PNG_WROTE_tIME) != 0) return; - png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof(png_time)); + if (mod_time->month == 0 || mod_time->month > 12 || + mod_time->day == 0 || mod_time->day > 31 || + mod_time->hour > 23 || mod_time->minute > 59 || + mod_time->second > 60) + { + png_warning(png_ptr, "Ignoring invalid time value"); + return; + } + + info_ptr->mod_time = *mod_time; info_ptr->valid |= PNG_INFO_tIME; } #endif #ifdef PNG_tRNS_SUPPORTED void PNGAPI -png_set_tRNS(png_structp png_ptr, png_infop info_ptr, +png_set_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_const_bytep trans_alpha, int num_trans, png_const_color_16p trans_color) { png_debug1(1, "in %s storage function", "tRNS"); @@ -874,16 +955,20 @@ png_set_tRNS(png_structp png_ptr, png_infop info_ptr, /* It may not actually be necessary to set png_ptr->trans_alpha here; * we do it for backward compatibility with the way the png_handle_tRNS * function used to do the allocation. + * + * 1.6.0: The above statement is incorrect; png_handle_tRNS effectively + * relies on png_set_tRNS storing the information in png_struct + * (otherwise it won't be there for the code in pngrtran.c). */ png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0); /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */ - png_ptr->trans_alpha = info_ptr->trans_alpha = - (png_bytep)png_malloc(png_ptr, (png_size_t)PNG_MAX_PALETTE_LENGTH); + png_ptr->trans_alpha = info_ptr->trans_alpha = png_voidcast(png_bytep, + png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH)); if (num_trans > 0 && num_trans <= PNG_MAX_PALETTE_LENGTH) - png_memcpy(info_ptr->trans_alpha, trans_alpha, (png_size_t)num_trans); + memcpy(info_ptr->trans_alpha, trans_alpha, (png_size_t)num_trans); } if (trans_color != NULL) @@ -891,16 +976,15 @@ png_set_tRNS(png_structp png_ptr, png_infop info_ptr, int sample_max = (1 << info_ptr->bit_depth); if ((info_ptr->color_type == PNG_COLOR_TYPE_GRAY && - (int)trans_color->gray > sample_max) || + trans_color->gray > sample_max) || (info_ptr->color_type == PNG_COLOR_TYPE_RGB && - ((int)trans_color->red > sample_max || - (int)trans_color->green > sample_max || - (int)trans_color->blue > sample_max))) + (trans_color->red > sample_max || + trans_color->green > sample_max || + trans_color->blue > sample_max))) png_warning(png_ptr, "tRNS chunk has out-of-range samples for bit_depth"); - png_memcpy(&(info_ptr->trans_color), trans_color, - png_sizeof(png_color_16)); + info_ptr->trans_color = *trans_color; if (num_trans == 0) num_trans = 1; @@ -918,8 +1002,8 @@ png_set_tRNS(png_structp png_ptr, png_infop info_ptr, #ifdef PNG_sPLT_SUPPORTED void PNGAPI -png_set_sPLT(png_structp png_ptr, - png_infop info_ptr, png_const_sPLT_tp entries, int nentries) +png_set_sPLT(png_const_structrp png_ptr, + png_inforp info_ptr, png_const_sPLT_tp entries, int nentries) /* * entries - array of png_sPLT_t structures * to be added to the list of palettes @@ -930,220 +1014,455 @@ png_set_sPLT(png_structp png_ptr, */ { png_sPLT_tp np; - int i; - if (png_ptr == NULL || info_ptr == NULL) + if (png_ptr == NULL || info_ptr == NULL || nentries <= 0 || entries == NULL) return; - np = (png_sPLT_tp)png_malloc_warn(png_ptr, - (info_ptr->splt_palettes_num + nentries) * - (png_size_t)png_sizeof(png_sPLT_t)); + /* Use the internal realloc function, which checks for all the possible + * overflows. Notice that the parameters are (int) and (size_t) + */ + np = png_voidcast(png_sPLT_tp,png_realloc_array(png_ptr, + info_ptr->splt_palettes, info_ptr->splt_palettes_num, nentries, + sizeof *np)); if (np == NULL) { - png_warning(png_ptr, "No memory for sPLT palettes"); + /* Out of memory or too many chunks */ + png_chunk_report(png_ptr, "too many sPLT chunks", PNG_CHUNK_WRITE_ERROR); return; } - png_memcpy(np, info_ptr->splt_palettes, - info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t)); - png_free(png_ptr, info_ptr->splt_palettes); - info_ptr->splt_palettes=NULL; + info_ptr->splt_palettes = np; + info_ptr->free_me |= PNG_FREE_SPLT; - for (i = 0; i < nentries; i++) + np += info_ptr->splt_palettes_num; + + do { - png_sPLT_tp to = np + info_ptr->splt_palettes_num + i; - png_const_sPLT_tp from = entries + i; - png_uint_32 length; + png_size_t length; - length = png_strlen(from->name) + 1; - to->name = (png_charp)png_malloc_warn(png_ptr, (png_size_t)length); - - if (to->name == NULL) + /* Skip invalid input entries */ + if (entries->name == NULL || entries->entries == NULL) { - png_warning(png_ptr, - "Out of memory while processing sPLT chunk"); + /* png_handle_sPLT doesn't do this, so this is an app error */ + png_app_error(png_ptr, "png_set_sPLT: invalid sPLT"); + /* Just skip the invalid entry */ continue; } - png_memcpy(to->name, from->name, length); - to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr, - (png_size_t)(from->nentries * png_sizeof(png_sPLT_entry))); + np->depth = entries->depth; - if (to->entries == NULL) + /* In the event of out-of-memory just return - there's no point keeping + * on trying to add sPLT chunks. + */ + length = strlen(entries->name) + 1; + np->name = png_voidcast(png_charp, png_malloc_base(png_ptr, length)); + + if (np->name == NULL) + break; + + memcpy(np->name, entries->name, length); + + /* IMPORTANT: we have memory now that won't get freed if something else + * goes wrong; this code must free it. png_malloc_array produces no + * warnings; use a png_chunk_report (below) if there is an error. + */ + np->entries = png_voidcast(png_sPLT_entryp, png_malloc_array(png_ptr, + entries->nentries, sizeof (png_sPLT_entry))); + + if (np->entries == NULL) { - png_warning(png_ptr, - "Out of memory while processing sPLT chunk"); - png_free(png_ptr, to->name); - to->name = NULL; - continue; + png_free(png_ptr, np->name); + np->name = NULL; + break; } - png_memcpy(to->entries, from->entries, - from->nentries * png_sizeof(png_sPLT_entry)); + np->nentries = entries->nentries; + /* This multiply can't overflow because png_malloc_array has already + * checked it when doing the allocation. + */ + memcpy(np->entries, entries->entries, + entries->nentries * sizeof (png_sPLT_entry)); - to->nentries = from->nentries; - to->depth = from->depth; + /* Note that 'continue' skips the advance of the out pointer and out + * count, so an invalid entry is not added. + */ + info_ptr->valid |= PNG_INFO_sPLT; + ++(info_ptr->splt_palettes_num); + ++np; + } + while (++entries, --nentries); + + if (nentries > 0) + png_chunk_report(png_ptr, "sPLT out of memory", PNG_CHUNK_WRITE_ERROR); +} +#endif /* sPLT */ + +#ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED +static png_byte +check_location(png_const_structrp png_ptr, int location) +{ + location &= (PNG_HAVE_IHDR|PNG_HAVE_PLTE|PNG_AFTER_IDAT); + + /* New in 1.6.0; copy the location and check it. This is an API + * change; previously the app had to use the + * png_set_unknown_chunk_location API below for each chunk. + */ + if (location == 0 && (png_ptr->mode & PNG_IS_READ_STRUCT) == 0) + { + /* Write struct, so unknown chunks come from the app */ + png_app_warning(png_ptr, + "png_set_unknown_chunks now expects a valid location"); + /* Use the old behavior */ + location = (png_byte)(png_ptr->mode & + (PNG_HAVE_IHDR|PNG_HAVE_PLTE|PNG_AFTER_IDAT)); } - info_ptr->splt_palettes = np; - info_ptr->splt_palettes_num += nentries; - info_ptr->valid |= PNG_INFO_sPLT; - info_ptr->free_me |= PNG_FREE_SPLT; -} -#endif /* PNG_sPLT_SUPPORTED */ + /* This need not be an internal error - if the app calls + * png_set_unknown_chunks on a read pointer it must get the location right. + */ + if (location == 0) + png_error(png_ptr, "invalid location in png_set_unknown_chunks"); + + /* Now reduce the location to the top-most set bit by removing each least + * significant bit in turn. + */ + while (location != (location & -location)) + location &= ~(location & -location); + + /* The cast is safe because 'location' is a bit mask and only the low four + * bits are significant. + */ + return (png_byte)location; +} -#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED void PNGAPI -png_set_unknown_chunks(png_structp png_ptr, - png_infop info_ptr, png_const_unknown_chunkp unknowns, int num_unknowns) +png_set_unknown_chunks(png_const_structrp png_ptr, + png_inforp info_ptr, png_const_unknown_chunkp unknowns, int num_unknowns) { png_unknown_chunkp np; - int i; - if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0) + if (png_ptr == NULL || info_ptr == NULL || num_unknowns <= 0 || + unknowns == NULL) return; - np = (png_unknown_chunkp)png_malloc_warn(png_ptr, - (png_size_t)(info_ptr->unknown_chunks_num + num_unknowns) * - png_sizeof(png_unknown_chunk)); + /* Check for the failure cases where support has been disabled at compile + * time. This code is hardly ever compiled - it's here because + * STORE_UNKNOWN_CHUNKS is set by both read and write code (compiling in this + * code) but may be meaningless if the read or write handling of unknown + * chunks is not compiled in. + */ +# if !defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) && \ + defined(PNG_READ_SUPPORTED) + if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0) + { + png_app_error(png_ptr, "no unknown chunk support on read"); + return; + } +# endif +# if !defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED) && \ + defined(PNG_WRITE_SUPPORTED) + if ((png_ptr->mode & PNG_IS_READ_STRUCT) == 0) + { + png_app_error(png_ptr, "no unknown chunk support on write"); + return; + } +# endif + + /* Prior to 1.6.0 this code used png_malloc_warn; however, this meant that + * unknown critical chunks could be lost with just a warning resulting in + * undefined behavior. Now png_chunk_report is used to provide behavior + * appropriate to read or write. + */ + np = png_voidcast(png_unknown_chunkp, png_realloc_array(png_ptr, + info_ptr->unknown_chunks, info_ptr->unknown_chunks_num, num_unknowns, + sizeof *np)); if (np == NULL) { - png_warning(png_ptr, - "Out of memory while processing unknown chunk"); + png_chunk_report(png_ptr, "too many unknown chunks", + PNG_CHUNK_WRITE_ERROR); return; } - png_memcpy(np, info_ptr->unknown_chunks, - (png_size_t)info_ptr->unknown_chunks_num * - png_sizeof(png_unknown_chunk)); - png_free(png_ptr, info_ptr->unknown_chunks); - info_ptr->unknown_chunks = NULL; + info_ptr->unknown_chunks = np; /* safe because it is initialized */ + info_ptr->free_me |= PNG_FREE_UNKN; - for (i = 0; i < num_unknowns; i++) + np += info_ptr->unknown_chunks_num; + + /* Increment unknown_chunks_num each time round the loop to protect the + * just-allocated chunk data. + */ + for (; num_unknowns > 0; --num_unknowns, ++unknowns) { - png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i; - png_const_unknown_chunkp from = unknowns + i; + memcpy(np->name, unknowns->name, (sizeof np->name)); + np->name[(sizeof np->name)-1] = '\0'; + np->location = check_location(png_ptr, unknowns->location); - png_memcpy(to->name, from->name, png_sizeof(from->name)); - to->name[png_sizeof(to->name)-1] = '\0'; - to->size = from->size; - - /* Note our location in the read or write sequence */ - to->location = (png_byte)(png_ptr->mode & 0xff); - - if (from->size == 0) - to->data=NULL; + if (unknowns->size == 0) + { + np->data = NULL; + np->size = 0; + } else { - to->data = (png_bytep)png_malloc_warn(png_ptr, - (png_size_t)from->size); + np->data = png_voidcast(png_bytep, + png_malloc_base(png_ptr, unknowns->size)); - if (to->data == NULL) + if (np->data == NULL) { - png_warning(png_ptr, - "Out of memory while processing unknown chunk"); - to->size = 0; + png_chunk_report(png_ptr, "unknown chunk: out of memory", + PNG_CHUNK_WRITE_ERROR); + /* But just skip storing the unknown chunk */ + continue; } - else - png_memcpy(to->data, from->data, from->size); + memcpy(np->data, unknowns->data, unknowns->size); + np->size = unknowns->size; } - } - info_ptr->unknown_chunks = np; - info_ptr->unknown_chunks_num += num_unknowns; - info_ptr->free_me |= PNG_FREE_UNKN; + /* These increments are skipped on out-of-memory for the data - the + * unknown chunk entry gets overwritten if the png_chunk_report returns. + * This is correct in the read case (the chunk is just dropped.) + */ + ++np; + ++(info_ptr->unknown_chunks_num); + } } void PNGAPI -png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr, +png_set_unknown_chunk_location(png_const_structrp png_ptr, png_inforp info_ptr, int chunk, int location) { - if (png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk < - info_ptr->unknown_chunks_num) - info_ptr->unknown_chunks[chunk].location = (png_byte)location; + /* This API is pretty pointless in 1.6.0 because the location can be set + * before the call to png_set_unknown_chunks. + * + * TODO: add a png_app_warning in 1.7 + */ + if (png_ptr != NULL && info_ptr != NULL && chunk >= 0 && + chunk < info_ptr->unknown_chunks_num) + { + if ((location & (PNG_HAVE_IHDR|PNG_HAVE_PLTE|PNG_AFTER_IDAT)) == 0) + { + png_app_error(png_ptr, "invalid unknown chunk location"); + /* Fake out the pre 1.6.0 behavior: */ + if ((location & PNG_HAVE_IDAT) != 0) /* undocumented! */ + location = PNG_AFTER_IDAT; + + else + location = PNG_HAVE_IHDR; /* also undocumented */ + } + + info_ptr->unknown_chunks[chunk].location = + check_location(png_ptr, location); + } } #endif #ifdef PNG_MNG_FEATURES_SUPPORTED png_uint_32 PNGAPI -png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features) +png_permit_mng_features (png_structrp png_ptr, png_uint_32 mng_features) { png_debug(1, "in png_permit_mng_features"); if (png_ptr == NULL) - return (png_uint_32)0; + return 0; - png_ptr->mng_features_permitted = - (png_byte)(mng_features & PNG_ALL_MNG_FEATURES); + png_ptr->mng_features_permitted = mng_features & PNG_ALL_MNG_FEATURES; - return (png_uint_32)png_ptr->mng_features_permitted; + return png_ptr->mng_features_permitted; } #endif #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED -void PNGAPI -png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_const_bytep - chunk_list, int num_chunks) +static unsigned int +add_one_chunk(png_bytep list, unsigned int count, png_const_bytep add, int keep) { - png_bytep new_list, p; - int i, old_num_chunks; + unsigned int i; + + /* Utility function: update the 'keep' state of a chunk if it is already in + * the list, otherwise add it to the list. + */ + for (i=0; i= PNG_HANDLE_CHUNK_LAST) { - if (keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE) - png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS; - - else - png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS; - - if (keep == PNG_HANDLE_CHUNK_ALWAYS) - png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS; - - else - png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS; - + png_app_error(png_ptr, "png_set_keep_unknown_chunks: invalid keep"); return; } - if (chunk_list == NULL) - return; + if (num_chunks_in <= 0) + { + png_ptr->unknown_default = keep; + + /* '0' means just set the flags, so stop here */ + if (num_chunks_in == 0) + return; + } + + if (num_chunks_in < 0) + { + /* Ignore all unknown chunks and all chunks recognized by + * libpng except for IHDR, PLTE, tRNS, IDAT, and IEND + */ + static PNG_CONST png_byte chunks_to_ignore[] = { + 98, 75, 71, 68, '\0', /* bKGD */ + 99, 72, 82, 77, '\0', /* cHRM */ + 103, 65, 77, 65, '\0', /* gAMA */ + 104, 73, 83, 84, '\0', /* hIST */ + 105, 67, 67, 80, '\0', /* iCCP */ + 105, 84, 88, 116, '\0', /* iTXt */ + 111, 70, 70, 115, '\0', /* oFFs */ + 112, 67, 65, 76, '\0', /* pCAL */ + 112, 72, 89, 115, '\0', /* pHYs */ + 115, 66, 73, 84, '\0', /* sBIT */ + 115, 67, 65, 76, '\0', /* sCAL */ + 115, 80, 76, 84, '\0', /* sPLT */ + 115, 84, 69, 82, '\0', /* sTER */ + 115, 82, 71, 66, '\0', /* sRGB */ + 116, 69, 88, 116, '\0', /* tEXt */ + 116, 73, 77, 69, '\0', /* tIME */ + 122, 84, 88, 116, '\0' /* zTXt */ + }; + + chunk_list = chunks_to_ignore; + num_chunks = (unsigned int)/*SAFE*/(sizeof chunks_to_ignore)/5U; + } + + else /* num_chunks_in > 0 */ + { + if (chunk_list == NULL) + { + /* Prior to 1.6.0 this was silently ignored, now it is an app_error + * which can be switched off. + */ + png_app_error(png_ptr, "png_set_keep_unknown_chunks: no chunk list"); + return; + } + + num_chunks = num_chunks_in; + } old_num_chunks = png_ptr->num_chunk_list; - new_list=(png_bytep)png_malloc(png_ptr, - (png_size_t)(5*(num_chunks + old_num_chunks))); + if (png_ptr->chunk_list == NULL) + old_num_chunks = 0; - if (png_ptr->chunk_list != NULL) + /* Since num_chunks is always restricted to UINT_MAX/5 this can't overflow. + */ + if (num_chunks + old_num_chunks > UINT_MAX/5) { - png_memcpy(new_list, png_ptr->chunk_list, - (png_size_t)(5*old_num_chunks)); - png_free(png_ptr, png_ptr->chunk_list); - png_ptr->chunk_list=NULL; + png_app_error(png_ptr, "png_set_keep_unknown_chunks: too many chunks"); + return; } - png_memcpy(new_list + 5*old_num_chunks, chunk_list, - (png_size_t)(5*num_chunks)); + /* If these chunks are being reset to the default then no more memory is + * required because add_one_chunk above doesn't extend the list if the 'keep' + * parameter is the default. + */ + if (keep != 0) + { + new_list = png_voidcast(png_bytep, png_malloc(png_ptr, + 5 * (num_chunks + old_num_chunks))); - for (p = new_list + 5*old_num_chunks + 4, i = 0; i 0) + memcpy(new_list, png_ptr->chunk_list, 5*old_num_chunks); + } - png_ptr->num_chunk_list = old_num_chunks + num_chunks; - png_ptr->chunk_list = new_list; - png_ptr->free_me |= PNG_FREE_LIST; + else if (old_num_chunks > 0) + new_list = png_ptr->chunk_list; + + else + new_list = NULL; + + /* Add the new chunks together with each one's handling code. If the chunk + * already exists the code is updated, otherwise the chunk is added to the + * end. (In libpng 1.6.0 order no longer matters because this code enforces + * the earlier convention that the last setting is the one that is used.) + */ + if (new_list != NULL) + { + png_const_bytep inlist; + png_bytep outlist; + unsigned int i; + + for (i=0; ichunk_list != new_list) + png_free(png_ptr, new_list); + + new_list = NULL; + } + } + + else + num_chunks = 0; + + png_ptr->num_chunk_list = num_chunks; + + if (png_ptr->chunk_list != new_list) + { + if (png_ptr->chunk_list != NULL) + png_free(png_ptr, png_ptr->chunk_list); + + png_ptr->chunk_list = new_list; + } } #endif #ifdef PNG_READ_USER_CHUNKS_SUPPORTED void PNGAPI -png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr, +png_set_read_user_chunk_fn(png_structrp png_ptr, png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn) { png_debug(1, "in png_set_read_user_chunk_fn"); @@ -1158,64 +1477,90 @@ png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr, #ifdef PNG_INFO_IMAGE_SUPPORTED void PNGAPI -png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers) +png_set_rows(png_const_structrp png_ptr, png_inforp info_ptr, + png_bytepp row_pointers) { png_debug1(1, "in %s storage function", "rows"); if (png_ptr == NULL || info_ptr == NULL) return; - if (info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers)) + if (info_ptr->row_pointers != NULL && + (info_ptr->row_pointers != row_pointers)) png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0); info_ptr->row_pointers = row_pointers; - if (row_pointers) + if (row_pointers != NULL) info_ptr->valid |= PNG_INFO_IDAT; } #endif void PNGAPI -png_set_compression_buffer_size(png_structp png_ptr, png_size_t size) +png_set_compression_buffer_size(png_structrp png_ptr, png_size_t size) { if (png_ptr == NULL) return; - png_free(png_ptr, png_ptr->zbuf); + if (size == 0 || size > PNG_UINT_31_MAX) + png_error(png_ptr, "invalid compression buffer size"); - if (size > ZLIB_IO_MAX) - { - png_warning(png_ptr, "Attempt to set buffer size beyond max ignored"); - png_ptr->zbuf_size = ZLIB_IO_MAX; - size = ZLIB_IO_MAX; /* must fit */ - } +# ifdef PNG_SEQUENTIAL_READ_SUPPORTED + if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0) + { + png_ptr->IDAT_read_size = (png_uint_32)size; /* checked above */ + return; + } +# endif - else - png_ptr->zbuf_size = (uInt)size; +# ifdef PNG_WRITE_SUPPORTED + if ((png_ptr->mode & PNG_IS_READ_STRUCT) == 0) + { + if (png_ptr->zowner != 0) + { + png_warning(png_ptr, + "Compression buffer size cannot be changed because it is in use"); + return; + } - png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size); + if (size > ZLIB_IO_MAX) + { + png_warning(png_ptr, + "Compression buffer size limited to system maximum"); + size = ZLIB_IO_MAX; /* must fit */ + } - /* The following ensures a relatively safe failure if this gets called while - * the buffer is actually in use. - */ - png_ptr->zstream.next_out = png_ptr->zbuf; - png_ptr->zstream.avail_out = 0; - png_ptr->zstream.avail_in = 0; + else if (size < 6) + { + /* Deflate will potentially go into an infinite loop on a SYNC_FLUSH + * if this is permitted. + */ + png_warning(png_ptr, + "Compression buffer size cannot be reduced below 6"); + return; + } + + if (png_ptr->zbuffer_size != size) + { + png_free_buffer_list(png_ptr, &png_ptr->zbuffer_list); + png_ptr->zbuffer_size = (uInt)size; + } + } +# endif } void PNGAPI -png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask) +png_set_invalid(png_const_structrp png_ptr, png_inforp info_ptr, int mask) { - if (png_ptr && info_ptr) + if (png_ptr != NULL && info_ptr != NULL) info_ptr->valid &= ~mask; } - #ifdef PNG_SET_USER_LIMITS_SUPPORTED /* This function was added to libpng 1.2.6 */ void PNGAPI -png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max, +png_set_user_limits (png_structrp png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max) { /* Images with dimensions larger than these limits will be @@ -1231,35 +1576,64 @@ png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max, /* This function was added to libpng 1.4.0 */ void PNGAPI -png_set_chunk_cache_max (png_structp png_ptr, - png_uint_32 user_chunk_cache_max) +png_set_chunk_cache_max (png_structrp png_ptr, png_uint_32 user_chunk_cache_max) { - if (png_ptr) + if (png_ptr != NULL) png_ptr->user_chunk_cache_max = user_chunk_cache_max; } /* This function was added to libpng 1.4.1 */ void PNGAPI -png_set_chunk_malloc_max (png_structp png_ptr, +png_set_chunk_malloc_max (png_structrp png_ptr, png_alloc_size_t user_chunk_malloc_max) { - if (png_ptr) + if (png_ptr != NULL) png_ptr->user_chunk_malloc_max = user_chunk_malloc_max; } -#endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */ +#endif /* ?SET_USER_LIMITS */ #ifdef PNG_BENIGN_ERRORS_SUPPORTED void PNGAPI -png_set_benign_errors(png_structp png_ptr, int allowed) +png_set_benign_errors(png_structrp png_ptr, int allowed) { png_debug(1, "in png_set_benign_errors"); - if (allowed) - png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN; + /* If allowed is 1, png_benign_error() is treated as a warning. + * + * If allowed is 0, png_benign_error() is treated as an error (which + * is the default behavior if png_set_benign_errors() is not called). + */ + + if (allowed != 0) + png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN | + PNG_FLAG_APP_WARNINGS_WARN | PNG_FLAG_APP_ERRORS_WARN; else - png_ptr->flags &= ~PNG_FLAG_BENIGN_ERRORS_WARN; + png_ptr->flags &= ~(PNG_FLAG_BENIGN_ERRORS_WARN | + PNG_FLAG_APP_WARNINGS_WARN | PNG_FLAG_APP_ERRORS_WARN); } -#endif /* PNG_BENIGN_ERRORS_SUPPORTED */ -#endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */ +#endif /* BENIGN_ERRORS */ + +#ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED + /* Whether to report invalid palette index; added at libng-1.5.10. + * It is possible for an indexed (color-type==3) PNG file to contain + * pixels with invalid (out-of-range) indexes if the PLTE chunk has + * fewer entries than the image's bit-depth would allow. We recover + * from this gracefully by filling any incomplete palette with zeros + * (opaque black). By default, when this occurs libpng will issue + * a benign error. This API can be used to override that behavior. + */ +void PNGAPI +png_set_check_for_invalid_index(png_structrp png_ptr, int allowed) +{ + png_debug(1, "in png_set_check_for_invalid_index"); + + if (allowed > 0) + png_ptr->num_palette_max = 0; + + else + png_ptr->num_palette_max = -1; +} +#endif +#endif /* READ || WRITE */ diff --git a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngstruct.h b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngstruct.h index 6a587e34b58..8670a5a4e8d 100644 --- a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngstruct.h +++ b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngstruct.h @@ -29,11 +29,11 @@ * However, the following notice accompanied the original version of this * file and, per its terms, should not be removed: * - * Copyright (c) 1998-2011 Glenn Randers-Pehrson + * Copyright (c) 1998-2013 Glenn Randers-Pehrson * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) * - * Last changed in libpng 1.5.4 [July 7, 2011] + * Last changed in libpng 1.6.1 [March 28, 2013] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer @@ -52,13 +52,130 @@ * in this structure and is required for decompressing the LZ compressed * data in PNG files. */ +#ifndef ZLIB_CONST + /* We must ensure that zlib uses 'const' in declarations. */ +# define ZLIB_CONST +#endif #include "zlib.h" +#ifdef const + /* zlib.h sometimes #defines const to nothing, undo this. */ +# undef const +#endif + +/* zlib.h has mediocre z_const use before 1.2.6, this stuff is for compatibility + * with older builds. + */ +#if ZLIB_VERNUM < 0x1260 +# define PNGZ_MSG_CAST(s) png_constcast(char*,s) +# define PNGZ_INPUT_CAST(b) png_constcast(png_bytep,b) +#else +# define PNGZ_MSG_CAST(s) (s) +# define PNGZ_INPUT_CAST(b) (b) +#endif + +/* zlib.h declares a magic type 'uInt' that limits the amount of data that zlib + * can handle at once. This type need be no larger than 16 bits (so maximum of + * 65535), this define allows us to discover how big it is, but limited by the + * maximuum for png_size_t. The value can be overriden in a library build + * (pngusr.h, or set it in CPPFLAGS) and it works to set it to a considerably + * lower value (e.g. 255 works). A lower value may help memory usage (slightly) + * and may even improve performance on some systems (and degrade it on others.) + */ +#ifndef ZLIB_IO_MAX +# define ZLIB_IO_MAX ((uInt)-1) +#endif + +#ifdef PNG_WRITE_SUPPORTED +/* The type of a compression buffer list used by the write code. */ +typedef struct png_compression_buffer +{ + struct png_compression_buffer *next; + png_byte output[1]; /* actually zbuf_size */ +} png_compression_buffer, *png_compression_bufferp; + +#define PNG_COMPRESSION_BUFFER_SIZE(pp)\ + (offsetof(png_compression_buffer, output) + (pp)->zbuffer_size) +#endif + +/* Colorspace support; structures used in png_struct, png_info and in internal + * functions to hold and communicate information about the color space. + * + * PNG_COLORSPACE_SUPPORTED is only required if the application will perform + * colorspace corrections, otherwise all the colorspace information can be + * skipped and the size of libpng can be reduced (significantly) by compiling + * out the colorspace support. + */ +#ifdef PNG_COLORSPACE_SUPPORTED +/* The chromaticities of the red, green and blue colorants and the chromaticity + * of the corresponding white point (i.e. of rgb(1.0,1.0,1.0)). + */ +typedef struct png_xy +{ + png_fixed_point redx, redy; + png_fixed_point greenx, greeny; + png_fixed_point bluex, bluey; + png_fixed_point whitex, whitey; +} png_xy; + +/* The same data as above but encoded as CIE XYZ values. When this data comes + * from chromaticities the sum of the Y values is assumed to be 1.0 + */ +typedef struct png_XYZ +{ + png_fixed_point red_X, red_Y, red_Z; + png_fixed_point green_X, green_Y, green_Z; + png_fixed_point blue_X, blue_Y, blue_Z; +} png_XYZ; +#endif /* COLORSPACE */ + +#if defined(PNG_COLORSPACE_SUPPORTED) || defined(PNG_GAMMA_SUPPORTED) +/* A colorspace is all the above plus, potentially, profile information, + * however at present libpng does not use the profile internally so it is only + * stored in the png_info struct (if iCCP is supported.) The rendering intent + * is retained here and is checked. + * + * The file gamma encoding information is also stored here and gamma correction + * is done by libpng, whereas color correction must currently be done by the + * application. + */ +typedef struct png_colorspace +{ +#ifdef PNG_GAMMA_SUPPORTED + png_fixed_point gamma; /* File gamma */ +#endif + +#ifdef PNG_COLORSPACE_SUPPORTED + png_xy end_points_xy; /* End points as chromaticities */ + png_XYZ end_points_XYZ; /* End points as CIE XYZ colorant values */ + png_uint_16 rendering_intent; /* Rendering intent of a profile */ +#endif + + /* Flags are always defined to simplify the code. */ + png_uint_16 flags; /* As defined below */ +} png_colorspace, * PNG_RESTRICT png_colorspacerp; + +typedef const png_colorspace * PNG_RESTRICT png_const_colorspacerp; + +/* General flags for the 'flags' field */ +#define PNG_COLORSPACE_HAVE_GAMMA 0x0001 +#define PNG_COLORSPACE_HAVE_ENDPOINTS 0x0002 +#define PNG_COLORSPACE_HAVE_INTENT 0x0004 +#define PNG_COLORSPACE_FROM_gAMA 0x0008 +#define PNG_COLORSPACE_FROM_cHRM 0x0010 +#define PNG_COLORSPACE_FROM_sRGB 0x0020 +#define PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB 0x0040 +#define PNG_COLORSPACE_MATCHES_sRGB 0x0080 /* exact match on profile */ +#define PNG_COLORSPACE_INVALID 0x8000 +#define PNG_COLORSPACE_CANCEL(flags) (0xffff ^ (flags)) +#endif /* COLORSPACE || GAMMA */ struct png_struct_def { #ifdef PNG_SETJMP_SUPPORTED - jmp_buf longjmp_buffer; /* used in png_error */ + jmp_buf jmp_buf_local; /* New name in 1.6.0 for jmp_buf in png_struct */ png_longjmp_ptr longjmp_fn;/* setjmp non-local goto function. */ + jmp_buf *jmp_buf_ptr; /* passed to longjmp_fn */ + size_t jmp_buf_size; /* size of the above, if allocated */ #endif png_error_ptr error_fn; /* function for printing errors and aborting */ #ifdef PNG_WARNINGS_SUPPORTED @@ -91,22 +208,12 @@ struct png_struct_def png_uint_32 flags; /* flags indicating various things to libpng */ png_uint_32 transformations; /* which transformations to perform */ - z_stream zstream; /* pointer to decompression structure (below) */ - png_bytep zbuf; /* buffer for zlib */ - uInt zbuf_size; /* size of zbuf (typically 65536) */ + png_uint_32 zowner; /* ID (chunk type) of zstream owner, 0 if none */ + z_stream zstream; /* decompression structure */ + #ifdef PNG_WRITE_SUPPORTED - -/* Added in 1.5.4: state to keep track of whether the zstream has been - * initialized and if so whether it is for IDAT or some other chunk. - */ -#define PNG_ZLIB_UNINITIALIZED 0 -#define PNG_ZLIB_FOR_IDAT 1 -#define PNG_ZLIB_FOR_TEXT 2 /* anything other than IDAT */ -#define PNG_ZLIB_USE_MASK 3 /* bottom two bits */ -#define PNG_ZLIB_IN_USE 4 /* a flag value */ - - png_uint_32 zlib_state; /* State of zlib initialization */ -/* End of material added at libpng 1.5.4 */ + png_compression_bufferp zbuffer_list; /* Created on demand during write */ + uInt zbuffer_size; /* size of the actual buffer */ int zlib_level; /* holds zlib compression level */ int zlib_method; /* holds zlib compression method */ @@ -115,8 +222,7 @@ struct png_struct_def int zlib_strategy; /* holds zlib compression strategy */ #endif /* Added at libpng 1.5.4 */ -#if defined(PNG_WRITE_COMPRESSED_TEXT_SUPPORTED) || \ - defined(PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED) +#ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED int zlib_text_level; /* holds zlib compression level */ int zlib_text_method; /* holds zlib compression method */ int zlib_text_window_bits; /* holds zlib compression window bits */ @@ -124,6 +230,14 @@ struct png_struct_def int zlib_text_strategy; /* holds zlib compression strategy */ #endif /* End of material added at libpng 1.5.4 */ +/* Added at libpng 1.6.0 */ +#ifdef PNG_WRITE_SUPPORTED + int zlib_set_level; /* Actual values set into the zstream on write */ + int zlib_set_method; + int zlib_set_window_bits; + int zlib_set_mem_level; + int zlib_set_strategy; +#endif png_uint_32 width; /* width of image in pixels */ png_uint_32 height; /* height of image in pixels */ @@ -132,21 +246,32 @@ struct png_struct_def png_size_t rowbytes; /* size of row in bytes */ png_uint_32 iwidth; /* width of current interlaced row in pixels */ png_uint_32 row_number; /* current row in interlace pass */ - png_bytep prev_row; /* buffer to save previous (unfiltered) row */ - png_bytep row_buf; /* buffer to save current (unfiltered) row */ + png_uint_32 chunk_name; /* PNG_CHUNK() id of current chunk */ + png_bytep prev_row; /* buffer to save previous (unfiltered) row. + * This is a pointer into big_prev_row + */ + png_bytep row_buf; /* buffer to save current (unfiltered) row. + * This is a pointer into big_row_buf + */ +#ifdef PNG_WRITE_SUPPORTED png_bytep sub_row; /* buffer to save "sub" row when filtering */ png_bytep up_row; /* buffer to save "up" row when filtering */ png_bytep avg_row; /* buffer to save "avg" row when filtering */ png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */ - png_row_info row_info; /* used for transformation routines */ +#endif png_size_t info_rowbytes; /* Added in 1.5.4: cache of updated row bytes */ png_uint_32 idat_size; /* current IDAT size for read */ png_uint_32 crc; /* current chunk CRC value */ png_colorp palette; /* palette from the input file */ png_uint_16 num_palette; /* number of color entries in palette */ + +/* Added at libpng-1.5.10 */ +#ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED + int num_palette_max; /* maximum palette index found in IDAT */ +#endif + png_uint_16 num_trans; /* number of transparency values */ - png_byte chunk_name[5]; /* null-terminated name of current chunk */ png_byte compression; /* file compression type (always 0) */ png_byte filter; /* file filter type (always 0) */ png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */ @@ -154,12 +279,17 @@ struct png_struct_def png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */ png_byte color_type; /* color type of file */ png_byte bit_depth; /* bit depth of file */ - png_byte usr_bit_depth; /* bit depth of users row */ + png_byte usr_bit_depth; /* bit depth of users row: write only */ png_byte pixel_depth; /* number of bits per pixel */ png_byte channels; /* number of channels in file */ - png_byte usr_channels; /* channels at start of write */ +#ifdef PNG_WRITE_SUPPORTED + png_byte usr_channels; /* channels at start of write: write only */ +#endif png_byte sig_bytes; /* magic bytes read/written from start of file */ - + png_byte maximum_pixel_depth; + /* pixel depth used for the row buffers */ + png_byte transformed_pixel_depth; + /* pixel depth after read/write transforms */ #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED) png_uint_16 filler; /* filler bytes for pixel expansion */ #endif @@ -172,7 +302,7 @@ struct png_struct_def #ifdef PNG_READ_GAMMA_SUPPORTED png_color_16 background_1; /* background normalized to gamma 1.0 */ #endif -#endif /* PNG_bKGD_SUPPORTED */ +#endif /* bKGD */ #ifdef PNG_WRITE_FLUSH_SUPPORTED png_flush_ptr output_flush_fn; /* Function for flushing output */ @@ -180,19 +310,20 @@ struct png_struct_def png_uint_32 flush_rows; /* number of rows written since last flush */ #endif -#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) +#ifdef PNG_READ_GAMMA_SUPPORTED int gamma_shift; /* number of "insignificant" bits in 16-bit gamma */ - png_fixed_point gamma; /* file gamma value */ png_fixed_point screen_gamma; /* screen gamma value (display_exponent) */ -#endif -#if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) png_bytep gamma_table; /* gamma table for 8-bit depth files */ + png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */ +#if defined(PNG_READ_BACKGROUND_SUPPORTED) || \ + defined(PNG_READ_ALPHA_MODE_SUPPORTED) || \ + defined(PNG_READ_RGB_TO_GRAY_SUPPORTED) png_bytep gamma_from_1; /* converts from 1.0 to screen */ png_bytep gamma_to_1; /* converts from file to 1.0 */ - png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */ png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */ png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */ +#endif /* READ_BACKGROUND || READ_ALPHA_MODE || RGB_TO_GRAY */ #endif #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED) @@ -228,14 +359,7 @@ struct png_struct_def int process_mode; /* what push library is currently doing */ int cur_palette; /* current push library palette index */ -# ifdef PNG_TEXT_SUPPORTED - png_size_t current_text_size; /* current size of text input data */ - png_size_t current_text_left; /* how much text left to read in input */ - png_charp current_text; /* current text chunk buffer */ - png_charp current_text_ptr; /* current location in current_text */ -# endif /* PNG_PROGRESSIVE_READ_SUPPORTED && PNG_TEXT_SUPPORTED */ - -#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */ +#endif /* PROGRESSIVE_READ */ #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__) /* For the Borland special 64K segment handler */ @@ -251,10 +375,6 @@ struct png_struct_def png_bytep quantize_index; /* index translation for palette files */ #endif -#if defined(PNG_READ_QUANTIZE_SUPPORTED) || defined(PNG_hIST_SUPPORTED) - png_uint_16p hist; /* histogram */ -#endif - #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED png_byte heuristic_method; /* heuristic for row filter selection */ png_byte num_prev_filters; /* number of weights for previous rows */ @@ -265,9 +385,17 @@ struct png_struct_def png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */ #endif + /* Options */ +#ifdef PNG_SET_OPTION_SUPPORTED + png_byte options; /* On/off state (up to 4 options) */ +#endif + +#if PNG_LIBPNG_VER < 10700 +/* To do: remove this from libpng-1.7 */ #ifdef PNG_TIME_RFC1123_SUPPORTED char time_buffer[29]; /* String to hold RFC 1123 time text */ #endif +#endif /* New members added in libpng-1.0.6 */ @@ -275,27 +403,31 @@ struct png_struct_def #ifdef PNG_USER_CHUNKS_SUPPORTED png_voidp user_chunk_ptr; +#ifdef PNG_READ_USER_CHUNKS_SUPPORTED png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */ #endif +#endif -#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED - int num_chunk_list; - png_bytep chunk_list; +#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED + int unknown_default; /* As PNG_HANDLE_* */ + unsigned int num_chunk_list; /* Number of entries in the list */ + png_bytep chunk_list; /* List of png_byte[5]; the textual chunk name + * followed by a PNG_HANDLE_* byte */ #endif /* New members added in libpng-1.0.3 */ #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED png_byte rgb_to_gray_status; + /* Added in libpng 1.5.5 to record setting of coefficients: */ + png_byte rgb_to_gray_coefficients_set; /* These were changed from png_byte in libpng-1.0.6 */ png_uint_16 rgb_to_gray_red_coeff; png_uint_16 rgb_to_gray_green_coeff; - png_uint_16 rgb_to_gray_blue_coeff; + /* deleted in 1.5.5: rgb_to_gray_blue_coeff; */ #endif /* New member added in libpng-1.0.4 (renamed in 1.0.9) */ -#if defined(PNG_MNG_FEATURES_SUPPORTED) || \ - defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \ - defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) +#if defined(PNG_MNG_FEATURES_SUPPORTED) /* Changed from png_byte to png_uint_32 at version 1.2.0 */ png_uint_32 mng_features_permitted; #endif @@ -345,21 +477,41 @@ struct png_struct_def #endif /* New member added in libpng-1.0.25 and 1.2.17 */ -#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED - /* Storage for unknown chunk that the library doesn't recognize. */ +#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED + /* Temporary storage for unknown chunk that the library doesn't recognize, + * used while reading the chunk. + */ png_unknown_chunk unknown_chunk; #endif -/* New members added in libpng-1.2.26 */ +/* New member added in libpng-1.2.26 */ png_size_t old_big_row_buf_size; - png_size_t old_prev_row_size; +#ifdef PNG_READ_SUPPORTED /* New member added in libpng-1.2.30 */ - png_charp chunkdata; /* buffer for reading chunk data */ + png_bytep read_buffer; /* buffer for reading chunk data */ + png_alloc_size_t read_buffer_size; /* current size of the buffer */ +#endif +#ifdef PNG_SEQUENTIAL_READ_SUPPORTED + uInt IDAT_read_size; /* limit on read buffer size for IDAT */ +#endif #ifdef PNG_IO_STATE_SUPPORTED /* New member added in libpng-1.4.0 */ png_uint_32 io_state; #endif + +/* New member added in libpng-1.5.6 */ + png_bytep big_prev_row; + +/* New member added in libpng-1.5.7 */ + void (*read_filter[PNG_FILTER_VALUE_LAST-1])(png_row_infop row_info, + png_bytep row, png_const_bytep prev_row); + +#ifdef PNG_READ_SUPPORTED +#if defined(PNG_COLORSPACE_SUPPORTED) || defined(PNG_GAMMA_SUPPORTED) + png_colorspace colorspace; +#endif +#endif }; #endif /* PNGSTRUCT_H */ diff --git a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngtest.c b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngtest.c index 227181fbf96..fdd51acd04d 100644 --- a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngtest.c +++ b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngtest.c @@ -29,8 +29,8 @@ * However, the following notice accompanied the original version of this * file and, per its terms, should not be removed: * - * Last changed in libpng 1.5.4 [July 7, 2011] - * Copyright (c) 1998-2011 Glenn Randers-Pehrson + * Last changed in libpng 1.6.15 [November 20, 2014] + * Copyright (c) 1998-2014 Glenn Randers-Pehrson * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) * @@ -61,16 +61,50 @@ #define _POSIX_SOURCE 1 -#include "zlib.h" +#include +#include +#include + +/* Defined so I can write to a file on gui/windowing platforms */ +/* #define STDERR stderr */ +#define STDERR stdout /* For DOS */ + #include "png.h" + +/* Known chunks that exist in pngtest.png must be supported or pngtest will fail + * simply as a result of re-ordering them. This may be fixed in 1.7 + * + * pngtest allocates a single row buffer for each row and overwrites it, + * therefore if the write side doesn't support the writing of interlaced images + * nothing can be done for an interlaced image (and the code below will fail + * horribly trying to write extra data after writing garbage). + */ +#if defined PNG_READ_SUPPORTED && /* else nothing can be done */\ + defined PNG_READ_bKGD_SUPPORTED &&\ + defined PNG_READ_cHRM_SUPPORTED &&\ + defined PNG_READ_gAMA_SUPPORTED &&\ + defined PNG_READ_oFFs_SUPPORTED &&\ + defined PNG_READ_pCAL_SUPPORTED &&\ + defined PNG_READ_pHYs_SUPPORTED &&\ + defined PNG_READ_sBIT_SUPPORTED &&\ + defined PNG_READ_sCAL_SUPPORTED &&\ + defined PNG_READ_sRGB_SUPPORTED &&\ + defined PNG_READ_tEXt_SUPPORTED &&\ + defined PNG_READ_tIME_SUPPORTED &&\ + defined PNG_READ_zTXt_SUPPORTED &&\ + defined PNG_WRITE_INTERLACING_SUPPORTED + +#ifdef PNG_ZLIB_HEADER +# include PNG_ZLIB_HEADER /* defined by pnglibconf.h from 1.7 */ +#else +# include "zlib.h" +#endif + /* Copied from pngpriv.h but only used in error messages below. */ #ifndef PNG_ZBUF_SIZE # define PNG_ZBUF_SIZE 8192 #endif -# include -# include -# include -# define FCLOSE(file) fclose(file) +#define FCLOSE(file) fclose(file) #ifndef PNG_STDIO_SUPPORTED typedef FILE * png_FILE_p; @@ -95,17 +129,6 @@ typedef FILE * png_FILE_p; # define SINGLE_ROWBUF_ALLOC /* Makes buffer overruns easier to nail */ #endif -/* The code uses memcmp and memcpy on large objects (typically row pointers) so - * it is necessary to do soemthing special on certain architectures, note that - * the actual support for this was effectively removed in 1.4, so only the - * memory remains in this program: - */ -#define CVT_PTR(ptr) (ptr) -#define CVT_PTR_NOCHECK(ptr) (ptr) -#define png_memcmp memcmp -#define png_memcpy memcpy -#define png_memset memset - /* Turn on CPU timing #define PNGTEST_TIMING */ @@ -126,30 +149,34 @@ static char tIME_string[PNG_tIME_STRING_LENGTH] = "tIME chunk is not present"; #endif static int verbose = 0; - -int test_one_file PNGARG((PNG_CONST char *inname, PNG_CONST char *outname)); - -#ifdef __TURBOC__ -#include -#endif - -/* Defined so I can write to a file on gui/windowing platforms */ -/* #define STDERR stderr */ -#define STDERR stdout /* For DOS */ +static int strict = 0; +static int relaxed = 0; +static int unsupported_chunks = 0; /* chunk unsupported by libpng in input */ +static int error_count = 0; /* count calls to png_error */ +static int warning_count = 0; /* count calls to png_warning */ /* Define png_jmpbuf() in case we are using a pre-1.0.6 version of libpng */ #ifndef png_jmpbuf # define png_jmpbuf(png_ptr) png_ptr->jmpbuf #endif +/* Defines for unknown chunk handling if required. */ +#ifndef PNG_HANDLE_CHUNK_ALWAYS +# define PNG_HANDLE_CHUNK_ALWAYS 3 +#endif +#ifndef PNG_HANDLE_CHUNK_IF_SAFE +# define PNG_HANDLE_CHUNK_IF_SAFE 2 +#endif + +/* Utility to save typing/errors, the argument must be a name */ +#define MEMZERO(var) ((void)memset(&var, 0, sizeof var)) + /* Example of using row callbacks to make a simple progress meter */ static int status_pass = 1; static int status_dots_requested = 0; static int status_dots = 1; -void PNGCBAPI -read_row_callback(png_structp png_ptr, png_uint_32 row_number, int pass); -void PNGCBAPI +static void PNGCBAPI read_row_callback(png_structp png_ptr, png_uint_32 row_number, int pass) { if (png_ptr == NULL || row_number > PNG_UINT_31_MAX) @@ -173,9 +200,8 @@ read_row_callback(png_structp png_ptr, png_uint_32 row_number, int pass) fprintf(stdout, "r"); } -void PNGCBAPI -write_row_callback(png_structp png_ptr, png_uint_32 row_number, int pass); -void PNGCBAPI +#ifdef PNG_WRITE_SUPPORTED +static void PNGCBAPI write_row_callback(png_structp png_ptr, png_uint_32 row_number, int pass) { if (png_ptr == NULL || row_number > PNG_UINT_31_MAX || pass > 7) @@ -183,6 +209,7 @@ write_row_callback(png_structp png_ptr, png_uint_32 row_number, int pass) fprintf(stdout, "w"); } +#endif #ifdef PNG_READ_USER_TRANSFORM_SUPPORTED @@ -191,9 +218,7 @@ write_row_callback(png_structp png_ptr, png_uint_32 row_number, int pass) * 5 in case illegal filter values are present.) */ static png_uint_32 filters_used[256]; -void PNGCBAPI -count_filters(png_structp png_ptr, png_row_infop row_info, png_bytep data); -void PNGCBAPI +static void PNGCBAPI count_filters(png_structp png_ptr, png_row_infop row_info, png_bytep data) { if (png_ptr != NULL && row_info != NULL) @@ -208,9 +233,7 @@ count_filters(png_structp png_ptr, png_row_infop row_info, png_bytep data) static png_uint_32 zero_samples; -void PNGCBAPI -count_zero_samples(png_structp png_ptr, png_row_infop row_info, png_bytep data); -void PNGCBAPI +static void PNGCBAPI count_zero_samples(png_structp png_ptr, png_row_infop row_info, png_bytep data) { png_bytep dp = data; @@ -288,7 +311,8 @@ count_zero_samples(png_structp png_ptr, png_row_infop row_info, png_bytep data) png_uint_32 n, nstop; int channel; int color_channels = row_info->channels; - if (row_info->color_type > 3)color_channels--; + if (row_info->color_type > 3) + color_channels--; for (n = 0, nstop=row_info->width; nfile_name != NULL) + name = test->file_name; + + fprintf(STDERR, "%s: libpng warning: %s\n", name, message); } /* This is the default error handling function. Note that replacements for @@ -566,12 +483,14 @@ pngtest_warning(png_structp png_ptr, png_const_charp message) static void PNGCBAPI pngtest_error(png_structp png_ptr, png_const_charp message) { + ++error_count; + pngtest_warning(png_ptr, message); /* We can return because png_error calls the default handler, which is * actually OK in this case. */ } -#endif /* !PNG_STDIO_SUPPORTED */ + /* END of code to validate stdio-free compilation */ /* START of code to validate memory allocation and deallocation */ @@ -590,9 +509,9 @@ typedef struct memory_information { png_alloc_size_t size; png_voidp pointer; - struct memory_information FAR *next; + struct memory_information *next; } memory_information; -typedef memory_information FAR *memory_infop; +typedef memory_information *memory_infop; static memory_infop pinformation = NULL; static int current_allocation = 0; @@ -622,7 +541,7 @@ PNGCBAPI png_debug_malloc(png_structp png_ptr, png_alloc_size_t size) memory_infop pinfo; png_set_mem_fn(png_ptr, NULL, NULL, NULL); pinfo = (memory_infop)png_malloc(png_ptr, - png_sizeof(*pinfo)); + (sizeof *pinfo)); pinfo->size = size; current_allocation += size; total_allocation += size; @@ -648,9 +567,9 @@ PNGCBAPI png_debug_malloc(png_structp png_ptr, png_alloc_size_t size) pinfo->next = pinformation; pinformation = pinfo; /* Make sure the caller isn't assuming zeroed memory. */ - png_memset(pinfo->pointer, 0xdd, pinfo->size); + memset(pinfo->pointer, 0xdd, pinfo->size); - if (verbose) + if (verbose != 0) printf("png_malloc %lu bytes at %p\n", (unsigned long)size, pinfo->pointer); @@ -675,7 +594,7 @@ png_debug_free(png_structp png_ptr, png_voidp ptr) /* Unlink the element from the list. */ { - memory_infop FAR *ppinfo = &pinformation; + memory_infop *ppinfo = &pinformation; for (;;) { @@ -689,15 +608,16 @@ png_debug_free(png_structp png_ptr, png_voidp ptr) fprintf(STDERR, "Duplicate free of memory\n"); /* We must free the list element too, but first kill the memory that is to be freed. */ - png_memset(ptr, 0x55, pinfo->size); - png_free_default(png_ptr, pinfo); + memset(ptr, 0x55, pinfo->size); + if (pinfo != NULL) + free(pinfo); pinfo = NULL; break; } if (pinfo->next == NULL) { - fprintf(STDERR, "Pointer %x not found\n", (unsigned int)ptr); + fprintf(STDERR, "Pointer %p not found\n", ptr); break; } @@ -706,35 +626,84 @@ png_debug_free(png_structp png_ptr, png_voidp ptr) } /* Finally free the data. */ - if (verbose) + if (verbose != 0) printf("Freeing %p\n", ptr); - png_free_default(png_ptr, ptr); + if (ptr != NULL) + free(ptr); ptr = NULL; } -#endif /* PNG_USER_MEM_SUPPORTED && PNG_DEBUG */ +#endif /* USER_MEM && DEBUG */ /* END of code to test memory allocation/deallocation */ +#ifdef PNG_READ_USER_CHUNKS_SUPPORTED /* Demonstration of user chunk support of the sTER and vpAg chunks */ -#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED /* (sTER is a public chunk not yet known by libpng. vpAg is a private chunk used in ImageMagick to store "virtual page" size). */ -static png_uint_32 user_chunk_data[4]; - - /* 0: sTER mode + 1 - * 1: vpAg width - * 2: vpAg height - * 3: vpAg units - */ - -static int PNGCBAPI read_user_chunk_callback(png_struct *png_ptr, - png_unknown_chunkp chunk) +static struct user_chunk_data { - png_uint_32 - *my_user_chunk_data; + png_const_infop info_ptr; + png_uint_32 vpAg_width, vpAg_height; + png_byte vpAg_units; + png_byte sTER_mode; + int location[2]; +} +user_chunk_data; + +/* Used for location and order; zero means nothing. */ +#define have_sTER 0x01 +#define have_vpAg 0x02 +#define before_PLTE 0x10 +#define before_IDAT 0x20 +#define after_IDAT 0x40 + +static void +init_callback_info(png_const_infop info_ptr) +{ + MEMZERO(user_chunk_data); + user_chunk_data.info_ptr = info_ptr; +} + +static int +set_location(png_structp png_ptr, struct user_chunk_data *data, int what) +{ + int location; + + if ((data->location[0] & what) != 0 || (data->location[1] & what) != 0) + return 0; /* already have one of these */ + + /* Find where we are (the code below zeroes info_ptr to indicate that the + * chunks before the first IDAT have been read.) + */ + if (data->info_ptr == NULL) /* after IDAT */ + location = what | after_IDAT; + + else if (png_get_valid(png_ptr, data->info_ptr, PNG_INFO_PLTE) != 0) + location = what | before_IDAT; + + else + location = what | before_PLTE; + + if (data->location[0] == 0) + data->location[0] = location; + + else + data->location[1] = location; + + return 1; /* handled */ +} + +static int PNGCBAPI +read_user_chunk_callback(png_struct *png_ptr, png_unknown_chunkp chunk) +{ + struct user_chunk_data *my_user_chunk_data = + (struct user_chunk_data*)png_get_user_chunk_ptr(png_ptr); + + if (my_user_chunk_data == NULL) + png_error(png_ptr, "lost user chunk pointer"); /* Return one of the following: * return (-n); chunk had an error @@ -759,9 +728,14 @@ static int PNGCBAPI read_user_chunk_callback(png_struct *png_ptr, if (chunk->data[0] != 0 && chunk->data[0] != 1) return (-1); /* Invalid mode */ - my_user_chunk_data=(png_uint_32 *) png_get_user_chunk_ptr(png_ptr); - my_user_chunk_data[0]=chunk->data[0]+1; - return (1); + if (set_location(png_ptr, my_user_chunk_data, have_sTER) != 0) + { + my_user_chunk_data->sTER_mode=chunk->data[0]; + return (1); + } + + else + return (0); /* duplicate sTER - give it to libpng */ } if (chunk->name[0] != 118 || chunk->name[1] != 112 || /* v p */ @@ -773,30 +747,126 @@ static int PNGCBAPI read_user_chunk_callback(png_struct *png_ptr, if (chunk->size != 9) return (-1); /* Error return */ - my_user_chunk_data=(png_uint_32 *) png_get_user_chunk_ptr(png_ptr); + if (set_location(png_ptr, my_user_chunk_data, have_vpAg) == 0) + return (0); /* duplicate vpAg */ - my_user_chunk_data[1]=png_get_uint_31(png_ptr, chunk->data); - my_user_chunk_data[2]=png_get_uint_31(png_ptr, chunk->data + 4); - my_user_chunk_data[3]=(png_uint_32)chunk->data[8]; + my_user_chunk_data->vpAg_width = png_get_uint_31(png_ptr, chunk->data); + my_user_chunk_data->vpAg_height = png_get_uint_31(png_ptr, chunk->data + 4); + my_user_chunk_data->vpAg_units = chunk->data[8]; return (1); - } + +#ifdef PNG_WRITE_SUPPORTED +static void +write_sTER_chunk(png_structp write_ptr) +{ + png_byte sTER[5] = {115, 84, 69, 82, '\0'}; + + if (verbose != 0) + fprintf(STDERR, "\n stereo mode = %d\n", user_chunk_data.sTER_mode); + + png_write_chunk(write_ptr, sTER, &user_chunk_data.sTER_mode, 1); +} + +static void +write_vpAg_chunk(png_structp write_ptr) +{ + png_byte vpAg[5] = {118, 112, 65, 103, '\0'}; + + png_byte vpag_chunk_data[9]; + + if (verbose != 0) + fprintf(STDERR, " vpAg = %lu x %lu, units = %d\n", + (unsigned long)user_chunk_data.vpAg_width, + (unsigned long)user_chunk_data.vpAg_height, + user_chunk_data.vpAg_units); + + png_save_uint_32(vpag_chunk_data, user_chunk_data.vpAg_width); + png_save_uint_32(vpag_chunk_data + 4, user_chunk_data.vpAg_height); + vpag_chunk_data[8] = user_chunk_data.vpAg_units; + png_write_chunk(write_ptr, vpAg, vpag_chunk_data, 9); +} + +static void +write_chunks(png_structp write_ptr, int location) +{ + int i; + + /* Notice that this preserves the original chunk order, however chunks + * intercepted by the callback will be written *after* chunks passed to + * libpng. This will actually reverse a pair of sTER chunks or a pair of + * vpAg chunks, resulting in an error later. This is not worth worrying + * about - the chunks should not be duplicated! + */ + for (i=0; i<2; ++i) + { + if (user_chunk_data.location[i] == (location | have_sTER)) + write_sTER_chunk(write_ptr); + + else if (user_chunk_data.location[i] == (location | have_vpAg)) + write_vpAg_chunk(write_ptr); + } +} +#endif /* WRITE */ +#else /* !READ_USER_CHUNKS */ +# define write_chunks(pp,loc) ((void)0) #endif /* END of code to demonstrate user chunk support */ +/* START of code to check that libpng has the required text support; this only + * checks for the write support because if read support is missing the chunk + * will simply not be reported back to pngtest. + */ +#ifdef PNG_TEXT_SUPPORTED +static void +pngtest_check_text_support(png_const_structp png_ptr, png_textp text_ptr, + int num_text) +{ + while (num_text > 0) + { + switch (text_ptr[--num_text].compression) + { + case PNG_TEXT_COMPRESSION_NONE: + break; + + case PNG_TEXT_COMPRESSION_zTXt: +# ifndef PNG_WRITE_zTXt_SUPPORTED + ++unsupported_chunks; +# endif + break; + + case PNG_ITXT_COMPRESSION_NONE: + case PNG_ITXT_COMPRESSION_zTXt: +# ifndef PNG_WRITE_iTXt_SUPPORTED + ++unsupported_chunks; +# endif + break; + + default: + /* This is an error */ + png_error(png_ptr, "invalid text chunk compression field"); + break; + } + } +} +#endif +/* END of code to check that libpng has the required text support */ + /* Test one file */ -int +static int test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) { static png_FILE_p fpin; static png_FILE_p fpout; /* "static" prevents setjmp corruption */ + pngtest_error_parameters error_parameters; png_structp read_ptr; png_infop read_info_ptr, end_info_ptr; #ifdef PNG_WRITE_SUPPORTED png_structp write_ptr; png_infop write_info_ptr; png_infop write_end_info_ptr; + int interlace_preserved = 1; #else png_structp write_ptr = NULL; png_infop write_info_ptr = NULL; @@ -805,17 +875,11 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) png_bytep row_buf; png_uint_32 y; png_uint_32 width, height; - int num_pass, pass; + int num_pass = 1, pass; int bit_depth, color_type; -#ifdef PNG_SETJMP_SUPPORTED -#ifdef USE_FAR_KEYWORD - jmp_buf tmp_jmpbuf; -#endif -#endif - - char inbuf[256], outbuf[256]; row_buf = NULL; + error_parameters.file_name = inname; if ((fpin = fopen(inname, "rb")) == NULL) { @@ -839,20 +903,9 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); #endif -#ifndef PNG_STDIO_SUPPORTED - png_set_error_fn(read_ptr, (png_voidp)inname, pngtest_error, - pngtest_warning); -#endif + png_set_error_fn(read_ptr, &error_parameters, pngtest_error, + pngtest_warning); -#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED - user_chunk_data[0] = 0; - user_chunk_data[1] = 0; - user_chunk_data[2] = 0; - user_chunk_data[3] = 0; - png_set_read_user_chunk_fn(read_ptr, user_chunk_data, - read_user_chunk_callback); - -#endif #ifdef PNG_WRITE_SUPPORTED #if defined(PNG_USER_MEM_SUPPORTED) && PNG_DEBUG write_ptr = @@ -862,10 +915,8 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); #endif -#ifndef PNG_STDIO_SUPPORTED - png_set_error_fn(write_ptr, (png_voidp)inname, pngtest_error, - pngtest_warning); -#endif + png_set_error_fn(write_ptr, &error_parameters, pngtest_error, + pngtest_warning); #endif pngtest_debug("Allocating read_info, write_info and end_info structures"); read_info_ptr = png_create_info_struct(read_ptr); @@ -875,13 +926,15 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) write_end_info_ptr = png_create_info_struct(write_ptr); #endif +#ifdef PNG_READ_USER_CHUNKS_SUPPORTED + init_callback_info(read_info_ptr); + png_set_read_user_chunk_fn(read_ptr, &user_chunk_data, + read_user_chunk_callback); +#endif + #ifdef PNG_SETJMP_SUPPORTED pngtest_debug("Setting jmpbuf for read struct"); -#ifdef USE_FAR_KEYWORD - if (setjmp(tmp_jmpbuf)) -#else if (setjmp(png_jmpbuf(read_ptr))) -#endif { fprintf(STDERR, "%s -> %s: libpng read error\n", inname, outname); png_free(read_ptr, row_buf); @@ -895,18 +948,11 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) FCLOSE(fpout); return (1); } -#ifdef USE_FAR_KEYWORD - png_memcpy(png_jmpbuf(read_ptr), tmp_jmpbuf, png_sizeof(jmp_buf)); -#endif #ifdef PNG_WRITE_SUPPORTED pngtest_debug("Setting jmpbuf for write struct"); -#ifdef USE_FAR_KEYWORD - if (setjmp(tmp_jmpbuf)) -#else if (setjmp(png_jmpbuf(write_ptr))) -#endif { fprintf(STDERR, "%s -> %s: libpng write error\n", inname, outname); png_destroy_read_struct(&read_ptr, &read_info_ptr, &end_info_ptr); @@ -918,12 +964,34 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) FCLOSE(fpout); return (1); } +#endif +#endif -#ifdef USE_FAR_KEYWORD - png_memcpy(png_jmpbuf(write_ptr), tmp_jmpbuf, png_sizeof(jmp_buf)); -#endif + if (strict != 0) + { + /* Treat png_benign_error() as errors on read */ + png_set_benign_errors(read_ptr, 0); + +#ifdef PNG_WRITE_SUPPORTED + /* Treat them as errors on write */ + png_set_benign_errors(write_ptr, 0); #endif + + /* if strict is not set, then app warnings and errors are treated as + * warnings in release builds, but not in unstable builds; this can be + * changed with '--relaxed'. + */ + } + + else if (relaxed != 0) + { + /* Allow application (pngtest) errors and warnings to pass */ + png_set_benign_errors(read_ptr, 1); + +#ifdef PNG_WRITE_SUPPORTED + png_set_benign_errors(write_ptr, 1); #endif + } pngtest_debug("Initializing input and output streams"); #ifdef PNG_STDIO_SUPPORTED @@ -943,14 +1011,6 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) # endif #endif -#ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED - /* Normally one would use Z_DEFAULT_STRATEGY for text compression. - * This is here just to make pngtest replicate the results from libpng - * versions prior to 1.5.4, and to test this new API. - */ - png_set_text_compression_strategy(write_ptr, Z_FILTERED); -#endif - if (status_dots_requested == 1) { #ifdef PNG_WRITE_SUPPORTED @@ -982,36 +1042,65 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) png_set_write_user_transform_fn(write_ptr, count_zero_samples); #endif -#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED -# ifndef PNG_HANDLE_CHUNK_ALWAYS -# define PNG_HANDLE_CHUNK_ALWAYS 3 -# endif +#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED + /* Preserve all the unknown chunks, if possible. If this is disabled then, + * even if the png_{get,set}_unknown_chunks stuff is enabled, we can't use + * libpng to *save* the unknown chunks on read (because we can't switch the + * save option on!) + * + * Notice that if SET_UNKNOWN_CHUNKS is *not* supported read will discard all + * unknown chunks and write will write them all. + */ +#ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED png_set_keep_unknown_chunks(read_ptr, PNG_HANDLE_CHUNK_ALWAYS, NULL, 0); #endif #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED -# ifndef PNG_HANDLE_CHUNK_IF_SAFE -# define PNG_HANDLE_CHUNK_IF_SAFE 2 -# endif - png_set_keep_unknown_chunks(write_ptr, PNG_HANDLE_CHUNK_IF_SAFE, + png_set_keep_unknown_chunks(write_ptr, PNG_HANDLE_CHUNK_ALWAYS, NULL, 0); +#endif #endif pngtest_debug("Reading info struct"); png_read_info(read_ptr, read_info_ptr); +#ifdef PNG_READ_USER_CHUNKS_SUPPORTED + /* This is a bit of a hack; there is no obvious way in the callback function + * to determine that the chunks before the first IDAT have been read, so + * remove the info_ptr (which is only used to determine position relative to + * PLTE) here to indicate that we are after the IDAT. + */ + user_chunk_data.info_ptr = NULL; +#endif + pngtest_debug("Transferring info struct"); { int interlace_type, compression_type, filter_type; if (png_get_IHDR(read_ptr, read_info_ptr, &width, &height, &bit_depth, - &color_type, &interlace_type, &compression_type, &filter_type)) + &color_type, &interlace_type, &compression_type, &filter_type) != 0) { png_set_IHDR(write_ptr, write_info_ptr, width, height, bit_depth, -#ifdef PNG_WRITE_INTERLACING_SUPPORTED color_type, interlace_type, compression_type, filter_type); -#else - color_type, PNG_INTERLACE_NONE, compression_type, filter_type); +#ifndef PNG_READ_INTERLACING_SUPPORTED + /* num_pass will not be set below, set it here if the image is + * interlaced: what happens is that write interlacing is *not* turned + * on an the partial interlaced rows are written directly. + */ + switch (interlace_type) + { + case PNG_INTERLACE_NONE: + num_pass = 1; + break; + + case PNG_INTERLACE_ADAM7: + num_pass = 7; + break; + + default: + png_error(read_ptr, "invalid interlace type"); + /*NOT REACHED*/ + } #endif } } @@ -1022,7 +1111,7 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) blue_y; if (png_get_cHRM_fixed(read_ptr, read_info_ptr, &white_x, &white_y, - &red_x, &red_y, &green_x, &green_y, &blue_x, &blue_y)) + &red_x, &red_y, &green_x, &green_y, &blue_x, &blue_y) != 0) { png_set_cHRM_fixed(write_ptr, write_info_ptr, white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y); @@ -1033,7 +1122,7 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) { png_fixed_point gamma; - if (png_get_gAMA_fixed(read_ptr, read_info_ptr, &gamma)) + if (png_get_gAMA_fixed(read_ptr, read_info_ptr, &gamma) != 0) png_set_gAMA_fixed(write_ptr, write_info_ptr, gamma); } #endif @@ -1045,7 +1134,7 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) blue_y; if (png_get_cHRM(read_ptr, read_info_ptr, &white_x, &white_y, &red_x, - &red_y, &green_x, &green_y, &blue_x, &blue_y)) + &red_y, &green_x, &green_y, &blue_x, &blue_y) != 0) { png_set_cHRM(write_ptr, write_info_ptr, white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y); @@ -1056,7 +1145,7 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) { double gamma; - if (png_get_gAMA(read_ptr, read_info_ptr, &gamma)) + if (png_get_gAMA(read_ptr, read_info_ptr, &gamma) != 0) png_set_gAMA(write_ptr, write_info_ptr, gamma); } #endif @@ -1070,7 +1159,7 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) int compression_type; if (png_get_iCCP(read_ptr, read_info_ptr, &name, &compression_type, - &profile, &proflen)) + &profile, &proflen) != 0) { png_set_iCCP(write_ptr, write_info_ptr, name, compression_type, profile, proflen); @@ -1081,7 +1170,7 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) { int intent; - if (png_get_sRGB(read_ptr, read_info_ptr, &intent)) + if (png_get_sRGB(read_ptr, read_info_ptr, &intent) != 0) png_set_sRGB(write_ptr, write_info_ptr, intent); } #endif @@ -1089,14 +1178,14 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) png_colorp palette; int num_palette; - if (png_get_PLTE(read_ptr, read_info_ptr, &palette, &num_palette)) + if (png_get_PLTE(read_ptr, read_info_ptr, &palette, &num_palette) != 0) png_set_PLTE(write_ptr, write_info_ptr, palette, num_palette); } #ifdef PNG_bKGD_SUPPORTED { png_color_16p background; - if (png_get_bKGD(read_ptr, read_info_ptr, &background)) + if (png_get_bKGD(read_ptr, read_info_ptr, &background) != 0) { png_set_bKGD(write_ptr, write_info_ptr, background); } @@ -1106,7 +1195,7 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) { png_uint_16p hist; - if (png_get_hIST(read_ptr, read_info_ptr, &hist)) + if (png_get_hIST(read_ptr, read_info_ptr, &hist) != 0) png_set_hIST(write_ptr, write_info_ptr, hist); } #endif @@ -1116,7 +1205,7 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) int unit_type; if (png_get_oFFs(read_ptr, read_info_ptr, &offset_x, &offset_y, - &unit_type)) + &unit_type) != 0) { png_set_oFFs(write_ptr, write_info_ptr, offset_x, offset_y, unit_type); } @@ -1130,7 +1219,7 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) int type, nparams; if (png_get_pCAL(read_ptr, read_info_ptr, &purpose, &X0, &X1, &type, - &nparams, &units, ¶ms)) + &nparams, &units, ¶ms) != 0) { png_set_pCAL(write_ptr, write_info_ptr, purpose, X0, X1, type, nparams, units, params); @@ -1142,7 +1231,8 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) png_uint_32 res_x, res_y; int unit_type; - if (png_get_pHYs(read_ptr, read_info_ptr, &res_x, &res_y, &unit_type)) + if (png_get_pHYs(read_ptr, read_info_ptr, &res_x, &res_y, + &unit_type) != 0) png_set_pHYs(write_ptr, write_info_ptr, res_x, res_y, unit_type); } #endif @@ -1150,18 +1240,19 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) { png_color_8p sig_bit; - if (png_get_sBIT(read_ptr, read_info_ptr, &sig_bit)) + if (png_get_sBIT(read_ptr, read_info_ptr, &sig_bit) != 0) png_set_sBIT(write_ptr, write_info_ptr, sig_bit); } #endif #ifdef PNG_sCAL_SUPPORTED -#ifdef PNG_FLOATING_POINT_SUPPORTED +#if defined(PNG_FLOATING_POINT_SUPPORTED) && \ + defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) { int unit; double scal_width, scal_height; if (png_get_sCAL(read_ptr, read_info_ptr, &unit, &scal_width, - &scal_height)) + &scal_height) != 0) { png_set_sCAL(write_ptr, write_info_ptr, unit, scal_width, scal_height); } @@ -1173,7 +1264,7 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) png_charp scal_width, scal_height; if (png_get_sCAL_s(read_ptr, read_info_ptr, &unit, &scal_width, - &scal_height)) + &scal_height) != 0) { png_set_sCAL_s(write_ptr, write_info_ptr, unit, scal_width, scal_height); @@ -1190,6 +1281,21 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) if (png_get_text(read_ptr, read_info_ptr, &text_ptr, &num_text) > 0) { pngtest_debug1("Handling %d iTXt/tEXt/zTXt chunks", num_text); + + pngtest_check_text_support(read_ptr, text_ptr, num_text); + + if (verbose != 0) + { + int i; + + printf("\n"); + for (i=0; i 0) { pngtest_debug1("Handling %d iTXt/tEXt/zTXt chunks", num_text); + + pngtest_check_text_support(read_ptr, text_ptr, num_text); + + if (verbose != 0) + { + int i; + + printf("\n"); + for (i=0; i 0) + { + /* We don't really expect to get here because of the setjmp handling + * above, but this is safe. + */ + fprintf(STDERR, "\n %s: %d libpng errors found (%d warnings)", + inname, error_count, warning_count); + + if (strict != 0) + return (1); + } + +# ifdef PNG_WRITE_SUPPORTED + /* If there we no write support nothing was written! */ + else if (unsupported_chunks > 0) + { + fprintf(STDERR, "\n %s: unsupported chunks (%d)%s", + inname, unsupported_chunks, strict ? ": IGNORED --strict!" : ""); + } +# endif + + else if (warning_count > 0) + { + fprintf(STDERR, "\n %s: %d libpng warnings found", + inname, warning_count); + + if (strict != 0) + return (1); + } + pngtest_debug("Opening files for comparison"); if ((fpin = fopen(inname, "rb")) == NULL) { @@ -1480,61 +1629,84 @@ test_one_file(PNG_CONST char *inname, PNG_CONST char *outname) return (1); } - for (;;) +#ifdef PNG_WRITE_SUPPORTED /* else nothing was written */ + if (interlace_preserved != 0) /* else the files will be changed */ { - png_size_t num_in, num_out; - - num_in = fread(inbuf, 1, 1, fpin); - num_out = fread(outbuf, 1, 1, fpout); - - if (num_in != num_out) + for (;;) { - fprintf(STDERR, "\nFiles %s and %s are of a different size\n", - inname, outname); + static int wrote_question = 0; + png_size_t num_in, num_out; + char inbuf[256], outbuf[256]; - if (wrote_question == 0) + num_in = fread(inbuf, 1, sizeof inbuf, fpin); + num_out = fread(outbuf, 1, sizeof outbuf, fpout); + + if (num_in != num_out) { - fprintf(STDERR, - " Was %s written with the same maximum IDAT chunk size (%d bytes),", - inname, PNG_ZBUF_SIZE); - fprintf(STDERR, - "\n filtering heuristic (libpng default), compression"); - fprintf(STDERR, - " level (zlib default),\n and zlib version (%s)?\n\n", - ZLIB_VERSION); - wrote_question = 1; - } + fprintf(STDERR, "\nFiles %s and %s are of a different size\n", + inname, outname); - FCLOSE(fpin); - FCLOSE(fpout); - return (0); - } - - if (!num_in) - break; - - if (png_memcmp(inbuf, outbuf, num_in)) - { - fprintf(STDERR, "\nFiles %s and %s are different\n", inname, outname); - - if (wrote_question == 0) - { - fprintf(STDERR, + if (wrote_question == 0 && unsupported_chunks == 0) + { + fprintf(STDERR, " Was %s written with the same maximum IDAT chunk size (%d bytes),", inname, PNG_ZBUF_SIZE); - fprintf(STDERR, - "\n filtering heuristic (libpng default), compression"); - fprintf(STDERR, - " level (zlib default),\n and zlib version (%s)?\n\n", - ZLIB_VERSION); - wrote_question = 1; + fprintf(STDERR, + "\n filtering heuristic (libpng default), compression"); + fprintf(STDERR, + " level (zlib default),\n and zlib version (%s)?\n\n", + ZLIB_VERSION); + wrote_question = 1; + } + + FCLOSE(fpin); + FCLOSE(fpout); + + if (strict != 0 && unsupported_chunks == 0) + return (1); + + else + return (0); } - FCLOSE(fpin); - FCLOSE(fpout); - return (0); + if (num_in == 0) + break; + + if (memcmp(inbuf, outbuf, num_in)) + { + fprintf(STDERR, "\nFiles %s and %s are different\n", inname, + outname); + + if (wrote_question == 0 && unsupported_chunks == 0) + { + fprintf(STDERR, + " Was %s written with the same maximum IDAT chunk size (%d bytes),", + inname, PNG_ZBUF_SIZE); + fprintf(STDERR, + "\n filtering heuristic (libpng default), compression"); + fprintf(STDERR, + " level (zlib default),\n and zlib version (%s)?\n\n", + ZLIB_VERSION); + wrote_question = 1; + } + + FCLOSE(fpin); + FCLOSE(fpout); + + /* NOTE: the unsupported_chunks escape is permitted here because + * unsupported text chunk compression will result in the compression + * mode being changed (to NONE) yet, in the test case, the result + * can be exactly the same size! + */ + if (strict != 0 && unsupported_chunks == 0) + return (1); + + else + return (0); + } } } +#endif /* WRITE */ FCLOSE(fpin); FCLOSE(fpout); @@ -1614,6 +1786,24 @@ main(int argc, char *argv[]) inname = argv[2]; } + else if (strcmp(argv[1], "--strict") == 0) + { + status_dots_requested = 0; + verbose = 1; + inname = argv[2]; + strict++; + relaxed = 0; + } + + else if (strcmp(argv[1], "--relaxed") == 0) + { + status_dots_requested = 0; + verbose = 1; + inname = argv[2]; + strict = 0; + relaxed++; + } + else { inname = argv[1]; @@ -1621,10 +1811,11 @@ main(int argc, char *argv[]) } } - if (!multiple && argc == 3 + verbose) + if (multiple == 0 && argc == 3 + verbose) outname = argv[2 + verbose]; - if ((!multiple && argc > 3 + verbose) || (multiple && argc < 2)) + if ((multiple == 0 && argc > 3 + verbose) || + (multiple != 0 && argc < 2)) { fprintf(STDERR, "usage: %s [infile.png] [outfile.png]\n\t%s -m {infile.png}\n", @@ -1636,7 +1827,7 @@ main(int argc, char *argv[]) exit(1); } - if (multiple) + if (multiple != 0) { int i; #if defined(PNG_USER_MEM_SUPPORTED) && PNG_DEBUG @@ -1646,6 +1837,9 @@ main(int argc, char *argv[]) { int kerror; fprintf(STDERR, "\n Testing %s:", argv[i]); +#if PNG_DEBUG > 0 + fprintf(STDERR, "\n"); +#endif kerror = test_one_file(argv[i], outname); if (kerror == 0) { @@ -1660,7 +1854,7 @@ main(int argc, char *argv[]) #endif #ifdef PNG_READ_USER_TRANSFORM_SUPPORTED for (k = 0; k<256; k++) - if (filters_used[k]) + if (filters_used[k] != 0) fprintf(STDERR, " Filter %d was used %lu times\n", k, (unsigned long)filters_used[k]); #endif @@ -1669,7 +1863,7 @@ main(int argc, char *argv[]) fprintf(STDERR, " tIME = %s\n", tIME_string); tIME_chunk_present = 0; -#endif /* PNG_TIME_RFC1123_SUPPORTED */ +#endif /* TIME_RFC1123 */ } else @@ -1691,9 +1885,9 @@ main(int argc, char *argv[]) while (pinfo != NULL) { - fprintf(STDERR, " %lu bytes at %x\n", + fprintf(STDERR, " %lu bytes at %p\n", (unsigned long)pinfo->size, - (unsigned int)pinfo->pointer); + pinfo->pointer); pinfo = pinfo->next; } } @@ -1727,7 +1921,12 @@ main(int argc, char *argv[]) status_dots_requested = 0; if (i == 0 || verbose == 1 || ierror != 0) + { fprintf(STDERR, "\n Testing %s:", inname); +#if PNG_DEBUG > 0 + fprintf(STDERR, "\n"); +#endif + } kerror = test_one_file(inname, outname); @@ -1746,21 +1945,26 @@ main(int argc, char *argv[]) #endif #ifdef PNG_READ_USER_TRANSFORM_SUPPORTED for (k = 0; k<256; k++) - if (filters_used[k]) + if (filters_used[k] != 0) fprintf(STDERR, " Filter %d was used %lu times\n", k, (unsigned long)filters_used[k]); #endif #ifdef PNG_TIME_RFC1123_SUPPORTED if (tIME_chunk_present != 0) fprintf(STDERR, " tIME = %s\n", tIME_string); -#endif /* PNG_TIME_RFC1123_SUPPORTED */ +#endif /* TIME_RFC1123 */ } } else { if (verbose == 0 && i != 2) + { fprintf(STDERR, "\n Testing %s:", inname); +#if PNG_DEBUG > 0 + fprintf(STDERR, "\n"); +#endif + } fprintf(STDERR, " FAIL\n"); ierror += kerror; @@ -1779,8 +1983,8 @@ main(int argc, char *argv[]) while (pinfo != NULL) { - fprintf(STDERR, " %lu bytes at %x\n", - (unsigned long)pinfo->size, (unsigned int)pinfo->pointer); + fprintf(STDERR, " %lu bytes at %p\n", + (unsigned long)pinfo->size, pinfo->pointer); pinfo = pinfo->next; } } @@ -1820,6 +2024,16 @@ main(int argc, char *argv[]) return (int)(ierror != 0); } +#else +int +main(void) +{ + fprintf(STDERR, + " test ignored because libpng was not built with read support\n"); + /* And skip this test */ + return PNG_LIBPNG_VER < 10600 ? 0 : 77; +} +#endif /* Generate a compiler error if there is an old png.h in the search path. */ -typedef png_libpng_version_1_5_4 Your_png_h_is_not_version_1_5_4; +typedef png_libpng_version_1_6_16 Your_png_h_is_not_version_1_6_16; diff --git a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngtrans.c b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngtrans.c index b59fc695bed..5b95db8c66b 100644 --- a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngtrans.c +++ b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngtrans.c @@ -29,8 +29,8 @@ * However, the following notice accompanied the original version of this * file and, per its terms, should not be removed: * - * Last changed in libpng 1.5.4 [July 7, 2011] - * Copyright (c) 1998-2011 Glenn Randers-Pehrson + * Last changed in libpng 1.6.15 [November 20, 2014] + * Copyright (c) 1998-2014 Glenn Randers-Pehrson * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) * @@ -46,7 +46,7 @@ #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED) /* Turn on BGR-to-RGB mapping */ void PNGAPI -png_set_bgr(png_structp png_ptr) +png_set_bgr(png_structrp png_ptr) { png_debug(1, "in png_set_bgr"); @@ -60,7 +60,7 @@ png_set_bgr(png_structp png_ptr) #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED) /* Turn on 16 bit byte swapping */ void PNGAPI -png_set_swap(png_structp png_ptr) +png_set_swap(png_structrp png_ptr) { png_debug(1, "in png_set_swap"); @@ -75,7 +75,7 @@ png_set_swap(png_structp png_ptr) #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) /* Turn on pixel packing */ void PNGAPI -png_set_packing(png_structp png_ptr) +png_set_packing(png_structrp png_ptr) { png_debug(1, "in png_set_packing"); @@ -85,7 +85,9 @@ png_set_packing(png_structp png_ptr) if (png_ptr->bit_depth < 8) { png_ptr->transformations |= PNG_PACK; - png_ptr->usr_bit_depth = 8; +# ifdef PNG_WRITE_SUPPORTED + png_ptr->usr_bit_depth = 8; +# endif } } #endif @@ -93,7 +95,7 @@ png_set_packing(png_structp png_ptr) #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED) /* Turn on packed pixel swapping */ void PNGAPI -png_set_packswap(png_structp png_ptr) +png_set_packswap(png_structrp png_ptr) { png_debug(1, "in png_set_packswap"); @@ -107,7 +109,7 @@ png_set_packswap(png_structp png_ptr) #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED) void PNGAPI -png_set_shift(png_structp png_ptr, png_const_color_8p true_bits) +png_set_shift(png_structrp png_ptr, png_const_color_8p true_bits) { png_debug(1, "in png_set_shift"); @@ -122,11 +124,11 @@ png_set_shift(png_structp png_ptr, png_const_color_8p true_bits) #if defined(PNG_READ_INTERLACING_SUPPORTED) || \ defined(PNG_WRITE_INTERLACING_SUPPORTED) int PNGAPI -png_set_interlace_handling(png_structp png_ptr) +png_set_interlace_handling(png_structrp png_ptr) { png_debug(1, "in png_set_interlace handling"); - if (png_ptr && png_ptr->interlaced) + if (png_ptr != 0 && png_ptr->interlaced != 0) { png_ptr->transformations |= PNG_INTERLACE; return (7); @@ -143,44 +145,91 @@ png_set_interlace_handling(png_structp png_ptr) * that don't like bytes as parameters. */ void PNGAPI -png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc) +png_set_filler(png_structrp png_ptr, png_uint_32 filler, int filler_loc) { png_debug(1, "in png_set_filler"); if (png_ptr == NULL) return; + /* In libpng 1.6 it is possible to determine whether this is a read or write + * operation and therefore to do more checking here for a valid call. + */ + if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0) + { +# ifdef PNG_READ_FILLER_SUPPORTED + /* On read png_set_filler is always valid, regardless of the base PNG + * format, because other transformations can give a format where the + * filler code can execute (basically an 8 or 16-bit component RGB or G + * format.) + * + * NOTE: usr_channels is not used by the read code! (This has led to + * confusion in the past.) The filler is only used in the read code. + */ + png_ptr->filler = (png_uint_16)filler; +# else + png_app_error(png_ptr, "png_set_filler not supported on read"); + PNG_UNUSED(filler) /* not used in the write case */ + return; +# endif + } + + else /* write */ + { +# ifdef PNG_WRITE_FILLER_SUPPORTED + /* On write the usr_channels parameter must be set correctly at the + * start to record the number of channels in the app-supplied data. + */ + switch (png_ptr->color_type) + { + case PNG_COLOR_TYPE_RGB: + png_ptr->usr_channels = 4; + break; + + case PNG_COLOR_TYPE_GRAY: + if (png_ptr->bit_depth >= 8) + { + png_ptr->usr_channels = 2; + break; + } + + else + { + /* There simply isn't any code in libpng to strip out bits + * from bytes when the components are less than a byte in + * size! + */ + png_app_error(png_ptr, + "png_set_filler is invalid for low bit depth gray output"); + return; + } + + default: + png_app_error(png_ptr, + "png_set_filler: inappropriate color type"); + return; + } +# else + png_app_error(png_ptr, "png_set_filler not supported on write"); + return; +# endif + } + + /* Here on success - libpng supports the operation, set the transformation + * and the flag to say where the filler channel is. + */ png_ptr->transformations |= PNG_FILLER; - png_ptr->filler = (png_uint_16)filler; if (filler_loc == PNG_FILLER_AFTER) png_ptr->flags |= PNG_FLAG_FILLER_AFTER; else png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER; - - /* This should probably go in the "do_read_filler" routine. - * I attempted to do that in libpng-1.0.1a but that caused problems - * so I restored it in libpng-1.0.2a - */ - - if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) - { - png_ptr->usr_channels = 4; - } - - /* Also I added this in libpng-1.0.2a (what happens when we expand - * a less-than-8-bit grayscale to GA?) */ - - if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8) - { - png_ptr->usr_channels = 2; - } } /* Added to libpng-1.2.7 */ void PNGAPI -png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc) +png_set_add_alpha(png_structrp png_ptr, png_uint_32 filler, int filler_loc) { png_debug(1, "in png_set_add_alpha"); @@ -188,7 +237,9 @@ png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc) return; png_set_filler(png_ptr, filler, filler_loc); - png_ptr->transformations |= PNG_ADD_ALPHA; + /* The above may fail to do anything. */ + if ((png_ptr->transformations & PNG_FILLER) != 0) + png_ptr->transformations |= PNG_ADD_ALPHA; } #endif @@ -196,7 +247,7 @@ png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc) #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \ defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED) void PNGAPI -png_set_swap_alpha(png_structp png_ptr) +png_set_swap_alpha(png_structrp png_ptr) { png_debug(1, "in png_set_swap_alpha"); @@ -210,7 +261,7 @@ png_set_swap_alpha(png_structp png_ptr) #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \ defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED) void PNGAPI -png_set_invert_alpha(png_structp png_ptr) +png_set_invert_alpha(png_structrp png_ptr) { png_debug(1, "in png_set_invert_alpha"); @@ -223,7 +274,7 @@ png_set_invert_alpha(png_structp png_ptr) #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED) void PNGAPI -png_set_invert_mono(png_structp png_ptr) +png_set_invert_mono(png_structrp png_ptr) { png_debug(1, "in png_set_invert_mono"); @@ -304,9 +355,16 @@ png_do_swap(png_row_infop row_info, png_bytep row) for (i = 0; i < istop; i++, rp += 2) { +#ifdef PNG_BUILTIN_BSWAP16_SUPPORTED + /* Feature added to libpng-1.6.11 for testing purposes, not + * enabled by default. + */ + *(png_uint_16*)rp = __builtin_bswap16(*(png_uint_16*)rp); +#else png_byte t = *rp; *rp = *(rp + 1); *(rp + 1) = t; +#endif } } } @@ -448,7 +506,7 @@ png_do_packswap(png_row_infop row_info, png_bytep row) *rp = table[*rp]; } } -#endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */ +#endif /* PACKSWAP || WRITE_PACKSWAP */ #if defined(PNG_WRITE_FILLER_SUPPORTED) || \ defined(PNG_READ_STRIP_ALPHA_SUPPORTED) @@ -480,7 +538,7 @@ png_do_strip_channel(png_row_infop row_info, png_bytep row, int at_start) { if (row_info->bit_depth == 8) { - if (at_start) /* Skip initial filler */ + if (at_start != 0) /* Skip initial filler */ ++sp; else /* Skip initial channel and, for sp, the filler */ sp += 2, ++dp; @@ -494,7 +552,7 @@ png_do_strip_channel(png_row_infop row_info, png_bytep row, int at_start) else if (row_info->bit_depth == 16) { - if (at_start) /* Skip initial filler */ + if (at_start != 0) /* Skip initial filler */ sp += 2; else /* Skip initial channel and, for sp, the filler */ sp += 4, dp += 2; @@ -520,7 +578,7 @@ png_do_strip_channel(png_row_infop row_info, png_bytep row, int at_start) { if (row_info->bit_depth == 8) { - if (at_start) /* Skip initial filler */ + if (at_start != 0) /* Skip initial filler */ ++sp; else /* Skip initial channels and, for sp, the filler */ sp += 4, dp += 3; @@ -534,7 +592,7 @@ png_do_strip_channel(png_row_infop row_info, png_bytep row, int at_start) else if (row_info->bit_depth == 16) { - if (at_start) /* Skip initial filler */ + if (at_start != 0) /* Skip initial filler */ sp += 2; else /* Skip initial channels and, for sp, the filler */ sp += 8, dp += 6; @@ -575,7 +633,7 @@ png_do_bgr(png_row_infop row_info, png_bytep row) { png_debug(1, "in png_do_bgr"); - if ((row_info->color_type & PNG_COLOR_MASK_COLOR)) + if ((row_info->color_type & PNG_COLOR_MASK_COLOR) != 0) { png_uint_32 row_width = row_info->width; if (row_info->bit_depth == 8) @@ -645,19 +703,133 @@ png_do_bgr(png_row_infop row_info, png_bytep row) #endif } } -#endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */ +#endif /* READ_BGR || WRITE_BGR */ + +#if defined(PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED) || \ + defined(PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED) +/* Added at libpng-1.5.10 */ +void /* PRIVATE */ +png_do_check_palette_indexes(png_structrp png_ptr, png_row_infop row_info) +{ + if (png_ptr->num_palette < (1 << row_info->bit_depth) && + png_ptr->num_palette > 0) /* num_palette can be 0 in MNG files */ + { + /* Calculations moved outside switch in an attempt to stop different + * compiler warnings. 'padding' is in *bits* within the last byte, it is + * an 'int' because pixel_depth becomes an 'int' in the expression below, + * and this calculation is used because it avoids warnings that other + * forms produced on either GCC or MSVC. + */ + int padding = (-row_info->pixel_depth * row_info->width) & 7; + png_bytep rp = png_ptr->row_buf + row_info->rowbytes; + + switch (row_info->bit_depth) + { + case 1: + { + /* in this case, all bytes must be 0 so we don't need + * to unpack the pixels except for the rightmost one. + */ + for (; rp > png_ptr->row_buf; rp--) + { + if (*rp >> padding != 0) + png_ptr->num_palette_max = 1; + padding = 0; + } + + break; + } + + case 2: + { + for (; rp > png_ptr->row_buf; rp--) + { + int i = ((*rp >> padding) & 0x03); + + if (i > png_ptr->num_palette_max) + png_ptr->num_palette_max = i; + + i = (((*rp >> padding) >> 2) & 0x03); + + if (i > png_ptr->num_palette_max) + png_ptr->num_palette_max = i; + + i = (((*rp >> padding) >> 4) & 0x03); + + if (i > png_ptr->num_palette_max) + png_ptr->num_palette_max = i; + + i = (((*rp >> padding) >> 6) & 0x03); + + if (i > png_ptr->num_palette_max) + png_ptr->num_palette_max = i; + + padding = 0; + } + + break; + } + + case 4: + { + for (; rp > png_ptr->row_buf; rp--) + { + int i = ((*rp >> padding) & 0x0f); + + if (i > png_ptr->num_palette_max) + png_ptr->num_palette_max = i; + + i = (((*rp >> padding) >> 4) & 0x0f); + + if (i > png_ptr->num_palette_max) + png_ptr->num_palette_max = i; + + padding = 0; + } + + break; + } + + case 8: + { + for (; rp > png_ptr->row_buf; rp--) + { + if (*rp > png_ptr->num_palette_max) + png_ptr->num_palette_max = (int) *rp; + } + + break; + } + + default: + break; + } + } +} +#endif /* CHECK_FOR_INVALID_INDEX */ #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) #ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED void PNGAPI -png_set_user_transform_info(png_structp png_ptr, png_voidp +png_set_user_transform_info(png_structrp png_ptr, png_voidp user_transform_ptr, int user_transform_depth, int user_transform_channels) { png_debug(1, "in png_set_user_transform_info"); if (png_ptr == NULL) return; + +#ifdef PNG_READ_USER_TRANSFORM_SUPPORTED + if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0 && + (png_ptr->flags & PNG_FLAG_ROW_INIT) != 0) + { + png_app_error(png_ptr, + "info change after png_start_read_image or png_read_update_info"); + return; + } +#endif + png_ptr->user_transform_ptr = user_transform_ptr; png_ptr->user_transform_depth = (png_byte)user_transform_depth; png_ptr->user_transform_channels = (png_byte)user_transform_channels; @@ -671,20 +843,20 @@ png_set_user_transform_info(png_structp png_ptr, png_voidp */ #ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED png_voidp PNGAPI -png_get_user_transform_ptr(png_const_structp png_ptr) +png_get_user_transform_ptr(png_const_structrp png_ptr) { if (png_ptr == NULL) return (NULL); - return ((png_voidp)png_ptr->user_transform_ptr); + return png_ptr->user_transform_ptr; } #endif #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED png_uint_32 PNGAPI -png_get_current_row_number(png_const_structp png_ptr) +png_get_current_row_number(png_const_structrp png_ptr) { - /* See the comments in png.h - this is the sub-image row when reading and + /* See the comments in png.h - this is the sub-image row when reading an * interlaced image. */ if (png_ptr != NULL) @@ -694,13 +866,12 @@ png_get_current_row_number(png_const_structp png_ptr) } png_byte PNGAPI -png_get_current_pass_number(png_const_structp png_ptr) +png_get_current_pass_number(png_const_structrp png_ptr) { if (png_ptr != NULL) return png_ptr->pass; return 8; /* invalid */ } -#endif /* PNG_USER_TRANSFORM_INFO_SUPPORTED */ -#endif /* PNG_READ_USER_TRANSFORM_SUPPORTED || - PNG_WRITE_USER_TRANSFORM_SUPPORTED */ -#endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */ +#endif /* USER_TRANSFORM_INFO */ +#endif /* READ_USER_TRANSFORM || WRITE_USER_TRANSFORM */ +#endif /* READ || WRITE */ diff --git a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwio.c b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwio.c index 2f94f8c9572..017a9d7b31b 100644 --- a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwio.c +++ b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwio.c @@ -29,8 +29,8 @@ * However, the following notice accompanied the original version of this * file and, per its terms, should not be removed: * - * Last changed in libpng 1.5.0 [January 6, 2011] - * Copyright (c) 1998-2011 Glenn Randers-Pehrson + * Last changed in libpng 1.6.15 [November 20, 2014] + * Copyright (c) 1998-2014 Glenn Randers-Pehrson * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) * @@ -58,11 +58,12 @@ */ void /* PRIVATE */ -png_write_data(png_structp png_ptr, png_const_bytep data, png_size_t length) +png_write_data(png_structrp png_ptr, png_const_bytep data, png_size_t length) { /* NOTE: write_data_fn must not change the buffer! */ if (png_ptr->write_data_fn != NULL ) - (*(png_ptr->write_data_fn))(png_ptr, (png_bytep)data, length); + (*(png_ptr->write_data_fn))(png_ptr, png_constcast(png_bytep,data), + length); else png_error(png_ptr, "Call to NULL write function"); @@ -74,7 +75,6 @@ png_write_data(png_structp png_ptr, png_const_bytep data, png_size_t length) * write_data function and use it at run time with png_set_write_fn(), rather * than changing the library. */ -#ifndef USE_FAR_KEYWORD void PNGCBAPI png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length) { @@ -88,64 +88,6 @@ png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length) if (check != length) png_error(png_ptr, "Write Error"); } -#else -/* This is the model-independent version. Since the standard I/O library - * can't handle far buffers in the medium and small models, we have to copy - * the data. - */ - -#define NEAR_BUF_SIZE 1024 -#define MIN(a,b) (a <= b ? a : b) - -void PNGCBAPI -png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length) -{ - png_uint_32 check; - png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */ - png_FILE_p io_ptr; - - if (png_ptr == NULL) - return; - - /* Check if data really is near. If so, use usual code. */ - near_data = (png_byte *)CVT_PTR_NOCHECK(data); - io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr); - - if ((png_bytep)near_data == data) - { - check = fwrite(near_data, 1, length, io_ptr); - } - - else - { - png_byte buf[NEAR_BUF_SIZE]; - png_size_t written, remaining, err; - check = 0; - remaining = length; - - do - { - written = MIN(NEAR_BUF_SIZE, remaining); - png_memcpy(buf, data, written); /* Copy far buffer to near buffer */ - err = fwrite(buf, 1, written, io_ptr); - - if (err != written) - break; - - else - check += err; - - data += written; - remaining -= written; - } - while (remaining != 0); - } - - if (check != length) - png_error(png_ptr, "Write Error"); -} - -#endif #endif /* This function is called to output any data pending writing (normally @@ -154,7 +96,7 @@ png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length) */ #ifdef PNG_WRITE_FLUSH_SUPPORTED void /* PRIVATE */ -png_flush(png_structp png_ptr) +png_flush(png_structrp png_ptr) { if (png_ptr->output_flush_fn != NULL) (*(png_ptr->output_flush_fn))(png_ptr); @@ -169,7 +111,7 @@ png_default_flush(png_structp png_ptr) if (png_ptr == NULL) return; - io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr)); + io_ptr = png_voidcast(png_FILE_p, (png_ptr->io_ptr)); fflush(io_ptr); } # endif @@ -205,7 +147,7 @@ png_default_flush(png_structp png_ptr) * *FILE structure. */ void PNGAPI -png_set_write_fn(png_structp png_ptr, png_voidp io_ptr, +png_set_write_fn(png_structrp png_ptr, png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn) { if (png_ptr == NULL) @@ -235,8 +177,11 @@ png_set_write_fn(png_structp png_ptr, png_voidp io_ptr, # else png_ptr->output_flush_fn = output_flush_fn; # endif -#endif /* PNG_WRITE_FLUSH_SUPPORTED */ +#else + PNG_UNUSED(output_flush_fn) +#endif /* WRITE_FLUSH */ +#ifdef PNG_READ_SUPPORTED /* It is an error to read while writing a png file */ if (png_ptr->read_data_fn != NULL) { @@ -246,37 +191,6 @@ png_set_write_fn(png_structp png_ptr, png_voidp io_ptr, "Can't set both read_data_fn and write_data_fn in the" " same structure"); } -} - -#ifdef USE_FAR_KEYWORD -# ifdef _MSC_VER -void *png_far_to_near(png_structp png_ptr, png_voidp ptr, int check) -{ - void *near_ptr; - void FAR *far_ptr; - FP_OFF(near_ptr) = FP_OFF(ptr); - far_ptr = (void FAR *)near_ptr; - - if (check != 0) - if (FP_SEG(ptr) != FP_SEG(far_ptr)) - png_error(png_ptr, "segment lost in conversion"); - - return(near_ptr); -} -# else -void *png_far_to_near(png_structp png_ptr, png_voidp ptr, int check) -{ - void *near_ptr; - void FAR *far_ptr; - near_ptr = (void FAR *)ptr; - far_ptr = (void FAR *)near_ptr; - - if (check != 0) - if (far_ptr != ptr) - png_error(png_ptr, "segment lost in conversion"); - - return(near_ptr); -} -# endif #endif -#endif /* PNG_WRITE_SUPPORTED */ +} +#endif /* WRITE */ diff --git a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwrite.c b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwrite.c index bdc14670964..1d39e7490f7 100644 --- a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwrite.c +++ b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwrite.c @@ -29,8 +29,8 @@ * However, the following notice accompanied the original version of this * file and, per its terms, should not be removed: * - * Last changed in libpng 1.5.4 [July 7, 2011] - * Copyright (c) 1998-2011 Glenn Randers-Pehrson + * Last changed in libpng 1.6.15 [November 20, 2014] + * Copyright (c) 1998-2014 Glenn Randers-Pehrson * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) * @@ -40,9 +40,65 @@ */ #include "pngpriv.h" +#if defined(PNG_SIMPLIFIED_WRITE_SUPPORTED) && defined(PNG_STDIO_SUPPORTED) +# include +#endif #ifdef PNG_WRITE_SUPPORTED +#ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED +/* Write out all the unknown chunks for the current given location */ +static void +write_unknown_chunks(png_structrp png_ptr, png_const_inforp info_ptr, + unsigned int where) +{ + if (info_ptr->unknown_chunks_num != 0) + { + png_const_unknown_chunkp up; + + png_debug(5, "writing extra chunks"); + + for (up = info_ptr->unknown_chunks; + up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num; + ++up) + if ((up->location & where) != 0) + { + /* If per-chunk unknown chunk handling is enabled use it, otherwise + * just write the chunks the application has set. + */ +#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED + int keep = png_handle_as_unknown(png_ptr, up->name); + + /* NOTE: this code is radically different from the read side in the + * matter of handling an ancillary unknown chunk. In the read side + * the default behavior is to discard it, in the code below the default + * behavior is to write it. Critical chunks are, however, only + * written if explicitly listed or if the default is set to write all + * unknown chunks. + * + * The default handling is also slightly weird - it is not possible to + * stop the writing of all unsafe-to-copy chunks! + * + * TODO: REVIEW: this would seem to be a bug. + */ + if (keep != PNG_HANDLE_CHUNK_NEVER && + ((up->name[3] & 0x20) /* safe-to-copy overrides everything */ || + keep == PNG_HANDLE_CHUNK_ALWAYS || + (keep == PNG_HANDLE_CHUNK_AS_DEFAULT && + png_ptr->unknown_default == PNG_HANDLE_CHUNK_ALWAYS))) +#endif + { + /* TODO: review, what is wrong with a zero length unknown chunk? */ + if (up->size == 0) + png_warning(png_ptr, "Writing zero-length unknown chunk"); + + png_write_chunk(png_ptr, up->name, up->data, up->size); + } + } + } +} +#endif /* WRITE_UNKNOWN_CHUNKS */ + /* Writes all the PNG information. This is the suggested way to use the * library. If you have a new chunk to add, make a function to write it, * and put it in the correct location here. If you want the chunk written @@ -53,21 +109,21 @@ * them in png_write_end(), and compressing them. */ void PNGAPI -png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr) +png_write_info_before_PLTE(png_structrp png_ptr, png_const_inforp info_ptr) { png_debug(1, "in png_write_info_before_PLTE"); if (png_ptr == NULL || info_ptr == NULL) return; - if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE)) + if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0) { /* Write PNG signature */ png_write_sig(png_ptr); #ifdef PNG_MNG_FEATURES_SUPPORTED - if ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) && \ - (png_ptr->mng_features_permitted)) + if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 && \ + png_ptr->mng_features_permitted != 0) { png_warning(png_ptr, "MNG features are not allowed in a PNG datastream"); png_ptr->mng_features_permitted = 0; @@ -79,75 +135,88 @@ png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr) info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type, info_ptr->filter_type, #ifdef PNG_WRITE_INTERLACING_SUPPORTED - info_ptr->interlace_type); + info_ptr->interlace_type #else - 0); + 0 #endif + ); + /* The rest of these check to see if the valid field has the appropriate * flag set, and if it does, writes the chunk. + * + * 1.6.0: COLORSPACE support controls the writing of these chunks too, and + * the chunks will be written if the WRITE routine is there and information + * is available in the COLORSPACE. (See png_colorspace_sync_info in png.c + * for where the valid flags get set.) + * + * Under certain circumstances the colorspace can be invalidated without + * syncing the info_struct 'valid' flags; this happens if libpng detects and + * error and calls png_error while the color space is being set, yet the + * application continues writing the PNG. So check the 'invalid' flag here + * too. */ -#ifdef PNG_WRITE_gAMA_SUPPORTED - if (info_ptr->valid & PNG_INFO_gAMA) - png_write_gAMA_fixed(png_ptr, info_ptr->gamma); -#endif -#ifdef PNG_WRITE_sRGB_SUPPORTED - if (info_ptr->valid & PNG_INFO_sRGB) - png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent); +#ifdef PNG_GAMMA_SUPPORTED +# ifdef PNG_WRITE_gAMA_SUPPORTED + if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 && + (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_gAMA) != 0 && + (info_ptr->valid & PNG_INFO_gAMA) != 0) + png_write_gAMA_fixed(png_ptr, info_ptr->colorspace.gamma); +# endif #endif -#ifdef PNG_WRITE_iCCP_SUPPORTED - if (info_ptr->valid & PNG_INFO_iCCP) - png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE, - (png_charp)info_ptr->iccp_profile, (int)info_ptr->iccp_proflen); -#endif +#ifdef PNG_COLORSPACE_SUPPORTED + /* Write only one of sRGB or an ICC profile. If a profile was supplied + * and it matches one of the known sRGB ones issue a warning. + */ +# ifdef PNG_WRITE_iCCP_SUPPORTED + if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 && + (info_ptr->valid & PNG_INFO_iCCP) != 0) + { +# ifdef PNG_WRITE_sRGB_SUPPORTED + if ((info_ptr->valid & PNG_INFO_sRGB) != 0) + png_app_warning(png_ptr, + "profile matches sRGB but writing iCCP instead"); +# endif + + png_write_iCCP(png_ptr, info_ptr->iccp_name, + info_ptr->iccp_profile); + } +# ifdef PNG_WRITE_sRGB_SUPPORTED + else +# endif +# endif + +# ifdef PNG_WRITE_sRGB_SUPPORTED + if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 && + (info_ptr->valid & PNG_INFO_sRGB) != 0) + png_write_sRGB(png_ptr, info_ptr->colorspace.rendering_intent); +# endif /* WRITE_sRGB */ +#endif /* COLORSPACE */ + #ifdef PNG_WRITE_sBIT_SUPPORTED - if (info_ptr->valid & PNG_INFO_sBIT) + if ((info_ptr->valid & PNG_INFO_sBIT) != 0) png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type); #endif -#ifdef PNG_WRITE_cHRM_SUPPORTED - if (info_ptr->valid & PNG_INFO_cHRM) - png_write_cHRM_fixed(png_ptr, - info_ptr->x_white, info_ptr->y_white, - info_ptr->x_red, info_ptr->y_red, - info_ptr->x_green, info_ptr->y_green, - info_ptr->x_blue, info_ptr->y_blue); + +#ifdef PNG_COLORSPACE_SUPPORTED +# ifdef PNG_WRITE_cHRM_SUPPORTED + if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 && + (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0 && + (info_ptr->valid & PNG_INFO_cHRM) != 0) + png_write_cHRM_fixed(png_ptr, &info_ptr->colorspace.end_points_xy); +# endif #endif #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED - if (info_ptr->unknown_chunks_num) - { - png_unknown_chunk *up; - - png_debug(5, "writing extra chunks"); - - for (up = info_ptr->unknown_chunks; - up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num; - up++) - { - int keep = png_handle_as_unknown(png_ptr, up->name); - - if (keep != PNG_HANDLE_CHUNK_NEVER && - up->location && - !(up->location & PNG_HAVE_PLTE) && - !(up->location & PNG_HAVE_IDAT) && - !(up->location & PNG_AFTER_IDAT) && - ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS || - (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS))) - { - if (up->size == 0) - png_warning(png_ptr, "Writing zero-length unknown chunk"); - - png_write_chunk(png_ptr, up->name, up->data, up->size); - } - } - } + write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_IHDR); #endif + png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE; } } void PNGAPI -png_write_info(png_structp png_ptr, png_infop info_ptr) +png_write_info(png_structrp png_ptr, png_const_inforp info_ptr) { #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED) int i; @@ -160,19 +229,19 @@ png_write_info(png_structp png_ptr, png_infop info_ptr) png_write_info_before_PLTE(png_ptr, info_ptr); - if (info_ptr->valid & PNG_INFO_PLTE) + if ((info_ptr->valid & PNG_INFO_PLTE) != 0) png_write_PLTE(png_ptr, info_ptr->palette, (png_uint_32)info_ptr->num_palette); - else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + else if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) !=0) png_error(png_ptr, "Valid palette required for paletted images"); #ifdef PNG_WRITE_tRNS_SUPPORTED - if (info_ptr->valid & PNG_INFO_tRNS) + if ((info_ptr->valid & PNG_INFO_tRNS) !=0) { #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED /* Invert the alpha channel (in tRNS) */ - if ((png_ptr->transformations & PNG_INVERT_ALPHA) && + if ((png_ptr->transformations & PNG_INVERT_ALPHA) != 0 && info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { int j; @@ -186,42 +255,42 @@ png_write_info(png_structp png_ptr, png_infop info_ptr) } #endif #ifdef PNG_WRITE_bKGD_SUPPORTED - if (info_ptr->valid & PNG_INFO_bKGD) + if ((info_ptr->valid & PNG_INFO_bKGD) != 0) png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type); #endif #ifdef PNG_WRITE_hIST_SUPPORTED - if (info_ptr->valid & PNG_INFO_hIST) + if ((info_ptr->valid & PNG_INFO_hIST) != 0) png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette); #endif #ifdef PNG_WRITE_oFFs_SUPPORTED - if (info_ptr->valid & PNG_INFO_oFFs) + if ((info_ptr->valid & PNG_INFO_oFFs) != 0) png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset, info_ptr->offset_unit_type); #endif #ifdef PNG_WRITE_pCAL_SUPPORTED - if (info_ptr->valid & PNG_INFO_pCAL) + if ((info_ptr->valid & PNG_INFO_pCAL) != 0) png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0, info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams, info_ptr->pcal_units, info_ptr->pcal_params); #endif #ifdef PNG_WRITE_sCAL_SUPPORTED - if (info_ptr->valid & PNG_INFO_sCAL) + if ((info_ptr->valid & PNG_INFO_sCAL) != 0) png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit, info_ptr->scal_s_width, info_ptr->scal_s_height); #endif /* sCAL */ #ifdef PNG_WRITE_pHYs_SUPPORTED - if (info_ptr->valid & PNG_INFO_pHYs) + if ((info_ptr->valid & PNG_INFO_pHYs) != 0) png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit, info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type); #endif /* pHYs */ #ifdef PNG_WRITE_tIME_SUPPORTED - if (info_ptr->valid & PNG_INFO_tIME) + if ((info_ptr->valid & PNG_INFO_tIME) != 0) { png_write_tIME(png_ptr, &(info_ptr->mod_time)); png_ptr->mode |= PNG_WROTE_tIME; @@ -229,7 +298,7 @@ png_write_info(png_structp png_ptr, png_infop info_ptr) #endif /* tIME */ #ifdef PNG_WRITE_sPLT_SUPPORTED - if (info_ptr->valid & PNG_INFO_sPLT) + if ((info_ptr->valid & PNG_INFO_sPLT) != 0) for (i = 0; i < (int)info_ptr->splt_palettes_num; i++) png_write_sPLT(png_ptr, info_ptr->splt_palettes + i); #endif /* sPLT */ @@ -251,11 +320,14 @@ png_write_info(png_structp png_ptr, png_infop info_ptr) info_ptr->text[i].lang, info_ptr->text[i].lang_key, info_ptr->text[i].text); + /* Mark this chunk as written */ + if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE) + info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR; + else + info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR; #else - png_warning(png_ptr, "Unable to write international text"); + png_warning(png_ptr, "Unable to write international text"); #endif - /* Mark this chunk as written */ - info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR; } /* If we want a compressed text chunk */ @@ -264,13 +336,12 @@ png_write_info(png_structp png_ptr, png_infop info_ptr) #ifdef PNG_WRITE_zTXt_SUPPORTED /* Write compressed chunk */ png_write_zTXt(png_ptr, info_ptr->text[i].key, - info_ptr->text[i].text, 0, - info_ptr->text[i].compression); + info_ptr->text[i].text, info_ptr->text[i].compression); + /* Mark this chunk as written */ + info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR; #else png_warning(png_ptr, "Unable to write compressed text"); #endif - /* Mark this chunk as written */ - info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR; } else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE) @@ -291,29 +362,7 @@ png_write_info(png_structp png_ptr, png_infop info_ptr) #endif /* tEXt */ #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED - if (info_ptr->unknown_chunks_num) - { - png_unknown_chunk *up; - - png_debug(5, "writing extra chunks"); - - for (up = info_ptr->unknown_chunks; - up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num; - up++) - { - int keep = png_handle_as_unknown(png_ptr, up->name); - if (keep != PNG_HANDLE_CHUNK_NEVER && - up->location && - (up->location & PNG_HAVE_PLTE) && - !(up->location & PNG_HAVE_IDAT) && - !(up->location & PNG_AFTER_IDAT) && - ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS || - (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS))) - { - png_write_chunk(png_ptr, up->name, up->data, up->size); - } - } - } + write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_PLTE); #endif } @@ -323,16 +372,21 @@ png_write_info(png_structp png_ptr, png_infop info_ptr) * comments, I suggest writing them here, and compressing them. */ void PNGAPI -png_write_end(png_structp png_ptr, png_infop info_ptr) +png_write_end(png_structrp png_ptr, png_inforp info_ptr) { png_debug(1, "in png_write_end"); if (png_ptr == NULL) return; - if (!(png_ptr->mode & PNG_HAVE_IDAT)) + if ((png_ptr->mode & PNG_HAVE_IDAT) == 0) png_error(png_ptr, "No IDATs written into file"); +#ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED + if (png_ptr->num_palette_max > png_ptr->num_palette) + png_benign_error(png_ptr, "Wrote palette index exceeding num_palette"); +#endif + /* See if user wants us to write information chunks */ if (info_ptr != NULL) { @@ -341,8 +395,8 @@ png_write_end(png_structp png_ptr, png_infop info_ptr) #endif #ifdef PNG_WRITE_tIME_SUPPORTED /* Check to see if user has supplied a time chunk */ - if ((info_ptr->valid & PNG_INFO_tIME) && - !(png_ptr->mode & PNG_WROTE_tIME)) + if ((info_ptr->valid & PNG_INFO_tIME) != 0 && + (png_ptr->mode & PNG_WROTE_tIME) == 0) png_write_tIME(png_ptr, &(info_ptr->mod_time)); #endif @@ -363,11 +417,14 @@ png_write_end(png_structp png_ptr, png_infop info_ptr) info_ptr->text[i].lang, info_ptr->text[i].lang_key, info_ptr->text[i].text); + /* Mark this chunk as written */ + if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE) + info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR; + else + info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR; #else png_warning(png_ptr, "Unable to write international text"); #endif - /* Mark this chunk as written */ - info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR; } else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt) @@ -375,13 +432,12 @@ png_write_end(png_structp png_ptr, png_infop info_ptr) #ifdef PNG_WRITE_zTXt_SUPPORTED /* Write compressed chunk */ png_write_zTXt(png_ptr, info_ptr->text[i].key, - info_ptr->text[i].text, 0, - info_ptr->text[i].compression); + info_ptr->text[i].text, info_ptr->text[i].compression); + /* Mark this chunk as written */ + info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR; #else png_warning(png_ptr, "Unable to write compressed text"); #endif - /* Mark this chunk as written */ - info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR; } else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE) @@ -390,37 +446,16 @@ png_write_end(png_structp png_ptr, png_infop info_ptr) /* Write uncompressed chunk */ png_write_tEXt(png_ptr, info_ptr->text[i].key, info_ptr->text[i].text, 0); + /* Mark this chunk as written */ + info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR; #else png_warning(png_ptr, "Unable to write uncompressed text"); #endif - - /* Mark this chunk as written */ - info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR; } } #endif #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED - if (info_ptr->unknown_chunks_num) - { - png_unknown_chunk *up; - - png_debug(5, "writing extra chunks"); - - for (up = info_ptr->unknown_chunks; - up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num; - up++) - { - int keep = png_handle_as_unknown(png_ptr, up->name); - if (keep != PNG_HANDLE_CHUNK_NEVER && - up->location && - (up->location & PNG_AFTER_IDAT) && - ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS || - (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS))) - { - png_write_chunk(png_ptr, up->name, up->data, up->size); - } - } - } + write_unknown_chunks(png_ptr, info_ptr, PNG_AFTER_IDAT); #endif } @@ -428,6 +463,7 @@ png_write_end(png_structp png_ptr, png_infop info_ptr) /* Write end of PNG file */ png_write_IEND(png_ptr); + /* This flush, added in libpng-1.0.8, removed from libpng-1.0.9beta03, * and restored again in libpng-1.2.30, may cause some applications that * do not set png_ptr->output_flush_fn to crash. If your application @@ -443,9 +479,8 @@ png_write_end(png_structp png_ptr, png_infop info_ptr) } #ifdef PNG_CONVERT_tIME_SUPPORTED -/* "tm" structure is not supported on WindowsCE */ void PNGAPI -png_convert_from_struct_tm(png_timep ptime, PNG_CONST struct tm FAR * ttime) +png_convert_from_struct_tm(png_timep ptime, PNG_CONST struct tm * ttime) { png_debug(1, "in png_convert_from_struct_tm"); @@ -474,103 +509,75 @@ PNG_FUNCTION(png_structp,PNGAPI png_create_write_struct,(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED) { -#ifdef PNG_USER_MEM_SUPPORTED - return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn, - warn_fn, NULL, NULL, NULL)); +#ifndef PNG_USER_MEM_SUPPORTED + png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr, + error_fn, warn_fn, NULL, NULL, NULL); +#else + return png_create_write_struct_2(user_png_ver, error_ptr, error_fn, + warn_fn, NULL, NULL, NULL); } /* Alternate initialize png_ptr structure, and allocate any memory needed */ -static void png_reset_filter_heuristics(png_structp png_ptr); /* forward decl */ - PNG_FUNCTION(png_structp,PNGAPI png_create_write_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED) { -#endif /* PNG_USER_MEM_SUPPORTED */ - volatile int png_cleanup_needed = 0; -#ifdef PNG_SETJMP_SUPPORTED - volatile -#endif - png_structp png_ptr; -#ifdef PNG_SETJMP_SUPPORTED -#ifdef USE_FAR_KEYWORD - jmp_buf tmp_jmpbuf; -#endif -#endif - - png_debug(1, "in png_create_write_struct"); - -#ifdef PNG_USER_MEM_SUPPORTED - png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG, - (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr); -#else - png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); -#endif /* PNG_USER_MEM_SUPPORTED */ - if (png_ptr == NULL) - return (NULL); - - /* Added at libpng-1.2.6 */ -#ifdef PNG_SET_USER_LIMITS_SUPPORTED - png_ptr->user_width_max = PNG_USER_WIDTH_MAX; - png_ptr->user_height_max = PNG_USER_HEIGHT_MAX; -#endif - -#ifdef PNG_SETJMP_SUPPORTED -/* Applications that neglect to set up their own setjmp() and then - encounter a png_error() will longjmp here. Since the jmpbuf is - then meaningless we abort instead of returning. */ -#ifdef USE_FAR_KEYWORD - if (setjmp(tmp_jmpbuf)) -#else - if (setjmp(png_jmpbuf(png_ptr))) /* sets longjmp to match setjmp */ -#endif -#ifdef USE_FAR_KEYWORD - png_memcpy(png_jmpbuf(png_ptr), tmp_jmpbuf, png_sizeof(jmp_buf)); -#endif - PNG_ABORT(); -#endif - -#ifdef PNG_USER_MEM_SUPPORTED - png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn); -#endif /* PNG_USER_MEM_SUPPORTED */ - png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn); - - if (!png_user_version_check(png_ptr, user_png_ver)) - png_cleanup_needed = 1; - - /* Initialize zbuf - compression buffer */ - png_ptr->zbuf_size = PNG_ZBUF_SIZE; - - if (!png_cleanup_needed) + png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr, + error_fn, warn_fn, mem_ptr, malloc_fn, free_fn); +#endif /* USER_MEM */ + if (png_ptr != NULL) { - png_ptr->zbuf = (png_bytep)png_malloc_warn(png_ptr, - png_ptr->zbuf_size); - if (png_ptr->zbuf == NULL) - png_cleanup_needed = 1; + /* Set the zlib control values to defaults; they can be overridden by the + * application after the struct has been created. + */ + png_ptr->zbuffer_size = PNG_ZBUF_SIZE; + + /* The 'zlib_strategy' setting is irrelevant because png_default_claim in + * pngwutil.c defaults it according to whether or not filters will be + * used, and ignores this setting. + */ + png_ptr->zlib_strategy = PNG_Z_DEFAULT_STRATEGY; + png_ptr->zlib_level = PNG_Z_DEFAULT_COMPRESSION; + png_ptr->zlib_mem_level = 8; + png_ptr->zlib_window_bits = 15; + png_ptr->zlib_method = 8; + +#ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED + png_ptr->zlib_text_strategy = PNG_TEXT_Z_DEFAULT_STRATEGY; + png_ptr->zlib_text_level = PNG_TEXT_Z_DEFAULT_COMPRESSION; + png_ptr->zlib_text_mem_level = 8; + png_ptr->zlib_text_window_bits = 15; + png_ptr->zlib_text_method = 8; +#endif /* WRITE_COMPRESSED_TEXT */ + + /* This is a highly dubious configuration option; by default it is off, + * but it may be appropriate for private builds that are testing + * extensions not conformant to the current specification, or of + * applications that must not fail to write at all costs! + */ +#ifdef PNG_BENIGN_WRITE_ERRORS_SUPPORTED + /* In stable builds only warn if an application error can be completely + * handled. + */ + png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN; +#endif + + /* App warnings are warnings in release (or release candidate) builds but + * are errors during development. + */ +#if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC + png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN; +#endif + + /* TODO: delay this, it can be done in png_init_io() (if the app doesn't + * do it itself) avoiding setting the default function if it is not + * required. + */ + png_set_write_fn(png_ptr, NULL, NULL, NULL); } - if (png_cleanup_needed) - { - /* Clean up PNG structure and deallocate any memory. */ - png_free(png_ptr, png_ptr->zbuf); - png_ptr->zbuf = NULL; -#ifdef PNG_USER_MEM_SUPPORTED - png_destroy_struct_2((png_voidp)png_ptr, - (png_free_ptr)free_fn, (png_voidp)mem_ptr); -#else - png_destroy_struct((png_voidp)png_ptr); -#endif - return (NULL); - } - - png_set_write_fn(png_ptr, NULL, NULL, NULL); - -#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED - png_reset_filter_heuristics(png_ptr); -#endif - - return (png_ptr); + return png_ptr; } @@ -580,7 +587,7 @@ png_create_write_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr, * "write" the image seven times. */ void PNGAPI -png_write_rows(png_structp png_ptr, png_bytepp row, +png_write_rows(png_structrp png_ptr, png_bytepp row, png_uint_32 num_rows) { png_uint_32 i; /* row counter */ @@ -602,7 +609,7 @@ png_write_rows(png_structp png_ptr, png_bytepp row, * if you are writing an interlaced image. */ void PNGAPI -png_write_image(png_structp png_ptr, png_bytepp image) +png_write_image(png_structrp png_ptr, png_bytepp image) { png_uint_32 i; /* row index */ int pass, num_pass; /* pass variables */ @@ -632,10 +639,78 @@ png_write_image(png_structp png_ptr, png_bytepp image) } } +#ifdef PNG_MNG_FEATURES_SUPPORTED +/* Performs intrapixel differencing */ +static void +png_do_write_intrapixel(png_row_infop row_info, png_bytep row) +{ + png_debug(1, "in png_do_write_intrapixel"); + + if ((row_info->color_type & PNG_COLOR_MASK_COLOR) != 0) + { + int bytes_per_pixel; + png_uint_32 row_width = row_info->width; + if (row_info->bit_depth == 8) + { + png_bytep rp; + png_uint_32 i; + + if (row_info->color_type == PNG_COLOR_TYPE_RGB) + bytes_per_pixel = 3; + + else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + bytes_per_pixel = 4; + + else + return; + + for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel) + { + *(rp) = (png_byte)((*rp - *(rp + 1)) & 0xff); + *(rp + 2) = (png_byte)((*(rp + 2) - *(rp + 1)) & 0xff); + } + } + +#ifdef PNG_WRITE_16BIT_SUPPORTED + else if (row_info->bit_depth == 16) + { + png_bytep rp; + png_uint_32 i; + + if (row_info->color_type == PNG_COLOR_TYPE_RGB) + bytes_per_pixel = 6; + + else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) + bytes_per_pixel = 8; + + else + return; + + for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel) + { + png_uint_32 s0 = (*(rp ) << 8) | *(rp + 1); + png_uint_32 s1 = (*(rp + 2) << 8) | *(rp + 3); + png_uint_32 s2 = (*(rp + 4) << 8) | *(rp + 5); + png_uint_32 red = (png_uint_32)((s0 - s1) & 0xffffL); + png_uint_32 blue = (png_uint_32)((s2 - s1) & 0xffffL); + *(rp ) = (png_byte)((red >> 8) & 0xff); + *(rp + 1) = (png_byte)(red & 0xff); + *(rp + 4) = (png_byte)((blue >> 8) & 0xff); + *(rp + 5) = (png_byte)(blue & 0xff); + } + } +#endif /* WRITE_16BIT */ + } +} +#endif /* MNG_FEATURES */ + /* Called by user to write a row of image data */ void PNGAPI -png_write_row(png_structp png_ptr, png_const_bytep row) +png_write_row(png_structrp png_ptr, png_const_bytep row) { + /* 1.5.6: moved from png_struct to be a local structure: */ + png_row_info row_info; + if (png_ptr == NULL) return; @@ -646,44 +721,44 @@ png_write_row(png_structp png_ptr, png_const_bytep row) if (png_ptr->row_number == 0 && png_ptr->pass == 0) { /* Make sure we wrote the header info */ - if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE)) + if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0) png_error(png_ptr, "png_write_info was never called before png_write_row"); /* Check for transforms that have been set but were defined out */ #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED) - if (png_ptr->transformations & PNG_INVERT_MONO) + if ((png_ptr->transformations & PNG_INVERT_MONO) != 0) png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined"); #endif #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED) - if (png_ptr->transformations & PNG_FILLER) + if ((png_ptr->transformations & PNG_FILLER) != 0) png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined"); #endif #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \ defined(PNG_READ_PACKSWAP_SUPPORTED) - if (png_ptr->transformations & PNG_PACKSWAP) + if ((png_ptr->transformations & PNG_PACKSWAP) != 0) png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined"); #endif #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED) - if (png_ptr->transformations & PNG_PACK) + if ((png_ptr->transformations & PNG_PACK) != 0) png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined"); #endif #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED) - if (png_ptr->transformations & PNG_SHIFT) + if ((png_ptr->transformations & PNG_SHIFT) != 0) png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined"); #endif #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED) - if (png_ptr->transformations & PNG_BGR) + if ((png_ptr->transformations & PNG_BGR) != 0) png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined"); #endif #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED) - if (png_ptr->transformations & PNG_SWAP_BYTES) + if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0) png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined"); #endif @@ -692,12 +767,13 @@ png_write_row(png_structp png_ptr, png_const_bytep row) #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* If interlaced and not interested in row, return */ - if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE)) + if (png_ptr->interlaced != 0 && + (png_ptr->transformations & PNG_INTERLACE) != 0) { switch (png_ptr->pass) { case 0: - if (png_ptr->row_number & 0x07) + if ((png_ptr->row_number & 0x07) != 0) { png_write_finish_row(png_ptr); return; @@ -705,7 +781,7 @@ png_write_row(png_structp png_ptr, png_const_bytep row) break; case 1: - if ((png_ptr->row_number & 0x07) || png_ptr->width < 5) + if ((png_ptr->row_number & 0x07) != 0 || png_ptr->width < 5) { png_write_finish_row(png_ptr); return; @@ -721,7 +797,7 @@ png_write_row(png_structp png_ptr, png_const_bytep row) break; case 3: - if ((png_ptr->row_number & 0x03) || png_ptr->width < 3) + if ((png_ptr->row_number & 0x03) != 0 || png_ptr->width < 3) { png_write_finish_row(png_ptr); return; @@ -737,7 +813,7 @@ png_write_row(png_structp png_ptr, png_const_bytep row) break; case 5: - if ((png_ptr->row_number & 0x01) || png_ptr->width < 2) + if ((png_ptr->row_number & 0x01) != 0 || png_ptr->width < 2) { png_write_finish_row(png_ptr); return; @@ -745,7 +821,7 @@ png_write_row(png_structp png_ptr, png_const_bytep row) break; case 6: - if (!(png_ptr->row_number & 0x01)) + if ((png_ptr->row_number & 0x01) == 0) { png_write_finish_row(png_ptr); return; @@ -759,36 +835,31 @@ png_write_row(png_structp png_ptr, png_const_bytep row) #endif /* Set up row info for transformations */ - png_ptr->row_info.color_type = png_ptr->color_type; - png_ptr->row_info.width = png_ptr->usr_width; - png_ptr->row_info.channels = png_ptr->usr_channels; - png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth; - png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth * - png_ptr->row_info.channels); + row_info.color_type = png_ptr->color_type; + row_info.width = png_ptr->usr_width; + row_info.channels = png_ptr->usr_channels; + row_info.bit_depth = png_ptr->usr_bit_depth; + row_info.pixel_depth = (png_byte)(row_info.bit_depth * row_info.channels); + row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width); - png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth, - png_ptr->row_info.width); - - png_debug1(3, "row_info->color_type = %d", png_ptr->row_info.color_type); - png_debug1(3, "row_info->width = %u", png_ptr->row_info.width); - png_debug1(3, "row_info->channels = %d", png_ptr->row_info.channels); - png_debug1(3, "row_info->bit_depth = %d", png_ptr->row_info.bit_depth); - png_debug1(3, "row_info->pixel_depth = %d", png_ptr->row_info.pixel_depth); - png_debug1(3, "row_info->rowbytes = %lu", - (unsigned long)png_ptr->row_info.rowbytes); + png_debug1(3, "row_info->color_type = %d", row_info.color_type); + png_debug1(3, "row_info->width = %u", row_info.width); + png_debug1(3, "row_info->channels = %d", row_info.channels); + png_debug1(3, "row_info->bit_depth = %d", row_info.bit_depth); + png_debug1(3, "row_info->pixel_depth = %d", row_info.pixel_depth); + png_debug1(3, "row_info->rowbytes = %lu", (unsigned long)row_info.rowbytes); /* Copy user's row into buffer, leaving room for filter byte. */ - png_memcpy(png_ptr->row_buf + 1, row, png_ptr->row_info.rowbytes); + memcpy(png_ptr->row_buf + 1, row, row_info.rowbytes); #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* Handle interlacing */ if (png_ptr->interlaced && png_ptr->pass < 6 && - (png_ptr->transformations & PNG_INTERLACE)) + (png_ptr->transformations & PNG_INTERLACE) != 0) { - png_do_write_interlace(&(png_ptr->row_info), - png_ptr->row_buf + 1, png_ptr->pass); + png_do_write_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass); /* This should always get caught above, but still ... */ - if (!(png_ptr->row_info.width)) + if (row_info.width == 0) { png_write_finish_row(png_ptr); return; @@ -798,10 +869,17 @@ png_write_row(png_structp png_ptr, png_const_bytep row) #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED /* Handle other transformations */ - if (png_ptr->transformations) - png_do_write_transformations(png_ptr); + if (png_ptr->transformations != 0) + png_do_write_transformations(png_ptr, &row_info); #endif + /* At this point the row_info pixel depth must match the 'transformed' depth, + * which is also the output depth. + */ + if (row_info.pixel_depth != png_ptr->pixel_depth || + row_info.pixel_depth != png_ptr->transformed_pixel_depth) + png_error(png_ptr, "internal write transform logic error"); + #ifdef PNG_MNG_FEATURES_SUPPORTED /* Write filter_method 64 (intrapixel differencing) only if * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and @@ -812,16 +890,24 @@ png_write_row(png_structp png_ptr, png_const_bytep row) * 4. The filter_method is 64 and * 5. The color_type is RGB or RGBA */ - if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) && + if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 && (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING)) { /* Intrapixel differencing */ - png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1); + png_do_write_intrapixel(&row_info, png_ptr->row_buf + 1); } #endif +/* Added at libpng-1.5.10 */ +#ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED + /* Check for out-of-range palette index */ + if (row_info.color_type == PNG_COLOR_TYPE_PALETTE && + png_ptr->num_palette_max >= 0) + png_do_check_palette_indexes(png_ptr, &row_info); +#endif + /* Find a filter if necessary, filter the row and write it out. */ - png_write_find_filter(png_ptr, &(png_ptr->row_info)); + png_write_find_filter(png_ptr, &row_info); if (png_ptr->write_row_fn != NULL) (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass); @@ -830,7 +916,7 @@ png_write_row(png_structp png_ptr, png_const_bytep row) #ifdef PNG_WRITE_FLUSH_SUPPORTED /* Set the automatic flush interval or 0 to turn flushing off */ void PNGAPI -png_set_flush(png_structp png_ptr, int nrows) +png_set_flush(png_structrp png_ptr, int nrows) { png_debug(1, "in png_set_flush"); @@ -842,10 +928,8 @@ png_set_flush(png_structp png_ptr, int nrows) /* Flush the current output buffers now */ void PNGAPI -png_write_flush(png_structp png_ptr) +png_write_flush(png_structrp png_ptr) { - int wrote_IDAT; - png_debug(1, "in png_write_flush"); if (png_ptr == NULL) @@ -855,146 +939,41 @@ png_write_flush(png_structp png_ptr) if (png_ptr->row_number >= png_ptr->num_rows) return; - do - { - int ret; - - /* Compress the data */ - ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH); - wrote_IDAT = 0; - - /* Check for compression errors */ - if (ret != Z_OK) - { - if (png_ptr->zstream.msg != NULL) - png_error(png_ptr, png_ptr->zstream.msg); - - else - png_error(png_ptr, "zlib error"); - } - - if (!(png_ptr->zstream.avail_out)) - { - /* Write the IDAT and reset the zlib output buffer */ - png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size); - wrote_IDAT = 1; - } - } while (wrote_IDAT == 1); - - /* If there is any data left to be output, write it into a new IDAT */ - if (png_ptr->zbuf_size != png_ptr->zstream.avail_out) - { - /* Write the IDAT and reset the zlib output buffer */ - png_write_IDAT(png_ptr, png_ptr->zbuf, - png_ptr->zbuf_size - png_ptr->zstream.avail_out); - } + png_compress_IDAT(png_ptr, NULL, 0, Z_SYNC_FLUSH); png_ptr->flush_rows = 0; png_flush(png_ptr); } -#endif /* PNG_WRITE_FLUSH_SUPPORTED */ +#endif /* WRITE_FLUSH */ -/* Free all memory used by the write */ -void PNGAPI -png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr) +#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED +static void png_reset_filter_heuristics(png_structrp png_ptr);/* forward decl */ +#endif + +/* Free any memory used in png_ptr struct without freeing the struct itself. */ +static void +png_write_destroy(png_structrp png_ptr) { - png_structp png_ptr = NULL; - png_infop info_ptr = NULL; -#ifdef PNG_USER_MEM_SUPPORTED - png_free_ptr free_fn = NULL; - png_voidp mem_ptr = NULL; -#endif - - png_debug(1, "in png_destroy_write_struct"); - - if (png_ptr_ptr != NULL) - { - png_ptr = *png_ptr_ptr; -#ifdef PNG_USER_MEM_SUPPORTED - free_fn = png_ptr->free_fn; - mem_ptr = png_ptr->mem_ptr; -#endif - } - -#ifdef PNG_USER_MEM_SUPPORTED - if (png_ptr != NULL) - { - free_fn = png_ptr->free_fn; - mem_ptr = png_ptr->mem_ptr; - } -#endif - - if (info_ptr_ptr != NULL) - info_ptr = *info_ptr_ptr; - - if (info_ptr != NULL) - { - if (png_ptr != NULL) - { - png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1); - -#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED - if (png_ptr->num_chunk_list) - { - png_free(png_ptr, png_ptr->chunk_list); - png_ptr->num_chunk_list = 0; - } -#endif - } - -#ifdef PNG_USER_MEM_SUPPORTED - png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn, - (png_voidp)mem_ptr); -#else - png_destroy_struct((png_voidp)info_ptr); -#endif - *info_ptr_ptr = NULL; - } - - if (png_ptr != NULL) - { - png_write_destroy(png_ptr); -#ifdef PNG_USER_MEM_SUPPORTED - png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn, - (png_voidp)mem_ptr); -#else - png_destroy_struct((png_voidp)png_ptr); -#endif - *png_ptr_ptr = NULL; - } -} - - -/* Free any memory used in png_ptr struct (old method) */ -void /* PRIVATE */ -png_write_destroy(png_structp png_ptr) -{ -#ifdef PNG_SETJMP_SUPPORTED - jmp_buf tmp_jmp; /* Save jump buffer */ -#endif - png_error_ptr error_fn; -#ifdef PNG_WARNINGS_SUPPORTED - png_error_ptr warning_fn; -#endif - png_voidp error_ptr; -#ifdef PNG_USER_MEM_SUPPORTED - png_free_ptr free_fn; -#endif - png_debug(1, "in png_write_destroy"); /* Free any memory zlib uses */ - if (png_ptr->zlib_state != PNG_ZLIB_UNINITIALIZED) + if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0) deflateEnd(&png_ptr->zstream); /* Free our memory. png_free checks NULL for us. */ - png_free(png_ptr, png_ptr->zbuf); + png_free_buffer_list(png_ptr, &png_ptr->zbuffer_list); png_free(png_ptr, png_ptr->row_buf); + png_ptr->row_buf = NULL; #ifdef PNG_WRITE_FILTER_SUPPORTED png_free(png_ptr, png_ptr->prev_row); png_free(png_ptr, png_ptr->sub_row); png_free(png_ptr, png_ptr->up_row); png_free(png_ptr, png_ptr->avg_row); png_free(png_ptr, png_ptr->paeth_row); + png_ptr->prev_row = NULL; + png_ptr->sub_row = NULL; + png_ptr->up_row = NULL; + png_ptr->avg_row = NULL; + png_ptr->paeth_row = NULL; #endif #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED @@ -1002,41 +981,51 @@ png_write_destroy(png_structp png_ptr) png_reset_filter_heuristics(png_ptr); png_free(png_ptr, png_ptr->filter_costs); png_free(png_ptr, png_ptr->inv_filter_costs); + png_ptr->filter_costs = NULL; + png_ptr->inv_filter_costs = NULL; #endif -#ifdef PNG_SETJMP_SUPPORTED - /* Reset structure */ - png_memcpy(tmp_jmp, png_ptr->longjmp_buffer, png_sizeof(jmp_buf)); +#ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED + png_free(png_ptr, png_ptr->chunk_list); + png_ptr->chunk_list = NULL; #endif - error_fn = png_ptr->error_fn; -#ifdef PNG_WARNINGS_SUPPORTED - warning_fn = png_ptr->warning_fn; -#endif - error_ptr = png_ptr->error_ptr; -#ifdef PNG_USER_MEM_SUPPORTED - free_fn = png_ptr->free_fn; -#endif + /* The error handling and memory handling information is left intact at this + * point: the jmp_buf may still have to be freed. See png_destroy_png_struct + * for how this happens. + */ +} - png_memset(png_ptr, 0, png_sizeof(png_struct)); +/* Free all memory used by the write. + * In libpng 1.6.0 this API changed quietly to no longer accept a NULL value for + * *png_ptr_ptr. Prior to 1.6.0 it would accept such a value and it would free + * the passed in info_structs but it would quietly fail to free any of the data + * inside them. In 1.6.0 it quietly does nothing (it has to be quiet because it + * has no png_ptr.) + */ +void PNGAPI +png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr) +{ + png_debug(1, "in png_destroy_write_struct"); - png_ptr->error_fn = error_fn; -#ifdef PNG_WARNINGS_SUPPORTED - png_ptr->warning_fn = warning_fn; -#endif - png_ptr->error_ptr = error_ptr; -#ifdef PNG_USER_MEM_SUPPORTED - png_ptr->free_fn = free_fn; -#endif + if (png_ptr_ptr != NULL) + { + png_structrp png_ptr = *png_ptr_ptr; -#ifdef PNG_SETJMP_SUPPORTED - png_memcpy(png_ptr->longjmp_buffer, tmp_jmp, png_sizeof(jmp_buf)); -#endif + if (png_ptr != NULL) /* added in libpng 1.6.0 */ + { + png_destroy_info_struct(png_ptr, info_ptr_ptr); + + *png_ptr_ptr = NULL; + png_write_destroy(png_ptr); + png_destroy_png_struct(png_ptr); + } + } } /* Allow the application to select one or more row filters to use. */ void PNGAPI -png_set_filter(png_structp png_ptr, int method, int filters) +png_set_filter(png_structrp png_ptr, int method, int filters) { png_debug(1, "in png_set_filter"); @@ -1044,7 +1033,7 @@ png_set_filter(png_structp png_ptr, int method, int filters) return; #ifdef PNG_MNG_FEATURES_SUPPORTED - if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) && + if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 && (method == PNG_INTRAPIXEL_DIFFERENCING)) method = PNG_FILTER_TYPE_BASE; @@ -1056,8 +1045,9 @@ png_set_filter(png_structp png_ptr, int method, int filters) #ifdef PNG_WRITE_FILTER_SUPPORTED case 5: case 6: - case 7: png_warning(png_ptr, "Unknown row filter for method 0"); -#endif /* PNG_WRITE_FILTER_SUPPORTED */ + case 7: png_app_error(png_ptr, "Unknown row filter for method 0"); + /* FALL THROUGH */ +#endif /* WRITE_FILTER */ case PNG_FILTER_VALUE_NONE: png_ptr->do_filter = PNG_FILTER_NONE; break; @@ -1078,8 +1068,8 @@ png_set_filter(png_structp png_ptr, int method, int filters) png_ptr->do_filter = (png_byte)filters; break; #else default: - png_warning(png_ptr, "Unknown row filter for method 0"); -#endif /* PNG_WRITE_FILTER_SUPPORTED */ + png_app_error(png_ptr, "Unknown row filter for method 0"); +#endif /* WRITE_FILTER */ } /* If we have allocated the row_buf, this means we have already started @@ -1094,14 +1084,16 @@ png_set_filter(png_structp png_ptr, int method, int filters) if (png_ptr->row_buf != NULL) { #ifdef PNG_WRITE_FILTER_SUPPORTED - if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL) + if ((png_ptr->do_filter & PNG_FILTER_SUB) != 0 && + png_ptr->sub_row == NULL) { png_ptr->sub_row = (png_bytep)png_malloc(png_ptr, (png_ptr->rowbytes + 1)); png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB; } - if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL) + if ((png_ptr->do_filter & PNG_FILTER_UP) != 0 && + png_ptr->up_row == NULL) { if (png_ptr->prev_row == NULL) { @@ -1118,7 +1110,8 @@ png_set_filter(png_structp png_ptr, int method, int filters) } } - if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL) + if ((png_ptr->do_filter & PNG_FILTER_AVG) != 0 && + png_ptr->avg_row == NULL) { if (png_ptr->prev_row == NULL) { @@ -1135,7 +1128,7 @@ png_set_filter(png_structp png_ptr, int method, int filters) } } - if ((png_ptr->do_filter & PNG_FILTER_PAETH) && + if ((png_ptr->do_filter & PNG_FILTER_PAETH) != 0 && png_ptr->paeth_row == NULL) { if (png_ptr->prev_row == NULL) @@ -1153,7 +1146,7 @@ png_set_filter(png_structp png_ptr, int method, int filters) } if (png_ptr->do_filter == PNG_NO_FILTERS) -#endif /* PNG_WRITE_FILTER_SUPPORTED */ +#endif /* WRITE_FILTER */ png_ptr->do_filter = PNG_FILTER_NONE; } } @@ -1171,7 +1164,7 @@ png_set_filter(png_structp png_ptr, int method, int filters) #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* GRR 970116 */ /* Convenience reset API. */ static void -png_reset_filter_heuristics(png_structp png_ptr) +png_reset_filter_heuristics(png_structrp png_ptr) { /* Clear out any old values in the 'weights' - this must be done because if * the app calls set_filter_heuristics multiple times with different @@ -1204,7 +1197,7 @@ png_reset_filter_heuristics(png_structp png_ptr) } static int -png_init_filter_heuristics(png_structp png_ptr, int heuristic_method, +png_init_filter_heuristics(png_structrp png_ptr, int heuristic_method, int num_weights) { if (png_ptr == NULL) @@ -1224,7 +1217,7 @@ png_init_filter_heuristics(png_structp png_ptr, int heuristic_method, if (num_weights > 0) { png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr, - (png_uint_32)(png_sizeof(png_byte) * num_weights)); + (png_uint_32)((sizeof (png_byte)) * num_weights)); /* To make sure that the weighting starts out fairly */ for (i = 0; i < num_weights; i++) @@ -1233,10 +1226,10 @@ png_init_filter_heuristics(png_structp png_ptr, int heuristic_method, } png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr, - (png_uint_32)(png_sizeof(png_uint_16) * num_weights)); + (png_uint_32)((sizeof (png_uint_16)) * num_weights)); png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr, - (png_uint_32)(png_sizeof(png_uint_16) * num_weights)); + (png_uint_32)((sizeof (png_uint_16)) * num_weights)); for (i = 0; i < num_weights; i++) { @@ -1254,10 +1247,10 @@ png_init_filter_heuristics(png_structp png_ptr, int heuristic_method, if (png_ptr->filter_costs == NULL) { png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr, - (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST)); + (png_uint_32)((sizeof (png_uint_16)) * PNG_FILTER_VALUE_LAST)); png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr, - (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST)); + (png_uint_32)((sizeof (png_uint_16)) * PNG_FILTER_VALUE_LAST)); } for (i = 0; i < PNG_FILTER_VALUE_LAST; i++) @@ -1287,7 +1280,7 @@ png_init_filter_heuristics(png_structp png_ptr, int heuristic_method, /* Provide floating and fixed point APIs */ #ifdef PNG_FLOATING_POINT_SUPPORTED void PNGAPI -png_set_filter_heuristics(png_structp png_ptr, int heuristic_method, +png_set_filter_heuristics(png_structrp png_ptr, int heuristic_method, int num_weights, png_const_doublep filter_weights, png_const_doublep filter_costs) { @@ -1296,7 +1289,7 @@ png_set_filter_heuristics(png_structp png_ptr, int heuristic_method, /* The internal API allocates all the arrays and ensures that the elements of * those arrays are set to the default value. */ - if (!png_init_filter_heuristics(png_ptr, heuristic_method, num_weights)) + if (png_init_filter_heuristics(png_ptr, heuristic_method, num_weights) == 0) return; /* If using the weighted method copy in the weights. */ @@ -1342,7 +1335,7 @@ png_set_filter_heuristics(png_structp png_ptr, int heuristic_method, #ifdef PNG_FIXED_POINT_SUPPORTED void PNGAPI -png_set_filter_heuristics_fixed(png_structp png_ptr, int heuristic_method, +png_set_filter_heuristics_fixed(png_structrp png_ptr, int heuristic_method, int num_weights, png_const_fixed_point_p filter_weights, png_const_fixed_point_p filter_costs) { @@ -1351,7 +1344,7 @@ png_set_filter_heuristics_fixed(png_structp png_ptr, int heuristic_method, /* The internal API allocates all the arrays and ensures that the elements of * those arrays are set to the default value. */ - if (!png_init_filter_heuristics(png_ptr, heuristic_method, num_weights)) + if (png_init_filter_heuristics(png_ptr, heuristic_method, num_weights) == 0) return; /* If using the weighted method copy in the weights. */ @@ -1405,40 +1398,40 @@ png_set_filter_heuristics_fixed(png_structp png_ptr, int heuristic_method, } } #endif /* FIXED_POINT */ -#endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */ +#endif /* WRITE_WEIGHTED_FILTER */ void PNGAPI -png_set_compression_level(png_structp png_ptr, int level) +png_set_compression_level(png_structrp png_ptr, int level) { png_debug(1, "in png_set_compression_level"); if (png_ptr == NULL) return; - png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL; png_ptr->zlib_level = level; } void PNGAPI -png_set_compression_mem_level(png_structp png_ptr, int mem_level) +png_set_compression_mem_level(png_structrp png_ptr, int mem_level) { png_debug(1, "in png_set_compression_mem_level"); if (png_ptr == NULL) return; - png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL; png_ptr->zlib_mem_level = mem_level; } void PNGAPI -png_set_compression_strategy(png_structp png_ptr, int strategy) +png_set_compression_strategy(png_structrp png_ptr, int strategy) { png_debug(1, "in png_set_compression_strategy"); if (png_ptr == NULL) return; + /* The flag setting here prevents the libpng dynamic selection of strategy. + */ png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY; png_ptr->zlib_strategy = strategy; } @@ -1447,80 +1440,81 @@ png_set_compression_strategy(png_structp png_ptr, int strategy) * smaller value of window_bits if it can do so safely. */ void PNGAPI -png_set_compression_window_bits(png_structp png_ptr, int window_bits) +png_set_compression_window_bits(png_structrp png_ptr, int window_bits) { if (png_ptr == NULL) return; + /* Prior to 1.6.0 this would warn but then set the window_bits value, this + * meant that negative window bits values could be selected which would cause + * libpng to write a non-standard PNG file with raw deflate or gzip + * compressed IDAT or ancillary chunks. Such files can be read and there is + * no warning on read, so this seems like a very bad idea. + */ if (window_bits > 15) + { png_warning(png_ptr, "Only compression windows <= 32k supported by PNG"); + window_bits = 15; + } else if (window_bits < 8) + { png_warning(png_ptr, "Only compression windows >= 256 supported by PNG"); + window_bits = 8; + } -#ifndef WBITS_8_OK - /* Avoid libpng bug with 256-byte windows */ - if (window_bits == 8) - { - png_warning(png_ptr, "Compression window is being reset to 512"); - window_bits = 9; - } - -#endif - png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS; png_ptr->zlib_window_bits = window_bits; } void PNGAPI -png_set_compression_method(png_structp png_ptr, int method) +png_set_compression_method(png_structrp png_ptr, int method) { png_debug(1, "in png_set_compression_method"); if (png_ptr == NULL) return; + /* This would produce an invalid PNG file if it worked, but it doesn't and + * deflate will fault it, so it is harmless to just warn here. + */ if (method != 8) png_warning(png_ptr, "Only compression method 8 is supported by PNG"); - png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD; png_ptr->zlib_method = method; } /* The following were added to libpng-1.5.4 */ #ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED void PNGAPI -png_set_text_compression_level(png_structp png_ptr, int level) +png_set_text_compression_level(png_structrp png_ptr, int level) { png_debug(1, "in png_set_text_compression_level"); if (png_ptr == NULL) return; - png_ptr->flags |= PNG_FLAG_ZTXT_CUSTOM_LEVEL; png_ptr->zlib_text_level = level; } void PNGAPI -png_set_text_compression_mem_level(png_structp png_ptr, int mem_level) +png_set_text_compression_mem_level(png_structrp png_ptr, int mem_level) { png_debug(1, "in png_set_text_compression_mem_level"); if (png_ptr == NULL) return; - png_ptr->flags |= PNG_FLAG_ZTXT_CUSTOM_MEM_LEVEL; png_ptr->zlib_text_mem_level = mem_level; } void PNGAPI -png_set_text_compression_strategy(png_structp png_ptr, int strategy) +png_set_text_compression_strategy(png_structrp png_ptr, int strategy) { png_debug(1, "in png_set_text_compression_strategy"); if (png_ptr == NULL) return; - png_ptr->flags |= PNG_FLAG_ZTXT_CUSTOM_STRATEGY; png_ptr->zlib_text_strategy = strategy; } @@ -1528,32 +1522,28 @@ png_set_text_compression_strategy(png_structp png_ptr, int strategy) * smaller value of window_bits if it can do so safely. */ void PNGAPI -png_set_text_compression_window_bits(png_structp png_ptr, int window_bits) +png_set_text_compression_window_bits(png_structrp png_ptr, int window_bits) { if (png_ptr == NULL) return; if (window_bits > 15) + { png_warning(png_ptr, "Only compression windows <= 32k supported by PNG"); + window_bits = 15; + } else if (window_bits < 8) + { png_warning(png_ptr, "Only compression windows >= 256 supported by PNG"); + window_bits = 8; + } -#ifndef WBITS_8_OK - /* Avoid libpng bug with 256-byte windows */ - if (window_bits == 8) - { - png_warning(png_ptr, "Text compression window is being reset to 512"); - window_bits = 9; - } - -#endif - png_ptr->flags |= PNG_FLAG_ZTXT_CUSTOM_WINDOW_BITS; png_ptr->zlib_text_window_bits = window_bits; } void PNGAPI -png_set_text_compression_method(png_structp png_ptr, int method) +png_set_text_compression_method(png_structrp png_ptr, int method) { png_debug(1, "in png_set_text_compression_method"); @@ -1563,14 +1553,13 @@ png_set_text_compression_method(png_structp png_ptr, int method) if (method != 8) png_warning(png_ptr, "Only compression method 8 is supported by PNG"); - png_ptr->flags |= PNG_FLAG_ZTXT_CUSTOM_METHOD; png_ptr->zlib_text_method = method; } -#endif /* PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED */ +#endif /* WRITE_CUSTOMIZE_ZTXT_COMPRESSION */ /* end of API added to libpng-1.5.4 */ void PNGAPI -png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn) +png_set_write_status_fn(png_structrp png_ptr, png_write_status_ptr write_row_fn) { if (png_ptr == NULL) return; @@ -1580,7 +1569,7 @@ png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn) #ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED void PNGAPI -png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr +png_set_write_user_transform_fn(png_structrp png_ptr, png_user_transform_ptr write_user_transform_fn) { png_debug(1, "in png_set_write_user_transform_fn"); @@ -1596,88 +1585,899 @@ png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr #ifdef PNG_INFO_IMAGE_SUPPORTED void PNGAPI -png_write_png(png_structp png_ptr, png_infop info_ptr, +png_write_png(png_structrp png_ptr, png_inforp info_ptr, int transforms, voidp params) { if (png_ptr == NULL || info_ptr == NULL) return; + if ((info_ptr->valid & PNG_INFO_IDAT) == 0) + { + png_app_error(png_ptr, "no rows for png_write_image to write"); + return; + } + /* Write the file header information. */ png_write_info(png_ptr, info_ptr); /* ------ these transformations don't touch the info structure ------- */ -#ifdef PNG_WRITE_INVERT_SUPPORTED /* Invert monochrome pixels */ - if (transforms & PNG_TRANSFORM_INVERT_MONO) + if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0) +#ifdef PNG_WRITE_INVERT_SUPPORTED png_set_invert_mono(png_ptr); +#else + png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported"); #endif -#ifdef PNG_WRITE_SHIFT_SUPPORTED /* Shift the pixels up to a legal bit depth and fill in * as appropriate to correctly scale the image. */ - if ((transforms & PNG_TRANSFORM_SHIFT) - && (info_ptr->valid & PNG_INFO_sBIT)) - png_set_shift(png_ptr, &info_ptr->sig_bit); + if ((transforms & PNG_TRANSFORM_SHIFT) != 0) +#ifdef PNG_WRITE_SHIFT_SUPPORTED + if ((info_ptr->valid & PNG_INFO_sBIT) != 0) + png_set_shift(png_ptr, &info_ptr->sig_bit); +#else + png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported"); #endif -#ifdef PNG_WRITE_PACK_SUPPORTED /* Pack pixels into bytes */ - if (transforms & PNG_TRANSFORM_PACKING) - png_set_packing(png_ptr); + if ((transforms & PNG_TRANSFORM_PACKING) != 0) +#ifdef PNG_WRITE_PACK_SUPPORTED + png_set_packing(png_ptr); +#else + png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported"); #endif -#ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED /* Swap location of alpha bytes from ARGB to RGBA */ - if (transforms & PNG_TRANSFORM_SWAP_ALPHA) + if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0) +#ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED png_set_swap_alpha(png_ptr); +#else + png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported"); #endif + /* Remove a filler (X) from XRGB/RGBX/AG/GA into to convert it into + * RGB, note that the code expects the input color type to be G or RGB; no + * alpha channel. + */ + if ((transforms & (PNG_TRANSFORM_STRIP_FILLER_AFTER| + PNG_TRANSFORM_STRIP_FILLER_BEFORE)) != 0) + { #ifdef PNG_WRITE_FILLER_SUPPORTED - /* Pack XRGB/RGBX/ARGB/RGBA into RGB (4 channels -> 3 channels) */ - if (transforms & PNG_TRANSFORM_STRIP_FILLER_AFTER) - png_set_filler(png_ptr, 0, PNG_FILLER_AFTER); + if ((transforms & PNG_TRANSFORM_STRIP_FILLER_AFTER) != 0) + { + if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0) + png_app_error(png_ptr, + "PNG_TRANSFORM_STRIP_FILLER: BEFORE+AFTER not supported"); - else if (transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) - png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE); + /* Continue if ignored - this is the pre-1.6.10 behavior */ + png_set_filler(png_ptr, 0, PNG_FILLER_AFTER); + } + + else if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0) + png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE); +#else + png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_FILLER not supported"); #endif + } -#ifdef PNG_WRITE_BGR_SUPPORTED /* Flip BGR pixels to RGB */ - if (transforms & PNG_TRANSFORM_BGR) + if ((transforms & PNG_TRANSFORM_BGR) != 0) +#ifdef PNG_WRITE_BGR_SUPPORTED png_set_bgr(png_ptr); +#else + png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported"); #endif -#ifdef PNG_WRITE_SWAP_SUPPORTED /* Swap bytes of 16-bit files to most significant byte first */ - if (transforms & PNG_TRANSFORM_SWAP_ENDIAN) + if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0) +#ifdef PNG_WRITE_SWAP_SUPPORTED png_set_swap(png_ptr); +#else + png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported"); #endif -#ifdef PNG_WRITE_PACKSWAP_SUPPORTED /* Swap bits of 1, 2, 4 bit packed pixel formats */ - if (transforms & PNG_TRANSFORM_PACKSWAP) + if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0) +#ifdef PNG_WRITE_PACKSWAP_SUPPORTED png_set_packswap(png_ptr); +#else + png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported"); #endif -#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED /* Invert the alpha channel from opacity to transparency */ - if (transforms & PNG_TRANSFORM_INVERT_ALPHA) + if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0) +#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED png_set_invert_alpha(png_ptr); +#else + png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported"); #endif /* ----------------------- end of transformations ------------------- */ /* Write the bits */ - if (info_ptr->valid & PNG_INFO_IDAT) - png_write_image(png_ptr, info_ptr->row_pointers); + png_write_image(png_ptr, info_ptr->row_pointers); /* It is REQUIRED to call this to finish writing the rest of the file */ png_write_end(png_ptr, info_ptr); - PNG_UNUSED(transforms) /* Quiet compiler warnings */ PNG_UNUSED(params) } #endif -#endif /* PNG_WRITE_SUPPORTED */ + + +#ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED +#ifdef PNG_STDIO_SUPPORTED /* currently required for png_image_write_* */ +/* Initialize the write structure - general purpose utility. */ +static int +png_image_write_init(png_imagep image) +{ + png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, image, + png_safe_error, png_safe_warning); + + if (png_ptr != NULL) + { + png_infop info_ptr = png_create_info_struct(png_ptr); + + if (info_ptr != NULL) + { + png_controlp control = png_voidcast(png_controlp, + png_malloc_warn(png_ptr, (sizeof *control))); + + if (control != NULL) + { + memset(control, 0, (sizeof *control)); + + control->png_ptr = png_ptr; + control->info_ptr = info_ptr; + control->for_write = 1; + + image->opaque = control; + return 1; + } + + /* Error clean up */ + png_destroy_info_struct(png_ptr, &info_ptr); + } + + png_destroy_write_struct(&png_ptr, NULL); + } + + return png_image_error(image, "png_image_write_: out of memory"); +} + +/* Arguments to png_image_write_main: */ +typedef struct +{ + /* Arguments: */ + png_imagep image; + png_const_voidp buffer; + png_int_32 row_stride; + png_const_voidp colormap; + int convert_to_8bit; + /* Local variables: */ + png_const_voidp first_row; + ptrdiff_t row_bytes; + png_voidp local_row; +} png_image_write_control; + +/* Write png_uint_16 input to a 16-bit PNG; the png_ptr has already been set to + * do any necessary byte swapping. The component order is defined by the + * png_image format value. + */ +static int +png_write_image_16bit(png_voidp argument) +{ + png_image_write_control *display = png_voidcast(png_image_write_control*, + argument); + png_imagep image = display->image; + png_structrp png_ptr = image->opaque->png_ptr; + + png_const_uint_16p input_row = png_voidcast(png_const_uint_16p, + display->first_row); + png_uint_16p output_row = png_voidcast(png_uint_16p, display->local_row); + png_uint_16p row_end; + const int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ? 3 : 1; + int aindex = 0; + png_uint_32 y = image->height; + + if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0) + { +# ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED + if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0) + { + aindex = -1; + ++input_row; /* To point to the first component */ + ++output_row; + } + + else +# endif + aindex = channels; + } + + else + png_error(png_ptr, "png_write_image: internal call error"); + + /* Work out the output row end and count over this, note that the increment + * above to 'row' means that row_end can actually be beyond the end of the + * row; this is correct. + */ + row_end = output_row + image->width * (channels+1); + + while (y-- > 0) + { + png_const_uint_16p in_ptr = input_row; + png_uint_16p out_ptr = output_row; + + while (out_ptr < row_end) + { + const png_uint_16 alpha = in_ptr[aindex]; + png_uint_32 reciprocal = 0; + int c; + + out_ptr[aindex] = alpha; + + /* Calculate a reciprocal. The correct calculation is simply + * component/alpha*65535 << 15. (I.e. 15 bits of precision); this + * allows correct rounding by adding .5 before the shift. 'reciprocal' + * is only initialized when required. + */ + if (alpha > 0 && alpha < 65535) + reciprocal = ((0xffff<<15)+(alpha>>1))/alpha; + + c = channels; + do /* always at least one channel */ + { + png_uint_16 component = *in_ptr++; + + /* The following gives 65535 for an alpha of 0, which is fine, + * otherwise if 0/0 is represented as some other value there is more + * likely to be a discontinuity which will probably damage + * compression when moving from a fully transparent area to a + * nearly transparent one. (The assumption here is that opaque + * areas tend not to be 0 intensity.) + */ + if (component >= alpha) + component = 65535; + + /* component 0 && alpha < 65535) + { + png_uint_32 calc = component * reciprocal; + calc += 16384; /* round to nearest */ + component = (png_uint_16)(calc >> 15); + } + + *out_ptr++ = component; + } + while (--c > 0); + + /* Skip to next component (skip the intervening alpha channel) */ + ++in_ptr; + ++out_ptr; + } + + png_write_row(png_ptr, png_voidcast(png_const_bytep, display->local_row)); + input_row += display->row_bytes/(sizeof (png_uint_16)); + } + + return 1; +} + +/* Given 16-bit input (1 to 4 channels) write 8-bit output. If an alpha channel + * is present it must be removed from the components, the components are then + * written in sRGB encoding. No components are added or removed. + * + * Calculate an alpha reciprocal to reverse pre-multiplication. As above the + * calculation can be done to 15 bits of accuracy; however, the output needs to + * be scaled in the range 0..255*65535, so include that scaling here. + */ +#define UNP_RECIPROCAL(alpha) ((((0xffff*0xff)<<7)+(alpha>>1))/alpha) + +static png_byte +png_unpremultiply(png_uint_32 component, png_uint_32 alpha, + png_uint_32 reciprocal/*from the above macro*/) +{ + /* The following gives 1.0 for an alpha of 0, which is fine, otherwise if 0/0 + * is represented as some other value there is more likely to be a + * discontinuity which will probably damage compression when moving from a + * fully transparent area to a nearly transparent one. (The assumption here + * is that opaque areas tend not to be 0 intensity.) + * + * There is a rounding problem here; if alpha is less than 128 it will end up + * as 0 when scaled to 8 bits. To avoid introducing spurious colors into the + * output change for this too. + */ + if (component >= alpha || alpha < 128) + return 255; + + /* component 0) + { + /* The test is that alpha/257 (rounded) is less than 255, the first value + * that becomes 255 is 65407. + * NOTE: this must agree with the PNG_DIV257 macro (which must, therefore, + * be exact!) [Could also test reciprocal != 0] + */ + if (alpha < 65407) + { + component *= reciprocal; + component += 64; /* round to nearest */ + component >>= 7; + } + + else + component *= 255; + + /* Convert the component to sRGB. */ + return (png_byte)PNG_sRGB_FROM_LINEAR(component); + } + + else + return 0; +} + +static int +png_write_image_8bit(png_voidp argument) +{ + png_image_write_control *display = png_voidcast(png_image_write_control*, + argument); + png_imagep image = display->image; + png_structrp png_ptr = image->opaque->png_ptr; + + png_const_uint_16p input_row = png_voidcast(png_const_uint_16p, + display->first_row); + png_bytep output_row = png_voidcast(png_bytep, display->local_row); + png_uint_32 y = image->height; + const int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ? 3 : 1; + + if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0) + { + png_bytep row_end; + int aindex; + +# ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED + if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0) + { + aindex = -1; + ++input_row; /* To point to the first component */ + ++output_row; + } + + else +# endif + aindex = channels; + + /* Use row_end in place of a loop counter: */ + row_end = output_row + image->width * (channels+1); + + while (y-- > 0) + { + png_const_uint_16p in_ptr = input_row; + png_bytep out_ptr = output_row; + + while (out_ptr < row_end) + { + png_uint_16 alpha = in_ptr[aindex]; + png_byte alphabyte = (png_byte)PNG_DIV257(alpha); + png_uint_32 reciprocal = 0; + int c; + + /* Scale and write the alpha channel. */ + out_ptr[aindex] = alphabyte; + + if (alphabyte > 0 && alphabyte < 255) + reciprocal = UNP_RECIPROCAL(alpha); + + c = channels; + do /* always at least one channel */ + *out_ptr++ = png_unpremultiply(*in_ptr++, alpha, reciprocal); + while (--c > 0); + + /* Skip to next component (skip the intervening alpha channel) */ + ++in_ptr; + ++out_ptr; + } /* while out_ptr < row_end */ + + png_write_row(png_ptr, png_voidcast(png_const_bytep, + display->local_row)); + input_row += display->row_bytes/(sizeof (png_uint_16)); + } /* while y */ + } + + else + { + /* No alpha channel, so the row_end really is the end of the row and it + * is sufficient to loop over the components one by one. + */ + png_bytep row_end = output_row + image->width * channels; + + while (y-- > 0) + { + png_const_uint_16p in_ptr = input_row; + png_bytep out_ptr = output_row; + + while (out_ptr < row_end) + { + png_uint_32 component = *in_ptr++; + + component *= 255; + *out_ptr++ = (png_byte)PNG_sRGB_FROM_LINEAR(component); + } + + png_write_row(png_ptr, output_row); + input_row += display->row_bytes/(sizeof (png_uint_16)); + } + } + + return 1; +} + +static void +png_image_set_PLTE(png_image_write_control *display) +{ + const png_imagep image = display->image; + const void *cmap = display->colormap; + const int entries = image->colormap_entries > 256 ? 256 : + (int)image->colormap_entries; + + /* NOTE: the caller must check for cmap != NULL and entries != 0 */ + const png_uint_32 format = image->format; + const int channels = PNG_IMAGE_SAMPLE_CHANNELS(format); + +# if defined(PNG_FORMAT_BGR_SUPPORTED) &&\ + defined(PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED) + const int afirst = (format & PNG_FORMAT_FLAG_AFIRST) != 0 && + (format & PNG_FORMAT_FLAG_ALPHA) != 0; +# else +# define afirst 0 +# endif + +# ifdef PNG_FORMAT_BGR_SUPPORTED + const int bgr = (format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0; +# else +# define bgr 0 +# endif + + int i, num_trans; + png_color palette[256]; + png_byte tRNS[256]; + + memset(tRNS, 255, (sizeof tRNS)); + memset(palette, 0, (sizeof palette)); + + for (i=num_trans=0; i= 3) /* RGB */ + { + palette[i].blue = (png_byte)PNG_sRGB_FROM_LINEAR(255 * + entry[(2 ^ bgr)]); + palette[i].green = (png_byte)PNG_sRGB_FROM_LINEAR(255 * + entry[1]); + palette[i].red = (png_byte)PNG_sRGB_FROM_LINEAR(255 * + entry[bgr]); + } + + else /* Gray */ + palette[i].blue = palette[i].red = palette[i].green = + (png_byte)PNG_sRGB_FROM_LINEAR(255 * *entry); + } + + else /* alpha */ + { + png_uint_16 alpha = entry[afirst ? 0 : channels-1]; + png_byte alphabyte = (png_byte)PNG_DIV257(alpha); + png_uint_32 reciprocal = 0; + + /* Calculate a reciprocal, as in the png_write_image_8bit code above + * this is designed to produce a value scaled to 255*65535 when + * divided by 128 (i.e. asr 7). + */ + if (alphabyte > 0 && alphabyte < 255) + reciprocal = (((0xffff*0xff)<<7)+(alpha>>1))/alpha; + + tRNS[i] = alphabyte; + if (alphabyte < 255) + num_trans = i+1; + + if (channels >= 3) /* RGB */ + { + palette[i].blue = png_unpremultiply(entry[afirst + (2 ^ bgr)], + alpha, reciprocal); + palette[i].green = png_unpremultiply(entry[afirst + 1], alpha, + reciprocal); + palette[i].red = png_unpremultiply(entry[afirst + bgr], alpha, + reciprocal); + } + + else /* gray */ + palette[i].blue = palette[i].red = palette[i].green = + png_unpremultiply(entry[afirst], alpha, reciprocal); + } + } + + else /* Color-map has sRGB values */ + { + png_const_bytep entry = png_voidcast(png_const_bytep, cmap); + + entry += i * channels; + + switch (channels) + { + case 4: + tRNS[i] = entry[afirst ? 0 : 3]; + if (tRNS[i] < 255) + num_trans = i+1; + /* FALL THROUGH */ + case 3: + palette[i].blue = entry[afirst + (2 ^ bgr)]; + palette[i].green = entry[afirst + 1]; + palette[i].red = entry[afirst + bgr]; + break; + + case 2: + tRNS[i] = entry[1 ^ afirst]; + if (tRNS[i] < 255) + num_trans = i+1; + /* FALL THROUGH */ + case 1: + palette[i].blue = palette[i].red = palette[i].green = + entry[afirst]; + break; + + default: + break; + } + } + } + +# ifdef afirst +# undef afirst +# endif +# ifdef bgr +# undef bgr +# endif + + png_set_PLTE(image->opaque->png_ptr, image->opaque->info_ptr, palette, + entries); + + if (num_trans > 0) + png_set_tRNS(image->opaque->png_ptr, image->opaque->info_ptr, tRNS, + num_trans, NULL); + + image->colormap_entries = entries; +} + +static int +png_image_write_main(png_voidp argument) +{ + png_image_write_control *display = png_voidcast(png_image_write_control*, + argument); + png_imagep image = display->image; + png_structrp png_ptr = image->opaque->png_ptr; + png_inforp info_ptr = image->opaque->info_ptr; + png_uint_32 format = image->format; + + /* The following four ints are actually booleans */ + int colormap = (format & PNG_FORMAT_FLAG_COLORMAP); + int linear = !colormap && (format & PNG_FORMAT_FLAG_LINEAR); /* input */ + int alpha = !colormap && (format & PNG_FORMAT_FLAG_ALPHA); + int write_16bit = linear && !colormap && (display->convert_to_8bit == 0); + +# ifdef PNG_BENIGN_ERRORS_SUPPORTED + /* Make sure we error out on any bad situation */ + png_set_benign_errors(png_ptr, 0/*error*/); +# endif + + /* Default the 'row_stride' parameter if required. */ + if (display->row_stride == 0) + display->row_stride = PNG_IMAGE_ROW_STRIDE(*image); + + /* Set the required transforms then write the rows in the correct order. */ + if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0) + { + if (display->colormap != NULL && image->colormap_entries > 0) + { + png_uint_32 entries = image->colormap_entries; + + png_set_IHDR(png_ptr, info_ptr, image->width, image->height, + entries > 16 ? 8 : (entries > 4 ? 4 : (entries > 2 ? 2 : 1)), + PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE, + PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); + + png_image_set_PLTE(display); + } + + else + png_error(image->opaque->png_ptr, + "no color-map for color-mapped image"); + } + + else + png_set_IHDR(png_ptr, info_ptr, image->width, image->height, + write_16bit ? 16 : 8, + ((format & PNG_FORMAT_FLAG_COLOR) ? PNG_COLOR_MASK_COLOR : 0) + + ((format & PNG_FORMAT_FLAG_ALPHA) ? PNG_COLOR_MASK_ALPHA : 0), + PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); + + /* Counter-intuitively the data transformations must be called *after* + * png_write_info, not before as in the read code, but the 'set' functions + * must still be called before. Just set the color space information, never + * write an interlaced image. + */ + + if (write_16bit != 0) + { + /* The gamma here is 1.0 (linear) and the cHRM chunk matches sRGB. */ + png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_LINEAR); + + if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0) + png_set_cHRM_fixed(png_ptr, info_ptr, + /* color x y */ + /* white */ 31270, 32900, + /* red */ 64000, 33000, + /* green */ 30000, 60000, + /* blue */ 15000, 6000 + ); + } + + else if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0) + png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_PERCEPTUAL); + + /* Else writing an 8-bit file and the *colors* aren't sRGB, but the 8-bit + * space must still be gamma encoded. + */ + else + png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_sRGB_INVERSE); + + /* Write the file header. */ + png_write_info(png_ptr, info_ptr); + + /* Now set up the data transformations (*after* the header is written), + * remove the handled transformations from the 'format' flags for checking. + * + * First check for a little endian system if writing 16 bit files. + */ + if (write_16bit != 0) + { + PNG_CONST png_uint_16 le = 0x0001; + + if ((*(png_const_bytep) & le) != 0) + png_set_swap(png_ptr); + } + +# ifdef PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED + if ((format & PNG_FORMAT_FLAG_BGR) != 0) + { + if (colormap == 0 && (format & PNG_FORMAT_FLAG_COLOR) != 0) + png_set_bgr(png_ptr); + format &= ~PNG_FORMAT_FLAG_BGR; + } +# endif + +# ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED + if ((format & PNG_FORMAT_FLAG_AFIRST) != 0) + { + if (colormap == 0 && (format & PNG_FORMAT_FLAG_ALPHA) != 0) + png_set_swap_alpha(png_ptr); + format &= ~PNG_FORMAT_FLAG_AFIRST; + } +# endif + + /* If there are 16 or fewer color-map entries we wrote a lower bit depth + * above, but the application data is still byte packed. + */ + if (colormap != 0 && image->colormap_entries <= 16) + png_set_packing(png_ptr); + + /* That should have handled all (both) the transforms. */ + if ((format & ~(png_uint_32)(PNG_FORMAT_FLAG_COLOR | PNG_FORMAT_FLAG_LINEAR | + PNG_FORMAT_FLAG_ALPHA | PNG_FORMAT_FLAG_COLORMAP)) != 0) + png_error(png_ptr, "png_write_image: unsupported transformation"); + + { + png_const_bytep row = png_voidcast(png_const_bytep, display->buffer); + ptrdiff_t row_bytes = display->row_stride; + + if (linear != 0) + row_bytes *= (sizeof (png_uint_16)); + + if (row_bytes < 0) + row += (image->height-1) * (-row_bytes); + + display->first_row = row; + display->row_bytes = row_bytes; + } + + /* Apply 'fast' options if the flag is set. */ + if ((image->flags & PNG_IMAGE_FLAG_FAST) != 0) + { + png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_NO_FILTERS); + /* NOTE: determined by experiment using pngstest, this reflects some + * balance between the time to write the image once and the time to read + * it about 50 times. The speed-up in pngstest was about 10-20% of the + * total (user) time on a heavily loaded system. + */ + png_set_compression_level(png_ptr, 3); + } + + /* Check for the cases that currently require a pre-transform on the row + * before it is written. This only applies when the input is 16-bit and + * either there is an alpha channel or it is converted to 8-bit. + */ + if ((linear != 0 && alpha != 0 ) || + (colormap == 0 && display->convert_to_8bit != 0)) + { + png_bytep row = png_voidcast(png_bytep, png_malloc(png_ptr, + png_get_rowbytes(png_ptr, info_ptr))); + int result; + + display->local_row = row; + if (write_16bit != 0) + result = png_safe_execute(image, png_write_image_16bit, display); + else + result = png_safe_execute(image, png_write_image_8bit, display); + display->local_row = NULL; + + png_free(png_ptr, row); + + /* Skip the 'write_end' on error: */ + if (result == 0) + return 0; + } + + /* Otherwise this is the case where the input is in a format currently + * supported by the rest of the libpng write code; call it directly. + */ + else + { + png_const_bytep row = png_voidcast(png_const_bytep, display->first_row); + ptrdiff_t row_bytes = display->row_bytes; + png_uint_32 y = image->height; + + while (y-- > 0) + { + png_write_row(png_ptr, row); + row += row_bytes; + } + } + + png_write_end(png_ptr, info_ptr); + return 1; +} + +int PNGAPI +png_image_write_to_stdio(png_imagep image, FILE *file, int convert_to_8bit, + const void *buffer, png_int_32 row_stride, const void *colormap) +{ + /* Write the image to the given (FILE*). */ + if (image != NULL && image->version == PNG_IMAGE_VERSION) + { + if (file != NULL) + { + if (png_image_write_init(image) != 0) + { + png_image_write_control display; + int result; + + /* This is slightly evil, but png_init_io doesn't do anything other + * than this and we haven't changed the standard IO functions so + * this saves a 'safe' function. + */ + image->opaque->png_ptr->io_ptr = file; + + memset(&display, 0, (sizeof display)); + display.image = image; + display.buffer = buffer; + display.row_stride = row_stride; + display.colormap = colormap; + display.convert_to_8bit = convert_to_8bit; + + result = png_safe_execute(image, png_image_write_main, &display); + png_image_free(image); + return result; + } + + else + return 0; + } + + else + return png_image_error(image, + "png_image_write_to_stdio: invalid argument"); + } + + else if (image != NULL) + return png_image_error(image, + "png_image_write_to_stdio: incorrect PNG_IMAGE_VERSION"); + + else + return 0; +} + +int PNGAPI +png_image_write_to_file(png_imagep image, const char *file_name, + int convert_to_8bit, const void *buffer, png_int_32 row_stride, + const void *colormap) +{ + /* Write the image to the named file. */ + if (image != NULL && image->version == PNG_IMAGE_VERSION) + { + if (file_name != NULL) + { + FILE *fp = fopen(file_name, "wb"); + + if (fp != NULL) + { + if (png_image_write_to_stdio(image, fp, convert_to_8bit, buffer, + row_stride, colormap) != 0) + { + int error; /* from fflush/fclose */ + + /* Make sure the file is flushed correctly. */ + if (fflush(fp) == 0 && ferror(fp) == 0) + { + if (fclose(fp) == 0) + return 1; + + error = errno; /* from fclose */ + } + + else + { + error = errno; /* from fflush or ferror */ + (void)fclose(fp); + } + + (void)remove(file_name); + /* The image has already been cleaned up; this is just used to + * set the error (because the original write succeeded). + */ + return png_image_error(image, strerror(error)); + } + + else + { + /* Clean up: just the opened file. */ + (void)fclose(fp); + (void)remove(file_name); + return 0; + } + } + + else + return png_image_error(image, strerror(errno)); + } + + else + return png_image_error(image, + "png_image_write_to_file: invalid argument"); + } + + else if (image != NULL) + return png_image_error(image, + "png_image_write_to_file: incorrect PNG_IMAGE_VERSION"); + + else + return 0; +} +#endif /* STDIO */ +#endif /* SIMPLIFIED_WRITE */ +#endif /* WRITE */ diff --git a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwtran.c b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwtran.c index 579057dcefd..ef015aeb7b9 100644 --- a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwtran.c +++ b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwtran.c @@ -29,8 +29,8 @@ * However, the following notice accompanied the original version of this * file and, per its terms, should not be removed: * - * Last changed in libpng 1.5.4 [July 7, 2011] - * Copyright (c) 1998-2011 Glenn Randers-Pehrson + * Last changed in libpng 1.6.15 [November 20, 2014] + * Copyright (c) 1998-2014 Glenn Randers-Pehrson * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) * @@ -42,90 +42,14 @@ #include "pngpriv.h" #ifdef PNG_WRITE_SUPPORTED - #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED -/* Transform the data according to the user's wishes. The order of - * transformations is significant. - */ -void /* PRIVATE */ -png_do_write_transformations(png_structp png_ptr) -{ - png_debug(1, "in png_do_write_transformations"); - - if (png_ptr == NULL) - return; - -#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED - if (png_ptr->transformations & PNG_USER_TRANSFORM) - if (png_ptr->write_user_transform_fn != NULL) - (*(png_ptr->write_user_transform_fn)) /* User write transform - function */ - (png_ptr, /* png_ptr */ - &(png_ptr->row_info), /* row_info: */ - /* png_uint_32 width; width of row */ - /* png_size_t rowbytes; number of bytes in row */ - /* png_byte color_type; color type of pixels */ - /* png_byte bit_depth; bit depth of samples */ - /* png_byte channels; number of channels (1-4) */ - /* png_byte pixel_depth; bits per pixel (depth*channels) */ - png_ptr->row_buf + 1); /* start of pixel data for row */ -#endif - -#ifdef PNG_WRITE_FILLER_SUPPORTED - if (png_ptr->transformations & PNG_FILLER) - png_do_strip_channel(&(png_ptr->row_info), png_ptr->row_buf + 1, - !(png_ptr->flags & PNG_FLAG_FILLER_AFTER)); -#endif - -#ifdef PNG_WRITE_PACKSWAP_SUPPORTED - if (png_ptr->transformations & PNG_PACKSWAP) - png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_WRITE_PACK_SUPPORTED - if (png_ptr->transformations & PNG_PACK) - png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1, - (png_uint_32)png_ptr->bit_depth); -#endif - -#ifdef PNG_WRITE_SWAP_SUPPORTED - if (png_ptr->transformations & PNG_SWAP_BYTES) - png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_WRITE_SHIFT_SUPPORTED - if (png_ptr->transformations & PNG_SHIFT) - png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1, - &(png_ptr->shift)); -#endif - -#ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED - if (png_ptr->transformations & PNG_SWAP_ALPHA) - png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED - if (png_ptr->transformations & PNG_INVERT_ALPHA) - png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_WRITE_BGR_SUPPORTED - if (png_ptr->transformations & PNG_BGR) - png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif - -#ifdef PNG_WRITE_INVERT_SUPPORTED - if (png_ptr->transformations & PNG_INVERT_MONO) - png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1); -#endif -} #ifdef PNG_WRITE_PACK_SUPPORTED /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The * row_info bit depth should be 8 (one pixel per byte). The channels * should be 1 (this only happens on grayscale and paletted images). */ -void /* PRIVATE */ +static void png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth) { png_debug(1, "in png_do_pack"); @@ -270,7 +194,7 @@ png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth) * would pass 3 as bit_depth, and this routine would translate the * data to 0 to 15. */ -void /* PRIVATE */ +static void png_do_shift(png_row_infop row_info, png_bytep row, png_const_color_8p bit_depth) { @@ -281,7 +205,7 @@ png_do_shift(png_row_infop row_info, png_bytep row, int shift_start[4], shift_dec[4]; int channels = 0; - if (row_info->color_type & PNG_COLOR_MASK_COLOR) + if ((row_info->color_type & PNG_COLOR_MASK_COLOR) != 0) { shift_start[channels] = row_info->bit_depth - bit_depth->red; shift_dec[channels] = bit_depth->red; @@ -303,7 +227,7 @@ png_do_shift(png_row_infop row_info, png_bytep row, channels++; } - if (row_info->color_type & PNG_COLOR_MASK_ALPHA) + if ((row_info->color_type & PNG_COLOR_MASK_ALPHA) != 0) { shift_start[channels] = row_info->bit_depth - bit_depth->alpha; shift_dec[channels] = bit_depth->alpha; @@ -315,7 +239,7 @@ png_do_shift(png_row_infop row_info, png_bytep row, { png_bytep bp = row; png_size_t i; - png_byte mask; + unsigned int mask; png_size_t row_bytes = row_info->rowbytes; if (bit_depth->gray == 1 && row_info->bit_depth == 2) @@ -329,20 +253,22 @@ png_do_shift(png_row_infop row_info, png_bytep row, for (i = 0; i < row_bytes; i++, bp++) { - png_uint_16 v; int j; + unsigned int v, out; v = *bp; - *bp = 0; + out = 0; for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0]) { if (j > 0) - *bp |= (png_byte)((v << j) & 0xff); + out |= v << j; else - *bp |= (png_byte)((v >> (-j)) & mask); + out |= (v >> (-j)) & mask; } + + *bp = (png_byte)(out & 0xff); } } @@ -355,21 +281,23 @@ png_do_shift(png_row_infop row_info, png_bytep row, for (i = 0; i < istop; i++, bp++) { - png_uint_16 v; + const unsigned int c = i%channels; int j; - int c = (int)(i%channels); + unsigned int v, out; v = *bp; - *bp = 0; + out = 0; for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c]) { if (j > 0) - *bp |= (png_byte)((v << j) & 0xff); + out |= v << j; else - *bp |= (png_byte)((v >> (-j)) & 0xff); + out |= v >> (-j); } + + *bp = (png_byte)(out & 0xff); } } @@ -381,22 +309,22 @@ png_do_shift(png_row_infop row_info, png_bytep row, for (bp = row, i = 0; i < istop; i++) { - int c = (int)(i%channels); - png_uint_16 value, v; + const unsigned int c = i%channels; int j; + unsigned int value, v; - v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1)); + v = png_get_uint_16(bp); value = 0; for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c]) { if (j > 0) - value |= (png_uint_16)((v << j) & (png_uint_16)0xffff); + value |= v << j; else - value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff); + value |= v >> (-j); } - *bp++ = (png_byte)(value >> 8); + *bp++ = (png_byte)((value >> 8) & 0xff); *bp++ = (png_byte)(value & 0xff); } } @@ -405,7 +333,7 @@ png_do_shift(png_row_infop row_info, png_bytep row, #endif #ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED -void /* PRIVATE */ +static void png_do_write_swap_alpha(png_row_infop row_info, png_bytep row) { png_debug(1, "in png_do_write_swap_alpha"); @@ -453,7 +381,7 @@ png_do_write_swap_alpha(png_row_infop row_info, png_bytep row) *(dp++) = save[1]; } } -#endif /* PNG_WRITE_16BIT_SUPPORTED */ +#endif /* WRITE_16BIT */ } else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) @@ -492,14 +420,14 @@ png_do_write_swap_alpha(png_row_infop row_info, png_bytep row) *(dp++) = save[1]; } } -#endif /* PNG_WRITE_16BIT_SUPPORTED */ +#endif /* WRITE_16BIT */ } } } #endif #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED -void /* PRIVATE */ +static void png_do_write_invert_alpha(png_row_infop row_info, png_bytep row) { png_debug(1, "in png_do_write_invert_alpha"); @@ -549,7 +477,7 @@ png_do_write_invert_alpha(png_row_infop row_info, png_bytep row) *(dp++) = (png_byte)(255 - *(sp++)); } } -#endif /* PNG_WRITE_16BIT_SUPPORTED */ +#endif /* WRITE_16BIT */ } else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) @@ -587,75 +515,88 @@ png_do_write_invert_alpha(png_row_infop row_info, png_bytep row) *(dp++) = (png_byte)(255 - *(sp++)); } } -#endif /* PNG_WRITE_16BIT_SUPPORTED */ +#endif /* WRITE_16BIT */ } } } #endif -#endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */ -#ifdef PNG_MNG_FEATURES_SUPPORTED -/* Undoes intrapixel differencing */ +/* Transform the data according to the user's wishes. The order of + * transformations is significant. + */ void /* PRIVATE */ -png_do_write_intrapixel(png_row_infop row_info, png_bytep row) +png_do_write_transformations(png_structrp png_ptr, png_row_infop row_info) { - png_debug(1, "in png_do_write_intrapixel"); + png_debug(1, "in png_do_write_transformations"); - if ((row_info->color_type & PNG_COLOR_MASK_COLOR)) - { - int bytes_per_pixel; - png_uint_32 row_width = row_info->width; - if (row_info->bit_depth == 8) - { - png_bytep rp; - png_uint_32 i; + if (png_ptr == NULL) + return; - if (row_info->color_type == PNG_COLOR_TYPE_RGB) - bytes_per_pixel = 3; +#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED + if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0) + if (png_ptr->write_user_transform_fn != NULL) + (*(png_ptr->write_user_transform_fn)) /* User write transform + function */ + (png_ptr, /* png_ptr */ + row_info, /* row_info: */ + /* png_uint_32 width; width of row */ + /* png_size_t rowbytes; number of bytes in row */ + /* png_byte color_type; color type of pixels */ + /* png_byte bit_depth; bit depth of samples */ + /* png_byte channels; number of channels (1-4) */ + /* png_byte pixel_depth; bits per pixel (depth*channels) */ + png_ptr->row_buf + 1); /* start of pixel data for row */ +#endif - else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) - bytes_per_pixel = 4; +#ifdef PNG_WRITE_FILLER_SUPPORTED + if ((png_ptr->transformations & PNG_FILLER) != 0) + png_do_strip_channel(row_info, png_ptr->row_buf + 1, + !(png_ptr->flags & PNG_FLAG_FILLER_AFTER)); +#endif - else - return; +#ifdef PNG_WRITE_PACKSWAP_SUPPORTED + if ((png_ptr->transformations & PNG_PACKSWAP) != 0) + png_do_packswap(row_info, png_ptr->row_buf + 1); +#endif - for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel) - { - *(rp) = (png_byte)((*rp - *(rp + 1)) & 0xff); - *(rp + 2) = (png_byte)((*(rp + 2) - *(rp + 1)) & 0xff); - } - } +#ifdef PNG_WRITE_PACK_SUPPORTED + if ((png_ptr->transformations & PNG_PACK) != 0) + png_do_pack(row_info, png_ptr->row_buf + 1, + (png_uint_32)png_ptr->bit_depth); +#endif -#ifdef PNG_WRITE_16BIT_SUPPORTED - else if (row_info->bit_depth == 16) - { - png_bytep rp; - png_uint_32 i; +#ifdef PNG_WRITE_SWAP_SUPPORTED +# ifdef PNG_16BIT_SUPPORTED + if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0) + png_do_swap(row_info, png_ptr->row_buf + 1); +# endif +#endif - if (row_info->color_type == PNG_COLOR_TYPE_RGB) - bytes_per_pixel = 6; +#ifdef PNG_WRITE_SHIFT_SUPPORTED + if ((png_ptr->transformations & PNG_SHIFT) != 0) + png_do_shift(row_info, png_ptr->row_buf + 1, + &(png_ptr->shift)); +#endif - else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) - bytes_per_pixel = 8; +#ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED + if ((png_ptr->transformations & PNG_SWAP_ALPHA) != 0) + png_do_write_swap_alpha(row_info, png_ptr->row_buf + 1); +#endif - else - return; +#ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED + if ((png_ptr->transformations & PNG_INVERT_ALPHA) != 0) + png_do_write_invert_alpha(row_info, png_ptr->row_buf + 1); +#endif - for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel) - { - png_uint_32 s0 = (*(rp ) << 8) | *(rp + 1); - png_uint_32 s1 = (*(rp + 2) << 8) | *(rp + 3); - png_uint_32 s2 = (*(rp + 4) << 8) | *(rp + 5); - png_uint_32 red = (png_uint_32)((s0 - s1) & 0xffffL); - png_uint_32 blue = (png_uint_32)((s2 - s1) & 0xffffL); - *(rp ) = (png_byte)((red >> 8) & 0xff); - *(rp + 1) = (png_byte)(red & 0xff); - *(rp + 4) = (png_byte)((blue >> 8) & 0xff); - *(rp + 5) = (png_byte)(blue & 0xff); - } - } -#endif /* PNG_WRITE_16BIT_SUPPORTED */ - } +#ifdef PNG_WRITE_BGR_SUPPORTED + if ((png_ptr->transformations & PNG_BGR) != 0) + png_do_bgr(row_info, png_ptr->row_buf + 1); +#endif + +#ifdef PNG_WRITE_INVERT_SUPPORTED + if ((png_ptr->transformations & PNG_INVERT_MONO) != 0) + png_do_invert(row_info, png_ptr->row_buf + 1); +#endif } -#endif /* PNG_MNG_FEATURES_SUPPORTED */ -#endif /* PNG_WRITE_SUPPORTED */ +#endif /* WRITE_TRANSFORMS */ +#endif /* WRITE */ diff --git a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwutil.c b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwutil.c index 91634671e7c..66a8812d790 100644 --- a/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwutil.c +++ b/jdk/src/java.desktop/share/native/libsplashscreen/libpng/pngwutil.c @@ -29,8 +29,8 @@ * However, the following notice accompanied the original version of this * file and, per its terms, should not be removed: * - * Last changed in libpng 1.5.4 [July 7, 2011] - * Copyright (c) 1998-2011 Glenn Randers-Pehrson + * Last changed in libpng 1.6.15 [November 20, 2014] + * Copyright (c) 1998-2014 Glenn Randers-Pehrson * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) * @@ -57,23 +57,6 @@ png_save_uint_32(png_bytep buf, png_uint_32 i) buf[3] = (png_byte)(i & 0xff); } -#ifdef PNG_SAVE_INT_32_SUPPORTED -/* The png_save_int_32 function assumes integers are stored in two's - * complement format. If this isn't the case, then this routine needs to - * be modified to write data in two's complement format. Note that, - * the following works correctly even if png_int_32 has more than 32 bits - * (compare the more complex code required on read for sign extention.) - */ -void PNGAPI -png_save_int_32(png_bytep buf, png_int_32 i) -{ - buf[0] = (png_byte)((i >> 24) & 0xff); - buf[1] = (png_byte)((i >> 16) & 0xff); - buf[2] = (png_byte)((i >> 8) & 0xff); - buf[3] = (png_byte)(i & 0xff); -} -#endif - /* Place a 16-bit number into a buffer in PNG byte order. * The parameter is declared unsigned int, not png_uint_16, * just to avoid potential problems on pre-ANSI C compilers. @@ -93,7 +76,7 @@ png_save_uint_16(png_bytep buf, unsigned int i) * bytes have already been written. */ void PNGAPI -png_write_sig(png_structp png_ptr) +png_write_sig(png_structrp png_ptr) { png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10}; @@ -110,39 +93,20 @@ png_write_sig(png_structp png_ptr) png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE; } -/* Write a PNG chunk all at once. The type is an array of ASCII characters - * representing the chunk name. The array must be at least 4 bytes in - * length, and does not need to be null terminated. To be safe, pass the - * pre-defined chunk names here, and if you need a new one, define it - * where the others are defined. The length is the length of the data. - * All the data must be present. If that is not possible, use the - * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end() - * functions instead. - */ -void PNGAPI -png_write_chunk(png_structp png_ptr, png_const_bytep chunk_name, - png_const_bytep data, png_size_t length) -{ - if (png_ptr == NULL) - return; - - png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length); - png_write_chunk_data(png_ptr, data, (png_size_t)length); - png_write_chunk_end(png_ptr); -} - /* Write the start of a PNG chunk. The type is the chunk type. * The total_length is the sum of the lengths of all the data you will be * passing in png_write_chunk_data(). */ -void PNGAPI -png_write_chunk_start(png_structp png_ptr, png_const_bytep chunk_name, +static void +png_write_chunk_header(png_structrp png_ptr, png_uint_32 chunk_name, png_uint_32 length) { png_byte buf[8]; - png_debug2(0, "Writing %s chunk, length = %lu", chunk_name, - (unsigned long)length); +#if defined(PNG_DEBUG) && (PNG_DEBUG > 0) + PNG_CSTRING_FROM_CHUNK(buf, chunk_name); + png_debug2(0, "Writing %s chunk, length = %lu", buf, (unsigned long)length); +#endif if (png_ptr == NULL) return; @@ -156,16 +120,16 @@ png_write_chunk_start(png_structp png_ptr, png_const_bytep chunk_name, /* Write the length and the chunk name */ png_save_uint_32(buf, length); - png_memcpy(buf + 4, chunk_name, 4); - png_write_data(png_ptr, buf, (png_size_t)8); + png_save_uint_32(buf + 4, chunk_name); + png_write_data(png_ptr, buf, 8); /* Put the chunk name into png_ptr->chunk_name */ - png_memcpy(png_ptr->chunk_name, chunk_name, 4); + png_ptr->chunk_name = chunk_name; /* Reset the crc and run it over the chunk name */ png_reset_crc(png_ptr); - png_calculate_crc(png_ptr, chunk_name, 4); + png_calculate_crc(png_ptr, buf + 4, 4); #ifdef PNG_IO_STATE_SUPPORTED /* Inform the I/O callback that chunk data will (possibly) be written. @@ -175,13 +139,20 @@ png_write_chunk_start(png_structp png_ptr, png_const_bytep chunk_name, #endif } -/* Write the data of a PNG chunk started with png_write_chunk_start(). +void PNGAPI +png_write_chunk_start(png_structrp png_ptr, png_const_bytep chunk_string, + png_uint_32 length) +{ + png_write_chunk_header(png_ptr, PNG_CHUNK_FROM_STRING(chunk_string), length); +} + +/* Write the data of a PNG chunk started with png_write_chunk_header(). * Note that multiple calls to this function are allowed, and that the * sum of the lengths from these calls *must* add up to the total_length - * given to png_write_chunk_start(). + * given to png_write_chunk_header(). */ void PNGAPI -png_write_chunk_data(png_structp png_ptr, png_const_bytep data, +png_write_chunk_data(png_structrp png_ptr, png_const_bytep data, png_size_t length) { /* Write the data, and run the CRC over it */ @@ -193,15 +164,15 @@ png_write_chunk_data(png_structp png_ptr, png_const_bytep data, png_write_data(png_ptr, data, length); /* Update the CRC after writing the data, - * in case that the user I/O routine alters it. + * in case the user I/O routine alters it. */ png_calculate_crc(png_ptr, data, length); } } -/* Finish a chunk started with png_write_chunk_start(). */ +/* Finish a chunk started with png_write_chunk_header(). */ void PNGAPI -png_write_chunk_end(png_structp png_ptr) +png_write_chunk_end(png_structrp png_ptr) { png_byte buf[4]; @@ -220,468 +191,601 @@ png_write_chunk_end(png_structp png_ptr) png_write_data(png_ptr, buf, (png_size_t)4); } -/* Initialize the compressor for the appropriate type of compression. */ -static void -png_zlib_claim(png_structp png_ptr, png_uint_32 state) -{ - if (!(png_ptr->zlib_state & PNG_ZLIB_IN_USE)) - { - /* If already initialized for 'state' do not re-init. */ - if (png_ptr->zlib_state != state) - { - int ret = Z_OK; - png_const_charp who = "-"; - - /* If actually initialized for another state do a deflateEnd. */ - if (png_ptr->zlib_state != PNG_ZLIB_UNINITIALIZED) - { - ret = deflateEnd(&png_ptr->zstream); - who = "end"; - png_ptr->zlib_state = PNG_ZLIB_UNINITIALIZED; - } - - /* zlib itself detects an incomplete state on deflateEnd */ - if (ret == Z_OK) switch (state) - { -# ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED - case PNG_ZLIB_FOR_TEXT: - ret = deflateInit2(&png_ptr->zstream, - png_ptr->zlib_text_level, png_ptr->zlib_text_method, - png_ptr->zlib_text_window_bits, - png_ptr->zlib_text_mem_level, png_ptr->zlib_text_strategy); - who = "text"; - break; -# endif - - case PNG_ZLIB_FOR_IDAT: - ret = deflateInit2(&png_ptr->zstream, png_ptr->zlib_level, - png_ptr->zlib_method, png_ptr->zlib_window_bits, - png_ptr->zlib_mem_level, png_ptr->zlib_strategy); - who = "IDAT"; - break; - - default: - png_error(png_ptr, "invalid zlib state"); - } - - if (ret == Z_OK) - png_ptr->zlib_state = state; - - else /* an error in deflateEnd or deflateInit2 */ - { - size_t pos = 0; - char msg[64]; - - pos = png_safecat(msg, sizeof msg, pos, - "zlib failed to initialize compressor ("); - pos = png_safecat(msg, sizeof msg, pos, who); - - switch (ret) - { - case Z_VERSION_ERROR: - pos = png_safecat(msg, sizeof msg, pos, ") version error"); - break; - - case Z_STREAM_ERROR: - pos = png_safecat(msg, sizeof msg, pos, ") stream error"); - break; - - case Z_MEM_ERROR: - pos = png_safecat(msg, sizeof msg, pos, ") memory error"); - break; - - default: - pos = png_safecat(msg, sizeof msg, pos, ") unknown error"); - break; - } - - png_error(png_ptr, msg); - } - } - - /* Here on success, claim the zstream: */ - png_ptr->zlib_state |= PNG_ZLIB_IN_USE; - } - - else - png_error(png_ptr, "zstream already in use (internal error)"); -} - -/* The opposite: release the stream. It is also reset, this API will warn on - * error but will not fail. +/* Write a PNG chunk all at once. The type is an array of ASCII characters + * representing the chunk name. The array must be at least 4 bytes in + * length, and does not need to be null terminated. To be safe, pass the + * pre-defined chunk names here, and if you need a new one, define it + * where the others are defined. The length is the length of the data. + * All the data must be present. If that is not possible, use the + * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end() + * functions instead. */ static void -png_zlib_release(png_structp png_ptr) +png_write_complete_chunk(png_structrp png_ptr, png_uint_32 chunk_name, + png_const_bytep data, png_size_t length) { - if (png_ptr->zlib_state & PNG_ZLIB_IN_USE) + if (png_ptr == NULL) + return; + + /* On 64 bit architectures 'length' may not fit in a png_uint_32. */ + if (length > PNG_UINT_31_MAX) + png_error(png_ptr, "length exceeds PNG maximum"); + + png_write_chunk_header(png_ptr, chunk_name, (png_uint_32)length); + png_write_chunk_data(png_ptr, data, length); + png_write_chunk_end(png_ptr); +} + +/* This is the API that calls the internal function above. */ +void PNGAPI +png_write_chunk(png_structrp png_ptr, png_const_bytep chunk_string, + png_const_bytep data, png_size_t length) +{ + png_write_complete_chunk(png_ptr, PNG_CHUNK_FROM_STRING(chunk_string), data, + length); +} + +/* This is used below to find the size of an image to pass to png_deflate_claim, + * so it only needs to be accurate if the size is less than 16384 bytes (the + * point at which a lower LZ window size can be used.) + */ +static png_alloc_size_t +png_image_size(png_structrp png_ptr) +{ + /* Only return sizes up to the maximum of a png_uint_32; do this by limiting + * the width and height used to 15 bits. + */ + png_uint_32 h = png_ptr->height; + + if (png_ptr->rowbytes < 32768 && h < 32768) { - int ret = deflateReset(&png_ptr->zstream); - - png_ptr->zlib_state &= ~PNG_ZLIB_IN_USE; - - if (ret != Z_OK) + if (png_ptr->interlaced != 0) { - png_const_charp err; - PNG_WARNING_PARAMETERS(p) + /* Interlacing makes the image larger because of the replication of + * both the filter byte and the padding to a byte boundary. + */ + png_uint_32 w = png_ptr->width; + unsigned int pd = png_ptr->pixel_depth; + png_alloc_size_t cb_base; + int pass; - switch (ret) + for (cb_base=0, pass=0; pass<=6; ++pass) { - case Z_VERSION_ERROR: - err = "version"; - break; + png_uint_32 pw = PNG_PASS_COLS(w, pass); - case Z_STREAM_ERROR: - err = "stream"; - break; - - case Z_MEM_ERROR: - err = "memory"; - break; - - default: - err = "unknown"; - break; + if (pw > 0) + cb_base += (PNG_ROWBYTES(pd, pw)+1) * PNG_PASS_ROWS(h, pass); } - png_warning_parameter_signed(p, 1, PNG_NUMBER_FORMAT_d, ret); - png_warning_parameter(p, 2, err); - - if (png_ptr->zstream.msg) - err = png_ptr->zstream.msg; - else - err = "[no zlib message]"; - - png_warning_parameter(p, 3, err); - - png_formatted_warning(png_ptr, p, - "zlib failed to reset compressor: @1(@2): @3"); + return cb_base; } + + else + return (png_ptr->rowbytes+1) * h; } else - png_warning(png_ptr, "zstream not in use (internal error)"); + return 0xffffffffU; +} + +#ifdef PNG_WRITE_OPTIMIZE_CMF_SUPPORTED + /* This is the code to hack the first two bytes of the deflate stream (the + * deflate header) to correct the windowBits value to match the actual data + * size. Note that the second argument is the *uncompressed* size but the + * first argument is the *compressed* data (and it must be deflate + * compressed.) + */ +static void +optimize_cmf(png_bytep data, png_alloc_size_t data_size) +{ + /* Optimize the CMF field in the zlib stream. The resultant zlib stream is + * still compliant to the stream specification. + */ + if (data_size <= 16384) /* else windowBits must be 15 */ + { + unsigned int z_cmf = data[0]; /* zlib compression method and flags */ + + if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70) + { + unsigned int z_cinfo; + unsigned int half_z_window_size; + + z_cinfo = z_cmf >> 4; + half_z_window_size = 1U << (z_cinfo + 7); + + if (data_size <= half_z_window_size) /* else no change */ + { + unsigned int tmp; + + do + { + half_z_window_size >>= 1; + --z_cinfo; + } + while (z_cinfo > 0 && data_size <= half_z_window_size); + + z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4); + + data[0] = (png_byte)z_cmf; + tmp = data[1] & 0xe0; + tmp += 0x1f - ((z_cmf << 8) + tmp) % 0x1f; + data[1] = (png_byte)tmp; + } + } + } +} +#endif /* WRITE_OPTIMIZE_CMF */ + +/* Initialize the compressor for the appropriate type of compression. */ +static int +png_deflate_claim(png_structrp png_ptr, png_uint_32 owner, + png_alloc_size_t data_size) +{ + if (png_ptr->zowner != 0) + { +#if defined(PNG_WARNINGS_SUPPORTED) || defined(PNG_ERROR_TEXT_SUPPORTED) + char msg[64]; + + PNG_STRING_FROM_CHUNK(msg, owner); + msg[4] = ':'; + msg[5] = ' '; + PNG_STRING_FROM_CHUNK(msg+6, png_ptr->zowner); + /* So the message that results is " using zstream"; this is an + * internal error, but is very useful for debugging. i18n requirements + * are minimal. + */ + (void)png_safecat(msg, (sizeof msg), 10, " using zstream"); +#endif +#if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC + png_warning(png_ptr, msg); + + /* Attempt sane error recovery */ + if (png_ptr->zowner == png_IDAT) /* don't steal from IDAT */ + { + png_ptr->zstream.msg = PNGZ_MSG_CAST("in use by IDAT"); + return Z_STREAM_ERROR; + } + + png_ptr->zowner = 0; +#else + png_error(png_ptr, msg); +#endif + } + + { + int level = png_ptr->zlib_level; + int method = png_ptr->zlib_method; + int windowBits = png_ptr->zlib_window_bits; + int memLevel = png_ptr->zlib_mem_level; + int strategy; /* set below */ + int ret; /* zlib return code */ + + if (owner == png_IDAT) + { + if ((png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY) != 0) + strategy = png_ptr->zlib_strategy; + + else if (png_ptr->do_filter != PNG_FILTER_NONE) + strategy = PNG_Z_DEFAULT_STRATEGY; + + else + strategy = PNG_Z_DEFAULT_NOFILTER_STRATEGY; + } + + else + { +#ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED + level = png_ptr->zlib_text_level; + method = png_ptr->zlib_text_method; + windowBits = png_ptr->zlib_text_window_bits; + memLevel = png_ptr->zlib_text_mem_level; + strategy = png_ptr->zlib_text_strategy; +#else + /* If customization is not supported the values all come from the + * IDAT values except for the strategy, which is fixed to the + * default. (This is the pre-1.6.0 behavior too, although it was + * implemented in a very different way.) + */ + strategy = Z_DEFAULT_STRATEGY; +#endif + } + + /* Adjust 'windowBits' down if larger than 'data_size'; to stop this + * happening just pass 32768 as the data_size parameter. Notice that zlib + * requires an extra 262 bytes in the window in addition to the data to be + * able to see the whole of the data, so if data_size+262 takes us to the + * next windowBits size we need to fix up the value later. (Because even + * though deflate needs the extra window, inflate does not!) + */ + if (data_size <= 16384) + { + /* IMPLEMENTATION NOTE: this 'half_window_size' stuff is only here to + * work round a Microsoft Visual C misbehavior which, contrary to C-90, + * widens the result of the following shift to 64-bits if (and, + * apparently, only if) it is used in a test. + */ + unsigned int half_window_size = 1U << (windowBits-1); + + while (data_size + 262 <= half_window_size) + { + half_window_size >>= 1; + --windowBits; + } + } + + /* Check against the previous initialized values, if any. */ + if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0 && + (png_ptr->zlib_set_level != level || + png_ptr->zlib_set_method != method || + png_ptr->zlib_set_window_bits != windowBits || + png_ptr->zlib_set_mem_level != memLevel || + png_ptr->zlib_set_strategy != strategy)) + { + if (deflateEnd(&png_ptr->zstream) != Z_OK) + png_warning(png_ptr, "deflateEnd failed (ignored)"); + + png_ptr->flags &= ~PNG_FLAG_ZSTREAM_INITIALIZED; + } + + /* For safety clear out the input and output pointers (currently zlib + * doesn't use them on Init, but it might in the future). + */ + png_ptr->zstream.next_in = NULL; + png_ptr->zstream.avail_in = 0; + png_ptr->zstream.next_out = NULL; + png_ptr->zstream.avail_out = 0; + + /* Now initialize if required, setting the new parameters, otherwise just + * to a simple reset to the previous parameters. + */ + if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0) + ret = deflateReset(&png_ptr->zstream); + + else + { + ret = deflateInit2(&png_ptr->zstream, level, method, windowBits, + memLevel, strategy); + + if (ret == Z_OK) + png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED; + } + + /* The return code is from either deflateReset or deflateInit2; they have + * pretty much the same set of error codes. + */ + if (ret == Z_OK) + png_ptr->zowner = owner; + + else + png_zstream_error(png_ptr, ret); + + return ret; + } +} + +/* Clean up (or trim) a linked list of compression buffers. */ +void /* PRIVATE */ +png_free_buffer_list(png_structrp png_ptr, png_compression_bufferp *listp) +{ + png_compression_bufferp list = *listp; + + if (list != NULL) + { + *listp = NULL; + + do + { + png_compression_bufferp next = list->next; + + png_free(png_ptr, list); + list = next; + } + while (list != NULL); + } } #ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED /* This pair of functions encapsulates the operation of (a) compressing a * text string, and (b) issuing it later as a series of chunk data writes. * The compression_state structure is shared context for these functions - * set up by the caller in order to make the whole mess thread-safe. + * set up by the caller to allow access to the relevant local variables. + * + * compression_buffer (new in 1.6.0) is just a linked list of zbuffer_size + * temporary buffers. From 1.6.0 it is retained in png_struct so that it will + * be correctly freed in the event of a write error (previous implementations + * just leaked memory.) */ - typedef struct { - png_const_bytep input; /* The uncompressed input data */ - png_size_t input_len; /* Its length */ - int num_output_ptr; /* Number of output pointers used */ - int max_output_ptr; /* Size of output_ptr */ - png_bytep *output_ptr; /* Array of pointers to output */ + png_const_bytep input; /* The uncompressed input data */ + png_alloc_size_t input_len; /* Its length */ + png_uint_32 output_len; /* Final compressed length */ + png_byte output[1024]; /* First block of output */ } compression_state; -/* Compress given text into storage in the png_ptr structure */ -static int /* PRIVATE */ -png_text_compress(png_structp png_ptr, - png_const_charp text, png_size_t text_len, int compression, - compression_state *comp) +static void +png_text_compress_init(compression_state *comp, png_const_bytep input, + png_alloc_size_t input_len) +{ + comp->input = input; + comp->input_len = input_len; + comp->output_len = 0; +} + +/* Compress the data in the compression state input */ +static int +png_text_compress(png_structrp png_ptr, png_uint_32 chunk_name, + compression_state *comp, png_uint_32 prefix_len) { int ret; - comp->num_output_ptr = 0; - comp->max_output_ptr = 0; - comp->output_ptr = NULL; - comp->input = NULL; - comp->input_len = text_len; - - /* We may just want to pass the text right through */ - if (compression == PNG_TEXT_COMPRESSION_NONE) - { - comp->input = (png_const_bytep)text; - return((int)text_len); - } - - if (compression >= PNG_TEXT_COMPRESSION_LAST) - { - PNG_WARNING_PARAMETERS(p) - - png_warning_parameter_signed(p, 1, PNG_NUMBER_FORMAT_d, - compression); - png_formatted_warning(png_ptr, p, "Unknown compression type @1"); - } - - /* We can't write the chunk until we find out how much data we have, - * which means we need to run the compressor first and save the - * output. This shouldn't be a problem, as the vast majority of - * comments should be reasonable, but we will set up an array of - * malloc'd pointers to be sure. + /* To find the length of the output it is necessary to first compress the + * input. The result is buffered rather than using the two-pass algorithm + * that is used on the inflate side; deflate is assumed to be slower and a + * PNG writer is assumed to have more memory available than a PNG reader. * - * If we knew the application was well behaved, we could simplify this - * greatly by assuming we can always malloc an output buffer large - * enough to hold the compressed text ((1001 * text_len / 1000) + 12) - * and malloc this directly. The only time this would be a bad idea is - * if we can't malloc more than 64K and we have 64K of random input - * data, or if the input string is incredibly large (although this - * wouldn't cause a failure, just a slowdown due to swapping). + * IMPLEMENTATION NOTE: the zlib API deflateBound() can be used to find an + * upper limit on the output size, but it is always bigger than the input + * size so it is likely to be more efficient to use this linked-list + * approach. */ - png_zlib_claim(png_ptr, PNG_ZLIB_FOR_TEXT); + ret = png_deflate_claim(png_ptr, chunk_name, comp->input_len); - /* Set up the compression buffers */ - /* TODO: the following cast hides a potential overflow problem. */ - png_ptr->zstream.avail_in = (uInt)text_len; + if (ret != Z_OK) + return ret; - /* NOTE: assume zlib doesn't overwrite the input */ - png_ptr->zstream.next_in = (Bytef *)text; - png_ptr->zstream.avail_out = png_ptr->zbuf_size; - png_ptr->zstream.next_out = png_ptr->zbuf; - - /* This is the same compression loop as in png_write_row() */ - do + /* Set up the compression buffers, we need a loop here to avoid overflowing a + * uInt. Use ZLIB_IO_MAX to limit the input. The output is always limited + * by the output buffer size, so there is no need to check that. Since this + * is ANSI-C we know that an 'int', hence a uInt, is always at least 16 bits + * in size. + */ { - /* Compress the data */ - ret = deflate(&png_ptr->zstream, Z_NO_FLUSH); + png_compression_bufferp *end = &png_ptr->zbuffer_list; + png_alloc_size_t input_len = comp->input_len; /* may be zero! */ + png_uint_32 output_len; - if (ret != Z_OK) + /* zlib updates these for us: */ + png_ptr->zstream.next_in = PNGZ_INPUT_CAST(comp->input); + png_ptr->zstream.avail_in = 0; /* Set below */ + png_ptr->zstream.next_out = comp->output; + png_ptr->zstream.avail_out = (sizeof comp->output); + + output_len = png_ptr->zstream.avail_out; + + do { - /* Error */ - if (png_ptr->zstream.msg != NULL) - png_error(png_ptr, png_ptr->zstream.msg); + uInt avail_in = ZLIB_IO_MAX; - else - png_error(png_ptr, "zlib error"); - } + if (avail_in > input_len) + avail_in = (uInt)input_len; - /* Check to see if we need more room */ - if (!(png_ptr->zstream.avail_out)) - { - /* Make sure the output array has room */ - if (comp->num_output_ptr >= comp->max_output_ptr) + input_len -= avail_in; + + png_ptr->zstream.avail_in = avail_in; + + if (png_ptr->zstream.avail_out == 0) { - int old_max; + png_compression_buffer *next; - old_max = comp->max_output_ptr; - comp->max_output_ptr = comp->num_output_ptr + 4; - if (comp->output_ptr != NULL) + /* Chunk data is limited to 2^31 bytes in length, so the prefix + * length must be counted here. + */ + if (output_len + prefix_len > PNG_UINT_31_MAX) { - png_bytepp old_ptr; - - old_ptr = comp->output_ptr; - - comp->output_ptr = (png_bytepp)png_malloc(png_ptr, - (png_alloc_size_t) - (comp->max_output_ptr * png_sizeof(png_charpp))); - - png_memcpy(comp->output_ptr, old_ptr, old_max - * png_sizeof(png_charp)); - - png_free(png_ptr, old_ptr); + ret = Z_MEM_ERROR; + break; } - else - comp->output_ptr = (png_bytepp)png_malloc(png_ptr, - (png_alloc_size_t) - (comp->max_output_ptr * png_sizeof(png_charp))); - } - /* Save the data */ - comp->output_ptr[comp->num_output_ptr] = - (png_bytep)png_malloc(png_ptr, - (png_alloc_size_t)png_ptr->zbuf_size); - - png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf, - png_ptr->zbuf_size); - - comp->num_output_ptr++; - - /* and reset the buffer */ - png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; - png_ptr->zstream.next_out = png_ptr->zbuf; - } - /* Continue until we don't have any more to compress */ - } while (png_ptr->zstream.avail_in); - - /* Finish the compression */ - do - { - /* Tell zlib we are finished */ - ret = deflate(&png_ptr->zstream, Z_FINISH); - - if (ret == Z_OK) - { - /* Check to see if we need more room */ - if (!(png_ptr->zstream.avail_out)) - { - /* Check to make sure our output array has room */ - if (comp->num_output_ptr >= comp->max_output_ptr) + /* Need a new (malloc'ed) buffer, but there may be one present + * already. + */ + next = *end; + if (next == NULL) { - int old_max; + next = png_voidcast(png_compression_bufferp, png_malloc_base + (png_ptr, PNG_COMPRESSION_BUFFER_SIZE(png_ptr))); - old_max = comp->max_output_ptr; - comp->max_output_ptr = comp->num_output_ptr + 4; - if (comp->output_ptr != NULL) + if (next == NULL) { - png_bytepp old_ptr; - - old_ptr = comp->output_ptr; - - /* This could be optimized to realloc() */ - comp->output_ptr = (png_bytepp)png_malloc(png_ptr, - (png_alloc_size_t)(comp->max_output_ptr * - png_sizeof(png_charp))); - - png_memcpy(comp->output_ptr, old_ptr, - old_max * png_sizeof(png_charp)); - - png_free(png_ptr, old_ptr); + ret = Z_MEM_ERROR; + break; } - else - comp->output_ptr = (png_bytepp)png_malloc(png_ptr, - (png_alloc_size_t)(comp->max_output_ptr * - png_sizeof(png_charp))); + /* Link in this buffer (so that it will be freed later) */ + next->next = NULL; + *end = next; } - /* Save the data */ - comp->output_ptr[comp->num_output_ptr] = - (png_bytep)png_malloc(png_ptr, - (png_alloc_size_t)png_ptr->zbuf_size); + png_ptr->zstream.next_out = next->output; + png_ptr->zstream.avail_out = png_ptr->zbuffer_size; + output_len += png_ptr->zstream.avail_out; - png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf, - png_ptr->zbuf_size); - - comp->num_output_ptr++; - - /* and reset the buffer pointers */ - png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; - png_ptr->zstream.next_out = png_ptr->zbuf; + /* Move 'end' to the next buffer pointer. */ + end = &next->next; } + + /* Compress the data */ + ret = deflate(&png_ptr->zstream, + input_len > 0 ? Z_NO_FLUSH : Z_FINISH); + + /* Claw back input data that was not consumed (because avail_in is + * reset above every time round the loop). + */ + input_len += png_ptr->zstream.avail_in; + png_ptr->zstream.avail_in = 0; /* safety */ } - else if (ret != Z_STREAM_END) + while (ret == Z_OK); + + /* There may be some space left in the last output buffer. This needs to + * be subtracted from output_len. + */ + output_len -= png_ptr->zstream.avail_out; + png_ptr->zstream.avail_out = 0; /* safety */ + comp->output_len = output_len; + + /* Now double check the output length, put in a custom message if it is + * too long. Otherwise ensure the z_stream::msg pointer is set to + * something. + */ + if (output_len + prefix_len >= PNG_UINT_31_MAX) { - /* We got an error */ - if (png_ptr->zstream.msg != NULL) - png_error(png_ptr, png_ptr->zstream.msg); - - else - png_error(png_ptr, "zlib error"); + png_ptr->zstream.msg = PNGZ_MSG_CAST("compressed data too long"); + ret = Z_MEM_ERROR; } - } while (ret != Z_STREAM_END); - /* Text length is number of buffers plus last buffer */ - text_len = png_ptr->zbuf_size * comp->num_output_ptr; + else + png_zstream_error(png_ptr, ret); - if (png_ptr->zstream.avail_out < png_ptr->zbuf_size) - text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out; + /* Reset zlib for another zTXt/iTXt or image data */ + png_ptr->zowner = 0; - return((int)text_len); + /* The only success case is Z_STREAM_END, input_len must be 0; if not this + * is an internal error. + */ + if (ret == Z_STREAM_END && input_len == 0) + { +#ifdef PNG_WRITE_OPTIMIZE_CMF_SUPPORTED + /* Fix up the deflate header, if required */ + optimize_cmf(comp->output, comp->input_len); +#endif + /* But Z_OK is returned, not Z_STREAM_END; this allows the claim + * function above to return Z_STREAM_END on an error (though it never + * does in the current versions of zlib.) + */ + return Z_OK; + } + + else + return ret; + } } /* Ship the compressed text out via chunk writes */ -static void /* PRIVATE */ -png_write_compressed_data_out(png_structp png_ptr, compression_state *comp) +static void +png_write_compressed_data_out(png_structrp png_ptr, compression_state *comp) { - int i; + png_uint_32 output_len = comp->output_len; + png_const_bytep output = comp->output; + png_uint_32 avail = (sizeof comp->output); + png_compression_buffer *next = png_ptr->zbuffer_list; - /* Handle the no-compression case */ - if (comp->input) + for (;;) { - png_write_chunk_data(png_ptr, comp->input, comp->input_len); + if (avail > output_len) + avail = output_len; - return; + png_write_chunk_data(png_ptr, output, avail); + + output_len -= avail; + + if (output_len == 0 || next == NULL) + break; + + avail = png_ptr->zbuffer_size; + output = next->output; + next = next->next; } -#ifdef PNG_WRITE_OPTIMIZE_CMF_SUPPORTED - if (comp->input_len >= 2 && comp->input_len < 16384) + /* This is an internal error; 'next' must have been NULL! */ + if (output_len > 0) + png_error(png_ptr, "error writing ancillary chunked compressed data"); +} +#endif /* WRITE_COMPRESSED_TEXT */ + +#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \ + defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED) +/* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification, + * and if invalid, correct the keyword rather than discarding the entire + * chunk. The PNG 1.0 specification requires keywords 1-79 characters in + * length, forbids leading or trailing whitespace, multiple internal spaces, + * and the non-break space (0x80) from ISO 8859-1. Returns keyword length. + * + * The 'new_key' buffer must be 80 characters in size (for the keyword plus a + * trailing '\0'). If this routine returns 0 then there was no keyword, or a + * valid one could not be generated, and the caller must png_error. + */ +static png_uint_32 +png_check_keyword(png_structrp png_ptr, png_const_charp key, png_bytep new_key) +{ + png_const_charp orig_key = key; + png_uint_32 key_len = 0; + int bad_character = 0; + int space = 1; + + png_debug(1, "in png_check_keyword"); + + if (key == NULL) { - unsigned int z_cmf; /* zlib compression method and flags */ + *new_key = 0; + return 0; + } - /* Optimize the CMF field in the zlib stream. This hack of the zlib - * stream is compliant to the stream specification. - */ + while (*key && key_len < 79) + { + png_byte ch = (png_byte)(0xff & *key++); - if (comp->num_output_ptr) - z_cmf = comp->output_ptr[0][0]; - else - z_cmf = png_ptr->zbuf[0]; + if ((ch > 32 && ch <= 126) || (ch >= 161 /*&& ch <= 255*/)) + *new_key++ = ch, ++key_len, space = 0; - if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70) + else if (space == 0) { - unsigned int z_cinfo; - unsigned int half_z_window_size; - png_size_t uncompressed_text_size = comp->input_len; + /* A space or an invalid character when one wasn't seen immediately + * before; output just a space. + */ + *new_key++ = 32, ++key_len, space = 1; - z_cinfo = z_cmf >> 4; - half_z_window_size = 1 << (z_cinfo + 7); - - while (uncompressed_text_size <= half_z_window_size && - half_z_window_size >= 256) - { - z_cinfo--; - half_z_window_size >>= 1; - } - - z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4); - - if (comp->num_output_ptr) - { - - if (comp->output_ptr[0][0] != z_cmf) - { - int tmp; - - comp->output_ptr[0][0] = (png_byte)z_cmf; - tmp = comp->output_ptr[0][1] & 0xe0; - tmp += 0x1f - ((z_cmf << 8) + tmp) % 0x1f; - comp->output_ptr[0][1] = (png_byte)tmp; - } - } - else - { - int tmp; - - png_ptr->zbuf[0] = (png_byte)z_cmf; - tmp = png_ptr->zbuf[1] & 0xe0; - tmp += 0x1f - ((z_cmf << 8) + tmp) % 0x1f; - png_ptr->zbuf[1] = (png_byte)tmp; - } + /* If the character was not a space then it is invalid. */ + if (ch != 32) + bad_character = ch; } - else - png_error(png_ptr, - "Invalid zlib compression method or flags in non-IDAT chunk"); + else if (bad_character == 0) + bad_character = ch; /* just skip it, record the first error */ } -#endif /* PNG_WRITE_OPTIMIZE_CMF_SUPPORTED */ - /* Write saved output buffers, if any */ - for (i = 0; i < comp->num_output_ptr; i++) + if (key_len > 0 && space != 0) /* trailing space */ { - png_write_chunk_data(png_ptr, comp->output_ptr[i], - (png_size_t)png_ptr->zbuf_size); - - png_free(png_ptr, comp->output_ptr[i]); + --key_len, --new_key; + if (bad_character == 0) + bad_character = 32; } - if (comp->max_output_ptr != 0) - png_free(png_ptr, comp->output_ptr); + /* Terminate the keyword */ + *new_key = 0; - /* Write anything left in zbuf */ - if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size) - png_write_chunk_data(png_ptr, png_ptr->zbuf, - (png_size_t)(png_ptr->zbuf_size - png_ptr->zstream.avail_out)); + if (key_len == 0) + return 0; - /* Reset zlib for another zTXt/iTXt or image data */ - png_zlib_release(png_ptr); +#ifdef PNG_WARNINGS_SUPPORTED + /* Try to only output one warning per keyword: */ + if (*key != 0) /* keyword too long */ + png_warning(png_ptr, "keyword truncated"); + + else if (bad_character != 0) + { + PNG_WARNING_PARAMETERS(p) + + png_warning_parameter(p, 1, orig_key); + png_warning_parameter_signed(p, 2, PNG_NUMBER_FORMAT_02x, bad_character); + + png_formatted_warning(png_ptr, p, "keyword \"@1\": bad character '0x@2'"); + } +#endif /* WARNINGS */ + + return key_len; } -#endif /* PNG_WRITE_COMPRESSED_TEXT_SUPPORTED */ +#endif /* WRITE_TEXT || WRITE_pCAL || WRITE_iCCP || WRITE_sPLT */ /* Write the IHDR chunk, and update the png_struct with the necessary * information. Note that the rest of this code depends upon this * information being correct. */ void /* PRIVATE */ -png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height, +png_write_IHDR(png_structrp png_ptr, png_uint_32 width, png_uint_32 height, int bit_depth, int color_type, int compression_type, int filter_type, int interlace_type) { - PNG_IHDR; - png_byte buf[13]; /* Buffer to store the IHDR info */ png_debug(1, "in png_write_IHDR"); @@ -772,8 +876,8 @@ png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height, */ if ( #ifdef PNG_MNG_FEATURES_SUPPORTED - !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) && - ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) && + !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 && + ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) == 0) && (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA) && (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) && @@ -823,14 +927,9 @@ png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height, buf[12] = (png_byte)interlace_type; /* Write the chunk */ - png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13); + png_write_complete_chunk(png_ptr, png_IHDR, buf, (png_size_t)13); - /* Initialize zlib with PNG info */ - png_ptr->zstream.zalloc = png_zalloc; - png_ptr->zstream.zfree = png_zfree; - png_ptr->zstream.opaque = (voidpf)png_ptr; - - if (!(png_ptr->do_filter)) + if ((png_ptr->do_filter) == PNG_NO_FILTERS) { if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE || png_ptr->bit_depth < 8) @@ -840,55 +939,6 @@ png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height, png_ptr->do_filter = PNG_ALL_FILTERS; } - if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY)) - { - if (png_ptr->do_filter != PNG_FILTER_NONE) - png_ptr->zlib_strategy = Z_FILTERED; - - else - png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY; - } - - if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL)) - png_ptr->zlib_level = Z_DEFAULT_COMPRESSION; - - if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL)) - png_ptr->zlib_mem_level = 8; - - if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS)) - png_ptr->zlib_window_bits = 15; - - if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD)) - png_ptr->zlib_method = 8; - -#ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED -#ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED - if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_STRATEGY)) - png_ptr->zlib_text_strategy = Z_DEFAULT_STRATEGY; - - if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_LEVEL)) - png_ptr->zlib_text_level = png_ptr->zlib_level; - - if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_MEM_LEVEL)) - png_ptr->zlib_text_mem_level = png_ptr->zlib_mem_level; - - if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_WINDOW_BITS)) - png_ptr->zlib_text_window_bits = png_ptr->zlib_window_bits; - - if (!(png_ptr->flags & PNG_FLAG_ZTXT_CUSTOM_METHOD)) - png_ptr->zlib_text_method = png_ptr->zlib_method; -#else - png_ptr->zlib_text_strategy = Z_DEFAULT_STRATEGY; - png_ptr->zlib_text_level = png_ptr->zlib_level; - png_ptr->zlib_text_mem_level = png_ptr->zlib_mem_level; - png_ptr->zlib_text_window_bits = png_ptr->zlib_window_bits; - png_ptr->zlib_text_method = png_ptr->zlib_method; -#endif /* PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED */ -#endif /* PNG_WRITE_COMPRESSED_TEXT_SUPPORTED */ - - /* Record that the compressor has not yet been initialized. */ - png_ptr->zlib_state = PNG_ZLIB_UNINITIALIZED; - png_ptr->mode = PNG_HAVE_IHDR; /* not READY_FOR_ZTXT */ } @@ -897,10 +947,9 @@ png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height, * structure. */ void /* PRIVATE */ -png_write_PLTE(png_structp png_ptr, png_const_colorp palette, +png_write_PLTE(png_structrp png_ptr, png_const_colorp palette, png_uint_32 num_pal) { - PNG_PLTE; png_uint_32 i; png_const_colorp pal_ptr; png_byte buf[3]; @@ -909,7 +958,7 @@ png_write_PLTE(png_structp png_ptr, png_const_colorp palette, if (( #ifdef PNG_MNG_FEATURES_SUPPORTED - !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) && + (png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0 && #endif num_pal == 0) || num_pal > 256) { @@ -925,7 +974,7 @@ png_write_PLTE(png_structp png_ptr, png_const_colorp palette, } } - if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR)) + if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) { png_warning(png_ptr, "Ignoring request to write a PLTE chunk in grayscale PNG"); @@ -936,7 +985,7 @@ png_write_PLTE(png_structp png_ptr, png_const_colorp palette, png_ptr->num_palette = (png_uint_16)num_pal; png_debug1(3, "num_palette = %d", png_ptr->num_palette); - png_write_chunk_start(png_ptr, png_PLTE, (png_uint_32)(num_pal * 3)); + png_write_chunk_header(png_ptr, png_PLTE, (png_uint_32)(num_pal * 3)); #ifdef PNG_POINTER_INDEXING_SUPPORTED for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++) @@ -966,127 +1015,192 @@ png_write_PLTE(png_structp png_ptr, png_const_colorp palette, png_ptr->mode |= PNG_HAVE_PLTE; } -/* Write an IDAT chunk */ +/* This is similar to png_text_compress, above, except that it does not require + * all of the data at once and, instead of buffering the compressed result, + * writes it as IDAT chunks. Unlike png_text_compress it *can* png_error out + * because it calls the write interface. As a result it does its own error + * reporting and does not return an error code. In the event of error it will + * just call png_error. The input data length may exceed 32-bits. The 'flush' + * parameter is exactly the same as that to deflate, with the following + * meanings: + * + * Z_NO_FLUSH: normal incremental output of compressed data + * Z_SYNC_FLUSH: do a SYNC_FLUSH, used by png_write_flush + * Z_FINISH: this is the end of the input, do a Z_FINISH and clean up + * + * The routine manages the acquire and release of the png_ptr->zstream by + * checking and (at the end) clearing png_ptr->zowner; it does some sanity + * checks on the 'mode' flags while doing this. + */ void /* PRIVATE */ -png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length) +png_compress_IDAT(png_structrp png_ptr, png_const_bytep input, + png_alloc_size_t input_len, int flush) { - PNG_IDAT; - - png_debug(1, "in png_write_IDAT"); - -#ifdef PNG_WRITE_OPTIMIZE_CMF_SUPPORTED - if (!(png_ptr->mode & PNG_HAVE_IDAT) && - png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE) + if (png_ptr->zowner != png_IDAT) { - /* Optimize the CMF field in the zlib stream. This hack of the zlib - * stream is compliant to the stream specification. + /* First time. Ensure we have a temporary buffer for compression and + * trim the buffer list if it has more than one entry to free memory. + * If 'WRITE_COMPRESSED_TEXT' is not set the list will never have been + * created at this point, but the check here is quick and safe. */ - unsigned int z_cmf = data[0]; /* zlib compression method and flags */ - - if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70) + if (png_ptr->zbuffer_list == NULL) { - /* Avoid memory underflows and multiplication overflows. - * - * The conditions below are practically always satisfied; - * however, they still must be checked. - */ - if (length >= 2 && - png_ptr->height < 16384 && png_ptr->width < 16384) - { - /* Compute the maximum possible length of the datastream */ - - /* Number of pixels, plus for each row a filter byte - * and possibly a padding byte, so increase the maximum - * size to account for these. - */ - unsigned int z_cinfo; - unsigned int half_z_window_size; - png_uint_32 uncompressed_idat_size = png_ptr->height * - ((png_ptr->width * - png_ptr->channels * png_ptr->bit_depth + 15) >> 3); - - /* If it's interlaced, each block of 8 rows is sent as up to - * 14 rows, i.e., 6 additional rows, each with a filter byte - * and possibly a padding byte - */ - if (png_ptr->interlaced) - uncompressed_idat_size += ((png_ptr->height + 7)/8) * - (png_ptr->bit_depth < 8 ? 12 : 6); - - z_cinfo = z_cmf >> 4; - half_z_window_size = 1 << (z_cinfo + 7); - - while (uncompressed_idat_size <= half_z_window_size && - half_z_window_size >= 256) - { - z_cinfo--; - half_z_window_size >>= 1; - } - - z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4); - - if (data[0] != z_cmf) - { - int tmp; - data[0] = (png_byte)z_cmf; - tmp = data[1] & 0xe0; - tmp += 0x1f - ((z_cmf << 8) + tmp) % 0x1f; - data[1] = (png_byte)tmp; - } - } + png_ptr->zbuffer_list = png_voidcast(png_compression_bufferp, + png_malloc(png_ptr, PNG_COMPRESSION_BUFFER_SIZE(png_ptr))); + png_ptr->zbuffer_list->next = NULL; } else - png_error(png_ptr, - "Invalid zlib compression method or flags in IDAT"); + png_free_buffer_list(png_ptr, &png_ptr->zbuffer_list->next); + + /* It is a terminal error if we can't claim the zstream. */ + if (png_deflate_claim(png_ptr, png_IDAT, png_image_size(png_ptr)) != Z_OK) + png_error(png_ptr, png_ptr->zstream.msg); + + /* The output state is maintained in png_ptr->zstream, so it must be + * initialized here after the claim. + */ + png_ptr->zstream.next_out = png_ptr->zbuffer_list->output; + png_ptr->zstream.avail_out = png_ptr->zbuffer_size; } -#endif /* PNG_WRITE_OPTIMIZE_CMF_SUPPORTED */ - png_write_chunk(png_ptr, png_IDAT, data, length); - png_ptr->mode |= PNG_HAVE_IDAT; - - /* Prior to 1.5.4 this code was replicated in every caller (except at the - * end, where it isn't technically necessary). Since this function has - * flushed the data we can safely reset the zlib output buffer here. + /* Now loop reading and writing until all the input is consumed or an error + * terminates the operation. The _out values are maintained across calls to + * this function, but the input must be reset each time. */ - png_ptr->zstream.next_out = png_ptr->zbuf; - png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; + png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input); + png_ptr->zstream.avail_in = 0; /* set below */ + for (;;) + { + int ret; + + /* INPUT: from the row data */ + uInt avail = ZLIB_IO_MAX; + + if (avail > input_len) + avail = (uInt)input_len; /* safe because of the check */ + + png_ptr->zstream.avail_in = avail; + input_len -= avail; + + ret = deflate(&png_ptr->zstream, input_len > 0 ? Z_NO_FLUSH : flush); + + /* Include as-yet unconsumed input */ + input_len += png_ptr->zstream.avail_in; + png_ptr->zstream.avail_in = 0; + + /* OUTPUT: write complete IDAT chunks when avail_out drops to zero. Note + * that these two zstream fields are preserved across the calls, therefore + * there is no need to set these up on entry to the loop. + */ + if (png_ptr->zstream.avail_out == 0) + { + png_bytep data = png_ptr->zbuffer_list->output; + uInt size = png_ptr->zbuffer_size; + + /* Write an IDAT containing the data then reset the buffer. The + * first IDAT may need deflate header optimization. + */ +#ifdef PNG_WRITE_OPTIMIZE_CMF_SUPPORTED + if ((png_ptr->mode & PNG_HAVE_IDAT) == 0 && + png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE) + optimize_cmf(data, png_image_size(png_ptr)); +#endif + + png_write_complete_chunk(png_ptr, png_IDAT, data, size); + png_ptr->mode |= PNG_HAVE_IDAT; + + png_ptr->zstream.next_out = data; + png_ptr->zstream.avail_out = size; + + /* For SYNC_FLUSH or FINISH it is essential to keep calling zlib with + * the same flush parameter until it has finished output, for NO_FLUSH + * it doesn't matter. + */ + if (ret == Z_OK && flush != Z_NO_FLUSH) + continue; + } + + /* The order of these checks doesn't matter much; it just affects which + * possible error might be detected if multiple things go wrong at once. + */ + if (ret == Z_OK) /* most likely return code! */ + { + /* If all the input has been consumed then just return. If Z_FINISH + * was used as the flush parameter something has gone wrong if we get + * here. + */ + if (input_len == 0) + { + if (flush == Z_FINISH) + png_error(png_ptr, "Z_OK on Z_FINISH with output space"); + + return; + } + } + + else if (ret == Z_STREAM_END && flush == Z_FINISH) + { + /* This is the end of the IDAT data; any pending output must be + * flushed. For small PNG files we may still be at the beginning. + */ + png_bytep data = png_ptr->zbuffer_list->output; + uInt size = png_ptr->zbuffer_size - png_ptr->zstream.avail_out; + +#ifdef PNG_WRITE_OPTIMIZE_CMF_SUPPORTED + if ((png_ptr->mode & PNG_HAVE_IDAT) == 0 && + png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE) + optimize_cmf(data, png_image_size(png_ptr)); +#endif + + png_write_complete_chunk(png_ptr, png_IDAT, data, size); + png_ptr->zstream.avail_out = 0; + png_ptr->zstream.next_out = NULL; + png_ptr->mode |= PNG_HAVE_IDAT | PNG_AFTER_IDAT; + + png_ptr->zowner = 0; /* Release the stream */ + return; + } + + else + { + /* This is an error condition. */ + png_zstream_error(png_ptr, ret); + png_error(png_ptr, png_ptr->zstream.msg); + } + } } /* Write an IEND chunk */ void /* PRIVATE */ -png_write_IEND(png_structp png_ptr) +png_write_IEND(png_structrp png_ptr) { - PNG_IEND; - png_debug(1, "in png_write_IEND"); - png_write_chunk(png_ptr, png_IEND, NULL, (png_size_t)0); + png_write_complete_chunk(png_ptr, png_IEND, NULL, (png_size_t)0); png_ptr->mode |= PNG_HAVE_IEND; } #ifdef PNG_WRITE_gAMA_SUPPORTED /* Write a gAMA chunk */ void /* PRIVATE */ -png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma) +png_write_gAMA_fixed(png_structrp png_ptr, png_fixed_point file_gamma) { - PNG_gAMA; png_byte buf[4]; png_debug(1, "in png_write_gAMA"); /* file_gamma is saved in 1/100,000ths */ png_save_uint_32(buf, (png_uint_32)file_gamma); - png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4); + png_write_complete_chunk(png_ptr, png_gAMA, buf, (png_size_t)4); } #endif #ifdef PNG_WRITE_sRGB_SUPPORTED /* Write a sRGB chunk */ void /* PRIVATE */ -png_write_sRGB(png_structp png_ptr, int srgb_intent) +png_write_sRGB(png_structrp png_ptr, int srgb_intent) { - PNG_sRGB; png_byte buf[1]; png_debug(1, "in png_write_sRGB"); @@ -1096,104 +1210,79 @@ png_write_sRGB(png_structp png_ptr, int srgb_intent) "Invalid sRGB rendering intent specified"); buf[0]=(png_byte)srgb_intent; - png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1); + png_write_complete_chunk(png_ptr, png_sRGB, buf, (png_size_t)1); } #endif #ifdef PNG_WRITE_iCCP_SUPPORTED /* Write an iCCP chunk */ void /* PRIVATE */ -png_write_iCCP(png_structp png_ptr, png_const_charp name, int compression_type, - png_const_charp profile, int profile_len) +png_write_iCCP(png_structrp png_ptr, png_const_charp name, + png_const_bytep profile) { - PNG_iCCP; - png_size_t name_len; - png_charp new_name; + png_uint_32 name_len; + png_uint_32 profile_len; + png_byte new_name[81]; /* 1 byte for the compression byte */ compression_state comp; - int embedded_profile_len = 0; + png_uint_32 temp; png_debug(1, "in png_write_iCCP"); - comp.num_output_ptr = 0; - comp.max_output_ptr = 0; - comp.output_ptr = NULL; - comp.input = NULL; - comp.input_len = 0; - - if ((name_len = png_check_keyword(png_ptr, name, &new_name)) == 0) - return; - - if (compression_type != PNG_COMPRESSION_TYPE_BASE) - png_warning(png_ptr, "Unknown compression type in iCCP chunk"); - + /* These are all internal problems: the profile should have been checked + * before when it was stored. + */ if (profile == NULL) - profile_len = 0; + png_error(png_ptr, "No profile for iCCP chunk"); /* internal error */ - if (profile_len > 3) - embedded_profile_len = - ((*( (png_const_bytep)profile ))<<24) | - ((*( (png_const_bytep)profile + 1))<<16) | - ((*( (png_const_bytep)profile + 2))<< 8) | - ((*( (png_const_bytep)profile + 3)) ); + profile_len = png_get_uint_32(profile); + + if (profile_len < 132) + png_error(png_ptr, "ICC profile too short"); + + temp = (png_uint_32) (*(profile+8)); + if (temp > 3 && (profile_len & 0x03)) + png_error(png_ptr, "ICC profile length invalid (not a multiple of 4)"); - if (embedded_profile_len < 0) { - png_warning(png_ptr, - "Embedded profile length in iCCP chunk is negative"); + png_uint_32 embedded_profile_len = png_get_uint_32(profile); - png_free(png_ptr, new_name); - return; + if (profile_len != embedded_profile_len) + png_error(png_ptr, "Profile length does not match profile"); } - if (profile_len < embedded_profile_len) - { - png_warning(png_ptr, - "Embedded profile length too large in iCCP chunk"); + name_len = png_check_keyword(png_ptr, name, new_name); - png_free(png_ptr, new_name); - return; - } + if (name_len == 0) + png_error(png_ptr, "iCCP: invalid keyword"); - if (profile_len > embedded_profile_len) - { - png_warning(png_ptr, - "Truncating profile to actual length in iCCP chunk"); - - profile_len = embedded_profile_len; - } - - if (profile_len) - profile_len = png_text_compress(png_ptr, profile, - (png_size_t)profile_len, PNG_COMPRESSION_TYPE_BASE, &comp); + new_name[++name_len] = PNG_COMPRESSION_TYPE_BASE; /* Make sure we include the NULL after the name and the compression type */ - png_write_chunk_start(png_ptr, png_iCCP, - (png_uint_32)(name_len + profile_len + 2)); + ++name_len; - new_name[name_len + 1] = 0x00; + png_text_compress_init(&comp, profile, profile_len); - png_write_chunk_data(png_ptr, (png_bytep)new_name, - (png_size_t)(name_len + 2)); + /* Allow for keyword terminator and compression byte */ + if (png_text_compress(png_ptr, png_iCCP, &comp, name_len) != Z_OK) + png_error(png_ptr, png_ptr->zstream.msg); - if (profile_len) - { - comp.input_len = profile_len; - png_write_compressed_data_out(png_ptr, &comp); - } + png_write_chunk_header(png_ptr, png_iCCP, name_len + comp.output_len); + + png_write_chunk_data(png_ptr, new_name, name_len); + + png_write_compressed_data_out(png_ptr, &comp); png_write_chunk_end(png_ptr); - png_free(png_ptr, new_name); } #endif #ifdef PNG_WRITE_sPLT_SUPPORTED /* Write a sPLT chunk */ void /* PRIVATE */ -png_write_sPLT(png_structp png_ptr, png_const_sPLT_tp spalette) +png_write_sPLT(png_structrp png_ptr, png_const_sPLT_tp spalette) { - PNG_sPLT; - png_size_t name_len; - png_charp new_name; + png_uint_32 name_len; + png_byte new_name[80]; png_byte entrybuf[10]; png_size_t entry_size = (spalette->depth == 8 ? 6 : 10); png_size_t palette_size = entry_size * spalette->nentries; @@ -1204,11 +1293,13 @@ png_write_sPLT(png_structp png_ptr, png_const_sPLT_tp spalette) png_debug(1, "in png_write_sPLT"); - if ((name_len = png_check_keyword(png_ptr,spalette->name, &new_name))==0) - return; + name_len = png_check_keyword(png_ptr, spalette->name, new_name); + + if (name_len == 0) + png_error(png_ptr, "sPLT: invalid keyword"); /* Make sure we include the NULL after the name */ - png_write_chunk_start(png_ptr, png_sPLT, + png_write_chunk_header(png_ptr, png_sPLT, (png_uint_32)(name_len + 2 + palette_size)); png_write_chunk_data(png_ptr, (png_bytep)new_name, @@ -1238,7 +1329,7 @@ png_write_sPLT(png_structp png_ptr, png_const_sPLT_tp spalette) png_save_uint_16(entrybuf + 8, ep->frequency); } - png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size); + png_write_chunk_data(png_ptr, entrybuf, entry_size); } #else ep=spalette->entries; @@ -1262,28 +1353,26 @@ png_write_sPLT(png_structp png_ptr, png_const_sPLT_tp spalette) png_save_uint_16(entrybuf + 8, ep[i].frequency); } - png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size); + png_write_chunk_data(png_ptr, entrybuf, entry_size); } #endif png_write_chunk_end(png_ptr); - png_free(png_ptr, new_name); } #endif #ifdef PNG_WRITE_sBIT_SUPPORTED /* Write the sBIT chunk */ void /* PRIVATE */ -png_write_sBIT(png_structp png_ptr, png_const_color_8p sbit, int color_type) +png_write_sBIT(png_structrp png_ptr, png_const_color_8p sbit, int color_type) { - PNG_sBIT; png_byte buf[4]; png_size_t size; png_debug(1, "in png_write_sBIT"); /* Make sure we don't depend upon the order of PNG_COLOR_8 */ - if (color_type & PNG_COLOR_MASK_COLOR) + if ((color_type & PNG_COLOR_MASK_COLOR) != 0) { png_byte maxbits; @@ -1316,7 +1405,7 @@ png_write_sBIT(png_structp png_ptr, png_const_color_8p sbit, int color_type) size = 1; } - if (color_type & PNG_COLOR_MASK_ALPHA) + if ((color_type & PNG_COLOR_MASK_ALPHA) != 0) { if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth) { @@ -1327,53 +1416,42 @@ png_write_sBIT(png_structp png_ptr, png_const_color_8p sbit, int color_type) buf[size++] = sbit->alpha; } - png_write_chunk(png_ptr, png_sBIT, buf, size); + png_write_complete_chunk(png_ptr, png_sBIT, buf, size); } #endif #ifdef PNG_WRITE_cHRM_SUPPORTED /* Write the cHRM chunk */ void /* PRIVATE */ -png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x, - png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y, - png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x, - png_fixed_point blue_y) +png_write_cHRM_fixed(png_structrp png_ptr, const png_xy *xy) { - PNG_cHRM; png_byte buf[32]; png_debug(1, "in png_write_cHRM"); /* Each value is saved in 1/100,000ths */ -#ifdef PNG_CHECK_cHRM_SUPPORTED - if (png_check_cHRM_fixed(png_ptr, white_x, white_y, red_x, red_y, - green_x, green_y, blue_x, blue_y)) -#endif - { - png_save_uint_32(buf, (png_uint_32)white_x); - png_save_uint_32(buf + 4, (png_uint_32)white_y); + png_save_int_32(buf, xy->whitex); + png_save_int_32(buf + 4, xy->whitey); - png_save_uint_32(buf + 8, (png_uint_32)red_x); - png_save_uint_32(buf + 12, (png_uint_32)red_y); + png_save_int_32(buf + 8, xy->redx); + png_save_int_32(buf + 12, xy->redy); - png_save_uint_32(buf + 16, (png_uint_32)green_x); - png_save_uint_32(buf + 20, (png_uint_32)green_y); + png_save_int_32(buf + 16, xy->greenx); + png_save_int_32(buf + 20, xy->greeny); - png_save_uint_32(buf + 24, (png_uint_32)blue_x); - png_save_uint_32(buf + 28, (png_uint_32)blue_y); + png_save_int_32(buf + 24, xy->bluex); + png_save_int_32(buf + 28, xy->bluey); - png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32); - } + png_write_complete_chunk(png_ptr, png_cHRM, buf, 32); } #endif #ifdef PNG_WRITE_tRNS_SUPPORTED /* Write the tRNS chunk */ void /* PRIVATE */ -png_write_tRNS(png_structp png_ptr, png_const_bytep trans_alpha, +png_write_tRNS(png_structrp png_ptr, png_const_bytep trans_alpha, png_const_color_16p tran, int num_trans, int color_type) { - PNG_tRNS; png_byte buf[6]; png_debug(1, "in png_write_tRNS"); @@ -1382,12 +1460,14 @@ png_write_tRNS(png_structp png_ptr, png_const_bytep trans_alpha, { if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette) { - png_warning(png_ptr, "Invalid number of transparent colors specified"); + png_app_warning(png_ptr, + "Invalid number of transparent colors specified"); return; } /* Write the chunk out as it is */ - png_write_chunk(png_ptr, png_tRNS, trans_alpha, (png_size_t)num_trans); + png_write_complete_chunk(png_ptr, png_tRNS, trans_alpha, + (png_size_t)num_trans); } else if (color_type == PNG_COLOR_TYPE_GRAY) @@ -1395,14 +1475,14 @@ png_write_tRNS(png_structp png_ptr, png_const_bytep trans_alpha, /* One 16 bit value */ if (tran->gray >= (1 << png_ptr->bit_depth)) { - png_warning(png_ptr, + png_app_warning(png_ptr, "Ignoring attempt to write tRNS chunk out-of-range for bit_depth"); return; } png_save_uint_16(buf, tran->gray); - png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2); + png_write_complete_chunk(png_ptr, png_tRNS, buf, (png_size_t)2); } else if (color_type == PNG_COLOR_TYPE_RGB) @@ -1412,22 +1492,22 @@ png_write_tRNS(png_structp png_ptr, png_const_bytep trans_alpha, png_save_uint_16(buf + 2, tran->green); png_save_uint_16(buf + 4, tran->blue); #ifdef PNG_WRITE_16BIT_SUPPORTED - if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4])) + if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]) != 0) #else - if (buf[0] | buf[2] | buf[4]) + if ((buf[0] | buf[2] | buf[4]) != 0) #endif { - png_warning(png_ptr, + png_app_warning(png_ptr, "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8"); return; } - png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6); + png_write_complete_chunk(png_ptr, png_tRNS, buf, (png_size_t)6); } else { - png_warning(png_ptr, "Can't write tRNS with an alpha channel"); + png_app_warning(png_ptr, "Can't write tRNS with an alpha channel"); } } #endif @@ -1435,9 +1515,8 @@ png_write_tRNS(png_structp png_ptr, png_const_bytep trans_alpha, #ifdef PNG_WRITE_bKGD_SUPPORTED /* Write the background chunk */ void /* PRIVATE */ -png_write_bKGD(png_structp png_ptr, png_const_color_16p back, int color_type) +png_write_bKGD(png_structrp png_ptr, png_const_color_16p back, int color_type) { - PNG_bKGD; png_byte buf[6]; png_debug(1, "in png_write_bKGD"); @@ -1446,8 +1525,8 @@ png_write_bKGD(png_structp png_ptr, png_const_color_16p back, int color_type) { if ( #ifdef PNG_MNG_FEATURES_SUPPORTED - (png_ptr->num_palette || - (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) && + (png_ptr->num_palette != 0 || + (png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0) && #endif back->index >= png_ptr->num_palette) { @@ -1456,18 +1535,18 @@ png_write_bKGD(png_structp png_ptr, png_const_color_16p back, int color_type) } buf[0] = back->index; - png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1); + png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)1); } - else if (color_type & PNG_COLOR_MASK_COLOR) + else if ((color_type & PNG_COLOR_MASK_COLOR) != 0) { png_save_uint_16(buf, back->red); png_save_uint_16(buf + 2, back->green); png_save_uint_16(buf + 4, back->blue); #ifdef PNG_WRITE_16BIT_SUPPORTED - if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4])) + if (png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]) != 0) #else - if (buf[0] | buf[2] | buf[4]) + if ((buf[0] | buf[2] | buf[4]) != 0) #endif { png_warning(png_ptr, @@ -1476,7 +1555,7 @@ png_write_bKGD(png_structp png_ptr, png_const_color_16p back, int color_type) return; } - png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6); + png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)6); } else @@ -1490,7 +1569,7 @@ png_write_bKGD(png_structp png_ptr, png_const_color_16p back, int color_type) } png_save_uint_16(buf, back->gray); - png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2); + png_write_complete_chunk(png_ptr, png_bKGD, buf, (png_size_t)2); } } #endif @@ -1498,9 +1577,8 @@ png_write_bKGD(png_structp png_ptr, png_const_color_16p back, int color_type) #ifdef PNG_WRITE_hIST_SUPPORTED /* Write the histogram */ void /* PRIVATE */ -png_write_hIST(png_structp png_ptr, png_const_uint_16p hist, int num_hist) +png_write_hIST(png_structrp png_ptr, png_const_uint_16p hist, int num_hist) { - PNG_hIST; int i; png_byte buf[3]; @@ -1515,7 +1593,7 @@ png_write_hIST(png_structp png_ptr, png_const_uint_16p hist, int num_hist) return; } - png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2)); + png_write_chunk_header(png_ptr, png_hIST, (png_uint_32)(num_hist * 2)); for (i = 0; i < num_hist; i++) { @@ -1527,236 +1605,93 @@ png_write_hIST(png_structp png_ptr, png_const_uint_16p hist, int num_hist) } #endif -#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \ - defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED) -/* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification, - * and if invalid, correct the keyword rather than discarding the entire - * chunk. The PNG 1.0 specification requires keywords 1-79 characters in - * length, forbids leading or trailing whitespace, multiple internal spaces, - * and the non-break space (0x80) from ISO 8859-1. Returns keyword length. - * - * The new_key is allocated to hold the corrected keyword and must be freed - * by the calling routine. This avoids problems with trying to write to - * static keywords without having to have duplicate copies of the strings. - */ -png_size_t /* PRIVATE */ -png_check_keyword(png_structp png_ptr, png_const_charp key, png_charpp new_key) -{ - png_size_t key_len; - png_const_charp ikp; - png_charp kp, dp; - int kflag; - int kwarn=0; - - png_debug(1, "in png_check_keyword"); - - *new_key = NULL; - - if (key == NULL || (key_len = png_strlen(key)) == 0) - { - png_warning(png_ptr, "zero length keyword"); - return ((png_size_t)0); - } - - png_debug1(2, "Keyword to be checked is '%s'", key); - - *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2)); - - if (*new_key == NULL) - { - png_warning(png_ptr, "Out of memory while procesing keyword"); - return ((png_size_t)0); - } - - /* Replace non-printing characters with a blank and print a warning */ - for (ikp = key, dp = *new_key; *ikp != '\0'; ikp++, dp++) - { - if ((png_byte)*ikp < 0x20 || - ((png_byte)*ikp > 0x7E && (png_byte)*ikp < 0xA1)) - { - PNG_WARNING_PARAMETERS(p) - - png_warning_parameter_unsigned(p, 1, PNG_NUMBER_FORMAT_02x, - (png_byte)*ikp); - png_formatted_warning(png_ptr, p, "invalid keyword character 0x@1"); - *dp = ' '; - } - - else - { - *dp = *ikp; - } - } - *dp = '\0'; - - /* Remove any trailing white space. */ - kp = *new_key + key_len - 1; - if (*kp == ' ') - { - png_warning(png_ptr, "trailing spaces removed from keyword"); - - while (*kp == ' ') - { - *(kp--) = '\0'; - key_len--; - } - } - - /* Remove any leading white space. */ - kp = *new_key; - if (*kp == ' ') - { - png_warning(png_ptr, "leading spaces removed from keyword"); - - while (*kp == ' ') - { - kp++; - key_len--; - } - } - - png_debug1(2, "Checking for multiple internal spaces in '%s'", kp); - - /* Remove multiple internal spaces. */ - for (kflag = 0, dp = *new_key; *kp != '\0'; kp++) - { - if (*kp == ' ' && kflag == 0) - { - *(dp++) = *kp; - kflag = 1; - } - - else if (*kp == ' ') - { - key_len--; - kwarn = 1; - } - - else - { - *(dp++) = *kp; - kflag = 0; - } - } - *dp = '\0'; - if (kwarn) - png_warning(png_ptr, "extra interior spaces removed from keyword"); - - if (key_len == 0) - { - png_free(png_ptr, *new_key); - png_warning(png_ptr, "Zero length keyword"); - } - - if (key_len > 79) - { - png_warning(png_ptr, "keyword length must be 1 - 79 characters"); - (*new_key)[79] = '\0'; - key_len = 79; - } - - return (key_len); -} -#endif - #ifdef PNG_WRITE_tEXt_SUPPORTED /* Write a tEXt chunk */ void /* PRIVATE */ -png_write_tEXt(png_structp png_ptr, png_const_charp key, png_const_charp text, +png_write_tEXt(png_structrp png_ptr, png_const_charp key, png_const_charp text, png_size_t text_len) { - PNG_tEXt; - png_size_t key_len; - png_charp new_key; + png_uint_32 key_len; + png_byte new_key[80]; png_debug(1, "in png_write_tEXt"); - if ((key_len = png_check_keyword(png_ptr, key, &new_key))==0) - return; + key_len = png_check_keyword(png_ptr, key, new_key); + + if (key_len == 0) + png_error(png_ptr, "tEXt: invalid keyword"); if (text == NULL || *text == '\0') text_len = 0; else - text_len = png_strlen(text); + text_len = strlen(text); + + if (text_len > PNG_UINT_31_MAX - (key_len+1)) + png_error(png_ptr, "tEXt: text too long"); /* Make sure we include the 0 after the key */ - png_write_chunk_start(png_ptr, png_tEXt, - (png_uint_32)(key_len + text_len + 1)); + png_write_chunk_header(png_ptr, png_tEXt, + (png_uint_32)/*checked above*/(key_len + text_len + 1)); /* * We leave it to the application to meet PNG-1.0 requirements on the * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG. */ - png_write_chunk_data(png_ptr, (png_bytep)new_key, - (png_size_t)(key_len + 1)); + png_write_chunk_data(png_ptr, new_key, key_len + 1); - if (text_len) - png_write_chunk_data(png_ptr, (png_const_bytep)text, - (png_size_t)text_len); + if (text_len != 0) + png_write_chunk_data(png_ptr, (png_const_bytep)text, text_len); png_write_chunk_end(png_ptr); - png_free(png_ptr, new_key); } #endif #ifdef PNG_WRITE_zTXt_SUPPORTED /* Write a compressed text chunk */ void /* PRIVATE */ -png_write_zTXt(png_structp png_ptr, png_const_charp key, png_const_charp text, - png_size_t text_len, int compression) +png_write_zTXt(png_structrp png_ptr, png_const_charp key, png_const_charp text, + int compression) { - PNG_zTXt; - png_size_t key_len; - png_byte buf; - png_charp new_key; + png_uint_32 key_len; + png_byte new_key[81]; compression_state comp; png_debug(1, "in png_write_zTXt"); - comp.num_output_ptr = 0; - comp.max_output_ptr = 0; - comp.output_ptr = NULL; - comp.input = NULL; - comp.input_len = 0; - - if ((key_len = png_check_keyword(png_ptr, key, &new_key)) == 0) + if (compression == PNG_TEXT_COMPRESSION_NONE) { - png_free(png_ptr, new_key); + png_write_tEXt(png_ptr, key, text, 0); return; } - if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE) - { - png_write_tEXt(png_ptr, new_key, text, (png_size_t)0); - png_free(png_ptr, new_key); - return; - } + if (compression != PNG_TEXT_COMPRESSION_zTXt) + png_error(png_ptr, "zTXt: invalid compression type"); - text_len = png_strlen(text); + key_len = png_check_keyword(png_ptr, key, new_key); + + if (key_len == 0) + png_error(png_ptr, "zTXt: invalid keyword"); + + /* Add the compression method and 1 for the keyword separator. */ + new_key[++key_len] = PNG_COMPRESSION_TYPE_BASE; + ++key_len; /* Compute the compressed data; do it now for the length */ - text_len = png_text_compress(png_ptr, text, text_len, compression, - &comp); + png_text_compress_init(&comp, (png_const_bytep)text, + text == NULL ? 0 : strlen(text)); + + if (png_text_compress(png_ptr, png_zTXt, &comp, key_len) != Z_OK) + png_error(png_ptr, png_ptr->zstream.msg); /* Write start of chunk */ - png_write_chunk_start(png_ptr, png_zTXt, - (png_uint_32)(key_len+text_len + 2)); + png_write_chunk_header(png_ptr, png_zTXt, key_len + comp.output_len); /* Write key */ - png_write_chunk_data(png_ptr, (png_bytep)new_key, - (png_size_t)(key_len + 1)); - - png_free(png_ptr, new_key); - - buf = (png_byte)compression; - - /* Write compression */ - png_write_chunk_data(png_ptr, &buf, (png_size_t)1); + png_write_chunk_data(png_ptr, new_key, key_len); /* Write the compressed data */ - comp.input_len = text_len; png_write_compressed_data_out(png_ptr, &comp); /* Close the chunk */ @@ -1767,104 +1702,109 @@ png_write_zTXt(png_structp png_ptr, png_const_charp key, png_const_charp text, #ifdef PNG_WRITE_iTXt_SUPPORTED /* Write an iTXt chunk */ void /* PRIVATE */ -png_write_iTXt(png_structp png_ptr, int compression, png_const_charp key, +png_write_iTXt(png_structrp png_ptr, int compression, png_const_charp key, png_const_charp lang, png_const_charp lang_key, png_const_charp text) { - PNG_iTXt; - png_size_t lang_len, key_len, lang_key_len, text_len; - png_charp new_lang; - png_charp new_key = NULL; - png_byte cbuf[2]; + png_uint_32 key_len, prefix_len; + png_size_t lang_len, lang_key_len; + png_byte new_key[82]; compression_state comp; png_debug(1, "in png_write_iTXt"); - comp.num_output_ptr = 0; - comp.max_output_ptr = 0; - comp.output_ptr = NULL; - comp.input = NULL; + key_len = png_check_keyword(png_ptr, key, new_key); - if ((key_len = png_check_keyword(png_ptr, key, &new_key)) == 0) - return; + if (key_len == 0) + png_error(png_ptr, "iTXt: invalid keyword"); - if ((lang_len = png_check_keyword(png_ptr, lang, &new_lang)) == 0) + /* Set the compression flag */ + switch (compression) { - png_warning(png_ptr, "Empty language field in iTXt chunk"); - new_lang = NULL; - lang_len = 0; + case PNG_ITXT_COMPRESSION_NONE: + case PNG_TEXT_COMPRESSION_NONE: + compression = new_key[++key_len] = 0; /* no compression */ + break; + + case PNG_TEXT_COMPRESSION_zTXt: + case PNG_ITXT_COMPRESSION_zTXt: + compression = new_key[++key_len] = 1; /* compressed */ + break; + + default: + png_error(png_ptr, "iTXt: invalid compression"); } - if (lang_key == NULL) - lang_key_len = 0; - - else - lang_key_len = png_strlen(lang_key); - - if (text == NULL) - text_len = 0; - - else - text_len = png_strlen(text); - - /* Compute the compressed data; do it now for the length */ - text_len = png_text_compress(png_ptr, text, text_len, compression - 2, - &comp); - - - /* Make sure we include the compression flag, the compression byte, - * and the NULs after the key, lang, and lang_key parts - */ - - png_write_chunk_start(png_ptr, png_iTXt, (png_uint_32)( - 5 /* comp byte, comp flag, terminators for key, lang and lang_key */ - + key_len - + lang_len - + lang_key_len - + text_len)); + new_key[++key_len] = PNG_COMPRESSION_TYPE_BASE; + ++key_len; /* for the keywod separator */ /* We leave it to the application to meet PNG-1.0 requirements on the * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of - * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them. + * any non-Latin-1 characters except for NEWLINE. ISO PNG, however, + * specifies that the text is UTF-8 and this really doesn't require any + * checking. + * * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG. + * + * TODO: validate the language tag correctly (see the spec.) */ - png_write_chunk_data(png_ptr, (png_bytep)new_key, (png_size_t)(key_len + 1)); + if (lang == NULL) lang = ""; /* empty language is valid */ + lang_len = strlen(lang)+1; + if (lang_key == NULL) lang_key = ""; /* may be empty */ + lang_key_len = strlen(lang_key)+1; + if (text == NULL) text = ""; /* may be empty */ - /* Set the compression flag */ - if (compression == PNG_ITXT_COMPRESSION_NONE || - compression == PNG_TEXT_COMPRESSION_NONE) - cbuf[0] = 0; + prefix_len = key_len; + if (lang_len > PNG_UINT_31_MAX-prefix_len) + prefix_len = PNG_UINT_31_MAX; + else + prefix_len = (png_uint_32)(prefix_len + lang_len); - else /* compression == PNG_ITXT_COMPRESSION_zTXt */ - cbuf[0] = 1; + if (lang_key_len > PNG_UINT_31_MAX-prefix_len) + prefix_len = PNG_UINT_31_MAX; + else + prefix_len = (png_uint_32)(prefix_len + lang_key_len); - /* Set the compression method */ - cbuf[1] = 0; + png_text_compress_init(&comp, (png_const_bytep)text, strlen(text)); - png_write_chunk_data(png_ptr, cbuf, (png_size_t)2); + if (compression != 0) + { + if (png_text_compress(png_ptr, png_iTXt, &comp, prefix_len) != Z_OK) + png_error(png_ptr, png_ptr->zstream.msg); + } - cbuf[0] = 0; - png_write_chunk_data(png_ptr, (new_lang ? (png_const_bytep)new_lang : cbuf), - (png_size_t)(lang_len + 1)); + else + { + if (comp.input_len > PNG_UINT_31_MAX-prefix_len) + png_error(png_ptr, "iTXt: uncompressed text too long"); - png_write_chunk_data(png_ptr, (lang_key ? (png_const_bytep)lang_key : cbuf), - (png_size_t)(lang_key_len + 1)); + /* So the string will fit in a chunk: */ + comp.output_len = (png_uint_32)/*SAFE*/comp.input_len; + } - png_write_compressed_data_out(png_ptr, &comp); + png_write_chunk_header(png_ptr, png_iTXt, comp.output_len + prefix_len); + + png_write_chunk_data(png_ptr, new_key, key_len); + + png_write_chunk_data(png_ptr, (png_const_bytep)lang, lang_len); + + png_write_chunk_data(png_ptr, (png_const_bytep)lang_key, lang_key_len); + + if (compression != 0) + png_write_compressed_data_out(png_ptr, &comp); + + else + png_write_chunk_data(png_ptr, (png_const_bytep)text, comp.input_len); png_write_chunk_end(png_ptr); - - png_free(png_ptr, new_key); - png_free(png_ptr, new_lang); } #endif #ifdef PNG_WRITE_oFFs_SUPPORTED /* Write the oFFs chunk */ void /* PRIVATE */ -png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset, +png_write_oFFs(png_structrp png_ptr, png_int_32 x_offset, png_int_32 y_offset, int unit_type) { - PNG_oFFs; png_byte buf[9]; png_debug(1, "in png_write_oFFs"); @@ -1876,52 +1816,57 @@ png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset, png_save_int_32(buf + 4, y_offset); buf[8] = (png_byte)unit_type; - png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9); + png_write_complete_chunk(png_ptr, png_oFFs, buf, (png_size_t)9); } #endif #ifdef PNG_WRITE_pCAL_SUPPORTED /* Write the pCAL chunk (described in the PNG extensions document) */ void /* PRIVATE */ -png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0, +png_write_pCAL(png_structrp png_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams, png_const_charp units, png_charpp params) { - PNG_pCAL; - png_size_t purpose_len, units_len, total_len; - png_uint_32p params_len; + png_uint_32 purpose_len; + png_size_t units_len, total_len; + png_size_tp params_len; png_byte buf[10]; - png_charp new_purpose; + png_byte new_purpose[80]; int i; png_debug1(1, "in png_write_pCAL (%d parameters)", nparams); if (type >= PNG_EQUATION_LAST) - png_warning(png_ptr, "Unrecognized equation type for pCAL chunk"); + png_error(png_ptr, "Unrecognized equation type for pCAL chunk"); + + purpose_len = png_check_keyword(png_ptr, purpose, new_purpose); + + if (purpose_len == 0) + png_error(png_ptr, "pCAL: invalid keyword"); + + ++purpose_len; /* terminator */ - purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1; png_debug1(3, "pCAL purpose length = %d", (int)purpose_len); - units_len = png_strlen(units) + (nparams == 0 ? 0 : 1); + units_len = strlen(units) + (nparams == 0 ? 0 : 1); png_debug1(3, "pCAL units length = %d", (int)units_len); total_len = purpose_len + units_len + 10; - params_len = (png_uint_32p)png_malloc(png_ptr, - (png_alloc_size_t)(nparams * png_sizeof(png_uint_32))); + params_len = (png_size_tp)png_malloc(png_ptr, + (png_alloc_size_t)(nparams * (sizeof (png_size_t)))); /* Find the length of each parameter, making sure we don't count the * null terminator for the last parameter. */ for (i = 0; i < nparams; i++) { - params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1); + params_len[i] = strlen(params[i]) + (i == nparams - 1 ? 0 : 1); png_debug2(3, "pCAL parameter %d length = %lu", i, (unsigned long)params_len[i]); - total_len += (png_size_t)params_len[i]; + total_len += params_len[i]; } png_debug1(3, "pCAL total length = %d", (int)total_len); - png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len); - png_write_chunk_data(png_ptr, (png_const_bytep)new_purpose, - (png_size_t)purpose_len); + png_write_chunk_header(png_ptr, png_pCAL, (png_uint_32)total_len); + png_write_chunk_data(png_ptr, new_purpose, purpose_len); png_save_int_32(buf, X0); png_save_int_32(buf + 4, X1); buf[8] = (png_byte)type; @@ -1929,12 +1874,9 @@ png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0, png_write_chunk_data(png_ptr, buf, (png_size_t)10); png_write_chunk_data(png_ptr, (png_const_bytep)units, (png_size_t)units_len); - png_free(png_ptr, new_purpose); - for (i = 0; i < nparams; i++) { - png_write_chunk_data(png_ptr, (png_const_bytep)params[i], - (png_size_t)params_len[i]); + png_write_chunk_data(png_ptr, (png_const_bytep)params[i], params_len[i]); } png_free(png_ptr, params_len); @@ -1945,17 +1887,16 @@ png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0, #ifdef PNG_WRITE_sCAL_SUPPORTED /* Write the sCAL chunk */ void /* PRIVATE */ -png_write_sCAL_s(png_structp png_ptr, int unit, png_const_charp width, +png_write_sCAL_s(png_structrp png_ptr, int unit, png_const_charp width, png_const_charp height) { - PNG_sCAL; png_byte buf[64]; png_size_t wlen, hlen, total_len; png_debug(1, "in png_write_sCAL_s"); - wlen = png_strlen(width); - hlen = png_strlen(height); + wlen = strlen(width); + hlen = strlen(height); total_len = wlen + hlen + 2; if (total_len > 64) @@ -1965,22 +1906,21 @@ png_write_sCAL_s(png_structp png_ptr, int unit, png_const_charp width, } buf[0] = (png_byte)unit; - png_memcpy(buf + 1, width, wlen + 1); /* Append the '\0' here */ - png_memcpy(buf + wlen + 2, height, hlen); /* Do NOT append the '\0' here */ + memcpy(buf + 1, width, wlen + 1); /* Append the '\0' here */ + memcpy(buf + wlen + 2, height, hlen); /* Do NOT append the '\0' here */ png_debug1(3, "sCAL total length = %u", (unsigned int)total_len); - png_write_chunk(png_ptr, png_sCAL, buf, total_len); + png_write_complete_chunk(png_ptr, png_sCAL, buf, total_len); } #endif #ifdef PNG_WRITE_pHYs_SUPPORTED /* Write the pHYs chunk */ void /* PRIVATE */ -png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit, +png_write_pHYs(png_structrp png_ptr, png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit, int unit_type) { - PNG_pHYs; png_byte buf[9]; png_debug(1, "in png_write_pHYs"); @@ -1992,7 +1932,7 @@ png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit, png_save_uint_32(buf + 4, y_pixels_per_unit); buf[8] = (png_byte)unit_type; - png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9); + png_write_complete_chunk(png_ptr, png_pHYs, buf, (png_size_t)9); } #endif @@ -2001,9 +1941,8 @@ png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit, * or png_convert_from_time_t(), or fill in the structure yourself. */ void /* PRIVATE */ -png_write_tIME(png_structp png_ptr, png_const_timep mod_time) +png_write_tIME(png_structrp png_ptr, png_const_timep mod_time) { - PNG_tIME; png_byte buf[7]; png_debug(1, "in png_write_tIME"); @@ -2023,40 +1962,44 @@ png_write_tIME(png_structp png_ptr, png_const_timep mod_time) buf[5] = mod_time->minute; buf[6] = mod_time->second; - png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7); + png_write_complete_chunk(png_ptr, png_tIME, buf, (png_size_t)7); } #endif /* Initializes the row writing capability of libpng */ void /* PRIVATE */ -png_write_start_row(png_structp png_ptr) +png_write_start_row(png_structrp png_ptr) { #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ - int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; + static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ - int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; + static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ - int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; + static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ - int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; + static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; #endif - png_size_t buf_size; + png_alloc_size_t buf_size; + int usr_pixel_depth; png_debug(1, "in png_write_start_row"); - buf_size = (png_size_t)(PNG_ROWBYTES( - png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1); + usr_pixel_depth = png_ptr->usr_channels * png_ptr->usr_bit_depth; + buf_size = PNG_ROWBYTES(usr_pixel_depth, png_ptr->width) + 1; + + /* 1.5.6: added to allow checking in the row write code. */ + png_ptr->transformed_pixel_depth = png_ptr->pixel_depth; + png_ptr->maximum_pixel_depth = (png_byte)usr_pixel_depth; /* Set up row buffer */ - png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, - (png_alloc_size_t)buf_size); + png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, buf_size); png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE; @@ -2070,13 +2013,13 @@ png_write_start_row(png_structp png_ptr) } /* We only need to keep the previous row if we are using one of these. */ - if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH)) + if ((png_ptr->do_filter & + (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH)) != 0) { /* Set up previous row buffer */ - png_ptr->prev_row = (png_bytep)png_calloc(png_ptr, - (png_alloc_size_t)buf_size); + png_ptr->prev_row = (png_bytep)png_calloc(png_ptr, buf_size); - if (png_ptr->do_filter & PNG_FILTER_UP) + if ((png_ptr->do_filter & PNG_FILTER_UP) != 0) { png_ptr->up_row = (png_bytep)png_malloc(png_ptr, png_ptr->rowbytes + 1); @@ -2084,7 +2027,7 @@ png_write_start_row(png_structp png_ptr) png_ptr->up_row[0] = PNG_FILTER_VALUE_UP; } - if (png_ptr->do_filter & PNG_FILTER_AVG) + if ((png_ptr->do_filter & PNG_FILTER_AVG) != 0) { png_ptr->avg_row = (png_bytep)png_malloc(png_ptr, png_ptr->rowbytes + 1); @@ -2092,7 +2035,7 @@ png_write_start_row(png_structp png_ptr) png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG; } - if (png_ptr->do_filter & PNG_FILTER_PAETH) + if ((png_ptr->do_filter & PNG_FILTER_PAETH) != 0) { png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr, png_ptr->rowbytes + 1); @@ -2100,13 +2043,13 @@ png_write_start_row(png_structp png_ptr) png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH; } } -#endif /* PNG_WRITE_FILTER_SUPPORTED */ +#endif /* WRITE_FILTER */ #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* If interlaced, we need to set up width and height of pass */ - if (png_ptr->interlaced) + if (png_ptr->interlaced != 0) { - if (!(png_ptr->transformations & PNG_INTERLACE)) + if ((png_ptr->transformations & PNG_INTERLACE) == 0) { png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 - png_pass_ystart[0]) / png_pass_yinc[0]; @@ -2128,34 +2071,28 @@ png_write_start_row(png_structp png_ptr) png_ptr->num_rows = png_ptr->height; png_ptr->usr_width = png_ptr->width; } - - png_zlib_claim(png_ptr, PNG_ZLIB_FOR_IDAT); - png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; - png_ptr->zstream.next_out = png_ptr->zbuf; } /* Internal use only. Called when finished processing a row of data. */ void /* PRIVATE */ -png_write_finish_row(png_structp png_ptr) +png_write_finish_row(png_structrp png_ptr) { #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ - int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; + static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ - int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; + static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ - int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; + static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ - int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; + static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; #endif - int ret; - png_debug(1, "in png_write_finish_row"); /* Next row */ @@ -2167,10 +2104,10 @@ png_write_finish_row(png_structp png_ptr) #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* If interlaced, go to next pass */ - if (png_ptr->interlaced) + if (png_ptr->interlaced != 0) { png_ptr->row_number = 0; - if (png_ptr->transformations & PNG_INTERLACE) + if ((png_ptr->transformations & PNG_INTERLACE) != 0) { png_ptr->pass++; } @@ -2195,7 +2132,7 @@ png_write_finish_row(png_structp png_ptr) png_pass_ystart[png_ptr->pass]) / png_pass_yinc[png_ptr->pass]; - if (png_ptr->transformations & PNG_INTERLACE) + if ((png_ptr->transformations & PNG_INTERLACE) != 0) break; } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0); @@ -2206,7 +2143,7 @@ png_write_finish_row(png_structp png_ptr) if (png_ptr->pass < 7) { if (png_ptr->prev_row != NULL) - png_memset(png_ptr->prev_row, 0, + memset(png_ptr->prev_row, 0, (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels* png_ptr->usr_bit_depth, png_ptr->width)) + 1); @@ -2217,42 +2154,7 @@ png_write_finish_row(png_structp png_ptr) /* If we get here, we've just written the last row, so we need to flush the compressor */ - do - { - /* Tell the compressor we are done */ - ret = deflate(&png_ptr->zstream, Z_FINISH); - - /* Check for an error */ - if (ret == Z_OK) - { - /* Check to see if we need more room */ - if (!(png_ptr->zstream.avail_out)) - { - png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size); - png_ptr->zstream.next_out = png_ptr->zbuf; - png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; - } - } - - else if (ret != Z_STREAM_END) - { - if (png_ptr->zstream.msg != NULL) - png_error(png_ptr, png_ptr->zstream.msg); - - else - png_error(png_ptr, "zlib error"); - } - } while (ret != Z_STREAM_END); - - /* Write any extra space */ - if (png_ptr->zstream.avail_out < png_ptr->zbuf_size) - { - png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size - - png_ptr->zstream.avail_out); - } - - png_zlib_release(png_ptr); - png_ptr->zstream.data_type = Z_BINARY; + png_compress_IDAT(png_ptr, NULL, 0, Z_FINISH); } #ifdef PNG_WRITE_INTERLACING_SUPPORTED @@ -2269,10 +2171,10 @@ png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass) /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ - int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; + static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ - int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; + static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; png_debug(1, "in png_do_write_interlace"); @@ -2416,7 +2318,7 @@ png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass) /* Move the pixel */ if (dp != sp) - png_memcpy(dp, sp, pixel_bytes); + memcpy(dp, sp, pixel_bytes); /* Next pixel */ dp += pixel_bytes; @@ -2440,14 +2342,16 @@ png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass) * been specified by the application, and then writes the row out with the * chosen filter. */ -static void png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row); +static void +png_write_filtered_row(png_structrp png_ptr, png_bytep filtered_row, + png_size_t row_bytes); #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1) #define PNG_HISHIFT 10 #define PNG_LOMASK ((png_uint_32)0xffffL) #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT)) void /* PRIVATE */ -png_write_find_filter(png_structp png_ptr, png_row_infop row_info) +png_write_find_filter(png_structrp png_ptr, png_row_infop row_info) { png_bytep best_row; #ifdef PNG_WRITE_FILTER_SUPPORTED @@ -2456,7 +2360,7 @@ png_write_find_filter(png_structp png_ptr, png_row_infop row_info) png_byte filter_to_do = png_ptr->do_filter; png_size_t row_bytes = row_info->rowbytes; #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED - int num_p_filters = (int)png_ptr->num_prev_filters; + int num_p_filters = png_ptr->num_prev_filters; #endif png_debug(1, "in png_write_find_filter"); @@ -2507,7 +2411,7 @@ png_write_find_filter(png_structp png_ptr, png_row_infop row_info) /* We don't need to test the 'no filter' case if this is the only filter * that has been chosen, as it doesn't actually do anything to the data. */ - if ((filter_to_do & PNG_FILTER_NONE) && filter_to_do != PNG_FILTER_NONE) + if ((filter_to_do & PNG_FILTER_NONE) != 0 && filter_to_do != PNG_FILTER_NONE) { png_bytep rp; png_uint_32 sum = 0; @@ -2583,7 +2487,7 @@ png_write_find_filter(png_structp png_ptr, png_row_infop row_info) best_row = png_ptr->sub_row; } - else if (filter_to_do & PNG_FILTER_SUB) + else if ((filter_to_do & PNG_FILTER_SUB) != 0) { png_bytep rp, dp, lp; png_uint_32 sum = 0, lmins = mins; @@ -2704,7 +2608,7 @@ png_write_find_filter(png_structp png_ptr, png_row_infop row_info) best_row = png_ptr->up_row; } - else if (filter_to_do & PNG_FILTER_UP) + else if ((filter_to_do & PNG_FILTER_UP) != 0) { png_bytep rp, dp, pp; png_uint_32 sum = 0, lmins = mins; @@ -2818,7 +2722,7 @@ png_write_find_filter(png_structp png_ptr, png_row_infop row_info) best_row = png_ptr->avg_row; } - else if (filter_to_do & PNG_FILTER_AVG) + else if ((filter_to_do & PNG_FILTER_AVG) != 0) { png_bytep rp, dp, pp, lp; png_uint_32 sum = 0, lmins = mins; @@ -2920,7 +2824,7 @@ png_write_find_filter(png_structp png_ptr, png_row_infop row_info) } /* Paeth filter */ - if (filter_to_do == PNG_FILTER_PAETH) + if ((filter_to_do == PNG_FILTER_PAETH) != 0) { png_bytep rp, dp, pp, cp, lp; png_size_t i; @@ -2959,7 +2863,7 @@ png_write_find_filter(png_structp png_ptr, png_row_infop row_info) best_row = png_ptr->paeth_row; } - else if (filter_to_do & PNG_FILTER_PAETH) + else if ((filter_to_do & PNG_FILTER_PAETH) != 0) { png_bytep rp, dp, pp, cp, lp; png_uint_32 sum = 0, lmins = mins; @@ -3029,7 +2933,7 @@ png_write_find_filter(png_structp png_ptr, png_row_infop row_info) pc = (p + pc) < 0 ? -(p + pc) : p + pc; #endif p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c; -#else /* PNG_SLOW_PAETH */ +#else /* SLOW_PAETH */ p = a + b - c; pa = abs(p - a); pb = abs(p - b); @@ -3043,7 +2947,7 @@ png_write_find_filter(png_structp png_ptr, png_row_infop row_info) else p = c; -#endif /* PNG_SLOW_PAETH */ +#endif /* SLOW_PAETH */ v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff); @@ -3092,10 +2996,10 @@ png_write_find_filter(png_structp png_ptr, png_row_infop row_info) best_row = png_ptr->paeth_row; } } -#endif /* PNG_WRITE_FILTER_SUPPORTED */ - /* Do the actual writing of the filtered row data from the chosen filter. */ +#endif /* WRITE_FILTER */ - png_write_filtered_row(png_ptr, best_row); + /* Do the actual writing of the filtered row data from the chosen filter. */ + png_write_filtered_row(png_ptr, best_row, row_info->rowbytes+1); #ifdef PNG_WRITE_FILTER_SUPPORTED #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED @@ -3112,74 +3016,20 @@ png_write_find_filter(png_structp png_ptr, png_row_infop row_info) png_ptr->prev_filters[j] = best_row[0]; } #endif -#endif /* PNG_WRITE_FILTER_SUPPORTED */ +#endif /* WRITE_FILTER */ } /* Do the actual writing of a previously filtered row. */ static void -png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row) +png_write_filtered_row(png_structrp png_ptr, png_bytep filtered_row, + png_size_t full_row_length/*includes filter byte*/) { - png_size_t avail; - png_debug(1, "in png_write_filtered_row"); png_debug1(2, "filter = %d", filtered_row[0]); - /* Set up the zlib input buffer */ - png_ptr->zstream.next_in = filtered_row; - png_ptr->zstream.avail_in = 0; - avail = png_ptr->row_info.rowbytes + 1; - /* Repeat until we have compressed all the data */ - do - { - int ret; /* Return of zlib */ - - /* Record the number of bytes available - zlib supports at least 65535 - * bytes at one step, depending on the size of the zlib type 'uInt', the - * maximum size zlib can write at once is ZLIB_IO_MAX (from pngpriv.h). - * Use this because on 16 bit systems 'rowbytes' can be up to 65536 (i.e. - * one more than 16 bits) and, in this case 'rowbytes+1' can overflow a - * uInt. ZLIB_IO_MAX can be safely reduced to cause zlib to be called - * with smaller chunks of data. - */ - if (png_ptr->zstream.avail_in == 0) - { - if (avail > ZLIB_IO_MAX) - { - png_ptr->zstream.avail_in = ZLIB_IO_MAX; - avail -= ZLIB_IO_MAX; - } - - else - { - /* So this will fit in the available uInt space: */ - png_ptr->zstream.avail_in = (uInt)avail; - avail = 0; - } - } - - /* Compress the data */ - ret = deflate(&png_ptr->zstream, Z_NO_FLUSH); - - /* Check for compression errors */ - if (ret != Z_OK) - { - if (png_ptr->zstream.msg != NULL) - png_error(png_ptr, png_ptr->zstream.msg); - - else - png_error(png_ptr, "zlib error"); - } - - /* See if it is time to write another IDAT */ - if (!(png_ptr->zstream.avail_out)) - { - /* Write the IDAT and reset the zlib output buffer */ - png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size); - } - /* Repeat until all data has been compressed */ - } while (avail > 0 || png_ptr->zstream.avail_in > 0); + png_compress_IDAT(png_ptr, filtered_row, full_row_length, Z_NO_FLUSH); /* Swap the current and previous rows */ if (png_ptr->prev_row != NULL) @@ -3202,6 +3052,6 @@ png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row) { png_write_flush(png_ptr); } -#endif +#endif /* WRITE_FLUSH */ } -#endif /* PNG_WRITE_SUPPORTED */ +#endif /* WRITE */ diff --git a/jdk/src/java.desktop/unix/classes/sun/awt/X11/GtkFileDialogPeer.java b/jdk/src/java.desktop/unix/classes/sun/awt/X11/GtkFileDialogPeer.java index fad3b3b6c09..8c0dc54a3b8 100644 --- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/GtkFileDialogPeer.java +++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/GtkFileDialogPeer.java @@ -29,6 +29,7 @@ import java.awt.peer.FileDialogPeer; import java.io.File; import java.io.FilenameFilter; import sun.awt.AWTAccessor; +import sun.misc.ManagedLocalsThread; /** * FileDialogPeer for the GtkFileChooser. @@ -111,13 +112,16 @@ final class GtkFileDialogPeer extends XDialogPeer implements FileDialogPeer { XToolkit.awtLock(); try { if (b) { - Thread t = new Thread() { - public void run() { - showNativeDialog(); - fd.setVisible(false); - } + Runnable task = () -> { + showNativeDialog(); + fd.setVisible(false); }; - t.start(); + if (System.getSecurityManager() == null) { + new Thread(task).start(); + } else { + new ManagedLocalsThread(task).start(); + } + } else { quit(); fd.setVisible(false); diff --git a/jdk/src/java.desktop/unix/classes/sun/awt/X11/InfoWindow.java b/jdk/src/java.desktop/unix/classes/sun/awt/X11/InfoWindow.java index 41d0ef0f2d0..33cc44fccec 100644 --- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/InfoWindow.java +++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/InfoWindow.java @@ -29,6 +29,9 @@ import java.awt.*; import java.awt.event.*; import java.awt.peer.TrayIconPeer; import sun.awt.*; +import sun.misc.InnocuousThread; +import sun.misc.ManagedLocalsThread; + import java.awt.image.*; import java.text.BreakIterator; import java.util.concurrent.ArrayBlockingQueue; @@ -338,7 +341,7 @@ public abstract class InfoWindow extends Window { lineLabels[i].setBackground(Color.white); } - displayer.start(); + displayer.thread.start(); } public void display(String caption, String text, String messageType) { @@ -415,7 +418,7 @@ public abstract class InfoWindow extends Window { } public void dispose() { - displayer.interrupt(); + displayer.thread.interrupt(); super.dispose(); } @@ -444,16 +447,23 @@ public abstract class InfoWindow extends Window { } } - private class Displayer extends Thread { + private class Displayer implements Runnable { final int MAX_CONCURRENT_MSGS = 10; ArrayBlockingQueue messageQueue = new ArrayBlockingQueue(MAX_CONCURRENT_MSGS); boolean isDisplayed; + final Thread thread; Displayer() { - setDaemon(true); + if (System.getSecurityManager() == null) { + this.thread = new Thread(this); + } else { + this.thread = new ManagedLocalsThread(this); + } + this.thread.setDaemon(true); } + @Override public void run() { while (true) { Message msg = null; diff --git a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XToolkit.java b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XToolkit.java index bfe94c9f27c..3adbc8d35c5 100644 --- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XToolkit.java +++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XToolkit.java @@ -266,21 +266,26 @@ public final class XToolkit extends UNIXToolkit implements Runnable { awtUnlock(); } PrivilegedAction a = () -> { - Thread shutdownThread = new Thread(ThreadGroupUtils.getRootThreadGroup(), "XToolkt-Shutdown-Thread") { - public void run() { - XSystemTrayPeer peer = XSystemTrayPeer.getPeerInstance(); - if (peer != null) { - peer.dispose(); - } - if (xs != null) { - ((XAWTXSettings)xs).dispose(); - } - freeXKB(); - if (log.isLoggable(PlatformLogger.Level.FINE)) { - dumpPeers(); - } - } - }; + Runnable r = () -> { + XSystemTrayPeer peer = XSystemTrayPeer.getPeerInstance(); + if (peer != null) { + peer.dispose(); + } + if (xs != null) { + ((XAWTXSettings)xs).dispose(); + } + freeXKB(); + if (log.isLoggable(PlatformLogger.Level.FINE)) { + dumpPeers(); + } + }; + String name = "XToolkt-Shutdown-Thread"; + Thread shutdownThread; + if (System.getSecurityManager() == null) { + shutdownThread = new Thread(ThreadGroupUtils.getRootThreadGroup(), r, name); + } else { + shutdownThread = new InnocuousThread(r, name); + } shutdownThread.setContextClassLoader(null); Runtime.getRuntime().addShutdownHook(shutdownThread); return null; @@ -326,7 +331,13 @@ public final class XToolkit extends UNIXToolkit implements Runnable { XWM.init(); toolkitThread = AccessController.doPrivileged((PrivilegedAction) () -> { - Thread thread = new Thread(ThreadGroupUtils.getRootThreadGroup(), XToolkit.this, "AWT-XAWT"); + String name = "AWT-XAWT"; + Thread thread; + if (System.getSecurityManager() == null) { + thread = new Thread(ThreadGroupUtils.getRootThreadGroup(), XToolkit.this, name); + } else { + thread = new InnocuousThread(XToolkit.this, name); + } thread.setContextClassLoader(null); thread.setPriority(Thread.NORM_PRIORITY + 1); thread.setDaemon(true); diff --git a/jdk/src/java.desktop/unix/classes/sun/awt/X11GraphicsDevice.java b/jdk/src/java.desktop/unix/classes/sun/awt/X11GraphicsDevice.java index 009035326d9..93511617183 100644 --- a/jdk/src/java.desktop/unix/classes/sun/awt/X11GraphicsDevice.java +++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11GraphicsDevice.java @@ -43,6 +43,7 @@ import sun.java2d.xr.XRGraphicsConfig; import sun.java2d.loops.SurfaceType; import sun.awt.util.ThreadGroupUtils; +import sun.misc.InnocuousThread; /** * This is an implementation of a GraphicsDevice object for a single @@ -428,7 +429,6 @@ public class X11GraphicsDevice // hook will have no effect) shutdownHookRegistered = true; PrivilegedAction a = () -> { - ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); Runnable r = () -> { Window old = getFullScreenWindow(); if (old != null) { @@ -436,7 +436,13 @@ public class X11GraphicsDevice setDisplayMode(origDisplayMode); } }; - Thread t = new Thread(rootTG, r,"Display-Change-Shutdown-Thread-"+screen); + String name = "Display-Change-Shutdown-Thread-" + screen; + Thread t; + if (System.getSecurityManager() == null) { + t = new Thread(ThreadGroupUtils.getRootThreadGroup(), r, name); + } else { + t = new InnocuousThread(r, name); + } t.setContextClassLoader(null); Runtime.getRuntime().addShutdownHook(t); return null; diff --git a/jdk/src/java.desktop/unix/classes/sun/print/PrintServiceLookupProvider.java b/jdk/src/java.desktop/unix/classes/sun/print/PrintServiceLookupProvider.java index 96acd53d58a..e40ba274b46 100644 --- a/jdk/src/java.desktop/unix/classes/sun/print/PrintServiceLookupProvider.java +++ b/jdk/src/java.desktop/unix/classes/sun/print/PrintServiceLookupProvider.java @@ -25,6 +25,8 @@ package sun.print; +import sun.misc.ManagedLocalsThread; + import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; @@ -211,7 +213,12 @@ public class PrintServiceLookupProvider extends PrintServiceLookup public PrintServiceLookupProvider() { // start the printer listener thread if (pollServices) { - PrinterChangeListener thr = new PrinterChangeListener(); + Thread thr; + if (System.getSecurityManager() == null) { + thr = new Thread(new PrinterChangeListener()); + } else { + thr = new ManagedLocalsThread(new PrinterChangeListener()); + } thr.setDaemon(true); thr.start(); IPPPrintService.debug_println(debugPrefix+"polling turned on"); @@ -934,8 +941,9 @@ public class PrintServiceLookupProvider extends PrintServiceLookup } } - private class PrinterChangeListener extends Thread { + private class PrinterChangeListener implements Runnable { + @Override public void run() { int refreshSecs; while (true) { @@ -954,7 +962,7 @@ public class PrintServiceLookupProvider extends PrintServiceLookup refreshSecs = minRefreshTime; } try { - sleep(refreshSecs * 1000); + Thread.sleep(refreshSecs * 1000); } catch (InterruptedException e) { break; } diff --git a/jdk/src/java.desktop/unix/native/libawt_xawt/awt/gtk2_interface.c b/jdk/src/java.desktop/unix/native/libawt_xawt/awt/gtk2_interface.c index 2e35e5ea43a..e8a45cb2059 100644 --- a/jdk/src/java.desktop/unix/native/libawt_xawt/awt/gtk2_interface.c +++ b/jdk/src/java.desktop/unix/native/libawt_xawt/awt/gtk2_interface.c @@ -368,9 +368,9 @@ const char *getStrFor(JNIEnv *env, jstring val) if (length > CONV_BUFFER_SIZE-1) { length = CONV_BUFFER_SIZE-1; -#ifdef INTERNAL_BUILD +#ifdef DEBUG fprintf(stderr, "Note: Detail is too long: %d chars\n", length); -#endif /* INTERNAL_BUILD */ +#endif /* DEBUG */ } (*env)->GetStringUTFRegion(env, val, 0, length, convertionBuffer); @@ -507,9 +507,9 @@ void update_supported_actions(JNIEnv *env) { } } } else { -#ifdef INTERNAL_BUILD +#ifdef DEBUG fprintf(stderr, "Cannot load g_vfs_get_supported_uri_schemes\n"); -#endif /* INTERNAL_BUILD */ +#endif /* DEBUG */ } } @@ -522,23 +522,23 @@ gboolean gtk2_show_uri_load(JNIEnv *env) { const char *gtk_version = fp_gtk_check_version(2, 14, 0); if (gtk_version != NULL) { // The gtk_show_uri is available from GTK+ 2.14 -#ifdef INTERNAL_BUILD +#ifdef DEBUG fprintf (stderr, "The version of GTK is %s. " "The gtk_show_uri function is supported " "since GTK+ 2.14.\n", gtk_version); -#endif /* INTERNAL_BUILD */ +#endif /* DEBUG */ } else { // Loading symbols only if the GTK version is 2.14 and higher fp_gtk_show_uri = dl_symbol("gtk_show_uri"); const char *dlsym_error = dlerror(); if (dlsym_error) { -#ifdef INTERNAL_BUILD +#ifdef DEBUG fprintf (stderr, "Cannot load symbol: %s \n", dlsym_error); -#endif /* INTERNAL_BUILD */ +#endif /* DEBUG */ } else if (fp_gtk_show_uri == NULL) { -#ifdef INTERNAL_BUILD +#ifdef DEBUG fprintf(stderr, "dlsym(gtk_show_uri) returned NULL\n"); -#endif /* INTERNAL_BUILD */ +#endif /* DEBUG */ } else { update_supported_actions(env); success = TRUE; diff --git a/jdk/src/java.desktop/unix/native/libawt_xawt/xawt/XlibWrapper.c b/jdk/src/java.desktop/unix/native/libawt_xawt/xawt/XlibWrapper.c index f1d63185186..c40200e5c6c 100644 --- a/jdk/src/java.desktop/unix/native/libawt_xawt/xawt/XlibWrapper.c +++ b/jdk/src/java.desktop/unix/native/libawt_xawt/xawt/XlibWrapper.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,7 +49,7 @@ #include -#if defined(DEBUG) || defined(INTERNAL_BUILD) +#if defined(DEBUG) static jmethodID lockIsHeldMID = NULL; static void @@ -2346,4 +2346,3 @@ Java_sun_awt_X11_XlibWrapper_SetBitmapShape (*env)->ReleaseIntArrayElements(env, bitmap, values, JNI_ABORT); } - diff --git a/jdk/src/java.desktop/unix/native/libawt_xawt/xawt/gnome_interface.c b/jdk/src/java.desktop/unix/native/libawt_xawt/xawt/gnome_interface.c index 90d56de93d1..46c96e13680 100644 --- a/jdk/src/java.desktop/unix/native/libawt_xawt/xawt/gnome_interface.c +++ b/jdk/src/java.desktop/unix/native/libawt_xawt/xawt/gnome_interface.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ gboolean gnome_load() { // we are trying to load the library without a version suffix vfs_handle = dlopen(JNI_LIB_NAME("gnomevfs-2"), RTLD_LAZY); if (vfs_handle == NULL) { - #ifdef INTERNAL_BUILD + #ifdef DEBUG fprintf(stderr, "can not load libgnomevfs-2.so\n"); #endif return FALSE; @@ -51,13 +51,13 @@ gboolean gnome_load() { dlerror(); /* Clear errors */ gnome_vfs_init = (GNOME_VFS_INIT_TYPE*)dlsym(vfs_handle, "gnome_vfs_init"); if (gnome_vfs_init == NULL){ - #ifdef INTERNAL_BUILD + #ifdef DEBUG fprintf(stderr, "dlsym( gnome_vfs_init) returned NULL\n"); #endif return FALSE; } if ((errmsg = dlerror()) != NULL) { - #ifdef INTERNAL_BUILD + #ifdef DEBUG fprintf(stderr, "can not find symbol gnome_vfs_init %s \n", errmsg); #endif return FALSE; @@ -69,7 +69,7 @@ gboolean gnome_load() { if (gnome_handle == NULL) { gnome_handle = dlopen(JNI_LIB_NAME("gnome-2"), RTLD_LAZY); if (gnome_handle == NULL) { - #ifdef INTERNAL_BUILD + #ifdef DEBUG fprintf(stderr, "can not load libgnome-2.so\n"); #endif return FALSE; @@ -78,7 +78,7 @@ gboolean gnome_load() { dlerror(); /* Clear errors */ gnome_url_show = (GNOME_URL_SHOW_TYPE*)dlsym(gnome_handle, "gnome_url_show"); if ((errmsg = dlerror()) != NULL) { - #ifdef INTERNAL_BUILD + #ifdef DEBUG fprintf(stderr, "can not find symble gnome_url_show\n"); #endif return FALSE; diff --git a/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_sys.c b/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_sys.c index 85a93042f1d..ed3bfaa1108 100644 --- a/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_sys.c +++ b/jdk/src/java.desktop/unix/native/libsplashscreen/splashscreen_sys.c @@ -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 @@ -281,9 +281,7 @@ SplashCreateWindow(Splash * splash) { /* for changing the visible shape of a window to an nonrectangular form */ void SplashUpdateShape(Splash * splash) { - if (!shapeSupported) - return; - if (!splash->maskRequired) { + if (splash->currentFrame < 0 || !shapeSupported || !splash->maskRequired) { return; } XShapeCombineRectangles(splash->display, splash->window, ShapeClip, 0, 0, @@ -324,6 +322,10 @@ ByteOrderToX(int byteOrder) { void SplashRedrawWindow(Splash * splash) { + if (splash->currentFrame < 0) { + return; + } + XImage *ximage; // making this method redraw a part of the image does not make diff --git a/jdk/src/java.desktop/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java b/jdk/src/java.desktop/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java index 1f3e2c3e987..52d198f034c 100644 --- a/jdk/src/java.desktop/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java +++ b/jdk/src/java.desktop/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java @@ -41,6 +41,7 @@ import java.util.stream.Stream; import static sun.awt.shell.Win32ShellFolder2.*; import sun.awt.OSInfo; import sun.awt.util.ThreadGroupUtils; +import sun.misc.InnocuousThread; // NOTE: This class supersedes Win32ShellFolderManager, which was removed // from distribution after version 1.4.2. @@ -516,26 +517,22 @@ final class Win32ShellFolderManager2 extends ShellFolderManager { private static Thread comThread; private ComInvoker() { - super(1, 1, 0, TimeUnit.DAYS, new LinkedBlockingQueue()); + super(1, 1, 0, TimeUnit.DAYS, new LinkedBlockingQueue<>()); allowCoreThreadTimeOut(false); setThreadFactory(this); - final Runnable shutdownHook = new Runnable() { - public void run() { - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - shutdownNow(); - return null; - } - }); - } - }; - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - Runtime.getRuntime().addShutdownHook( - new Thread(shutdownHook) - ); - return null; + final Runnable shutdownHook = () -> AccessController.doPrivileged((PrivilegedAction) () -> { + shutdownNow(); + return null; + }); + AccessController.doPrivileged((PrivilegedAction) () -> { + Thread t; + if (System.getSecurityManager() == null) { + t = new Thread(ThreadGroupUtils.getRootThreadGroup(), shutdownHook); + } else { + t = new InnocuousThread(shutdownHook); } + Runtime.getRuntime().addShutdownHook(t); + return null; }); } @@ -550,17 +547,22 @@ final class Win32ShellFolderManager2 extends ShellFolderManager { } } }; - comThread = AccessController.doPrivileged((PrivilegedAction) () -> { - /* The thread must be a member of a thread group - * which will not get GCed before VM exit. - * Make its parent the top-level thread group. - */ - ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); - Thread thread = new Thread(rootTG, comRun, "Swing-Shell"); - thread.setDaemon(true); - return thread; - } - ); + comThread = AccessController.doPrivileged((PrivilegedAction) () -> { + String name = "Swing-Shell"; + Thread thread; + if (System.getSecurityManager() == null) { + /* The thread must be a member of a thread group + * which will not get GCed before VM exit. + * Make its parent the top-level thread group. + */ + thread = new Thread(ThreadGroupUtils.getRootThreadGroup(), comRun, name); + } else { + /* InnocuousThread is a member of a correct TG by default */ + thread = new InnocuousThread(comRun, name); + } + thread.setDaemon(true); + return thread; + }); return comThread; } diff --git a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WFileDialogPeer.java b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WFileDialogPeer.java index beeb1031332..81a28c6b7d3 100644 --- a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WFileDialogPeer.java +++ b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WFileDialogPeer.java @@ -36,6 +36,7 @@ import java.util.MissingResourceException; import java.util.Vector; import sun.awt.CausedFocusEvent; import sun.awt.AWTAccessor; +import sun.misc.ManagedLocalsThread; final class WFileDialogPeer extends WWindowPeer implements FileDialogPeer { @@ -97,12 +98,11 @@ final class WFileDialogPeer extends WWindowPeer implements FileDialogPeer { @Override public void show() { - new Thread(new Runnable() { - @Override - public void run() { - _show(); - } - }).start(); + if (System.getSecurityManager() == null) { + new Thread(this::_show).start(); + } else { + new ManagedLocalsThread(this::_show).start(); + } } @Override diff --git a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WPageDialogPeer.java b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WPageDialogPeer.java index 78a1c04cf12..7a146d965cd 100644 --- a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WPageDialogPeer.java +++ b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WPageDialogPeer.java @@ -25,6 +25,8 @@ package sun.awt.windows; +import sun.misc.ManagedLocalsThread; + final class WPageDialogPeer extends WPrintDialogPeer { WPageDialogPeer(WPageDialog target) { @@ -39,20 +41,22 @@ final class WPageDialogPeer extends WPrintDialogPeer { @Override public void show() { - new Thread(new Runnable() { - @Override - public void run() { - // Call pageSetup even with no printer installed, this - // will display Windows error dialog and return false. - try { - ((WPrintDialog)target).setRetVal(_show()); - } catch (Exception e) { - // No exception should be thrown by native dialog code, - // but if it is we need to trap it so the thread does - // not hide is called and the thread doesn't hang. - } - ((WPrintDialog)target).setVisible(false); - } - }).start(); + Runnable runnable = () -> { + // Call pageSetup even with no printer installed, this + // will display Windows error dialog and return false. + try { + ((WPrintDialog)target).setRetVal(_show()); + } catch (Exception e) { + // No exception should be thrown by native dialog code, + // but if it is we need to trap it so the thread does + // not hide is called and the thread doesn't hang. + } + ((WPrintDialog)target).setVisible(false); + }; + if (System.getSecurityManager() == null) { + new Thread(runnable).start(); + } else { + new ManagedLocalsThread(runnable).start(); + } } } diff --git a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WPrintDialogPeer.java b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WPrintDialogPeer.java index d1efab01404..2f728f18899 100644 --- a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WPrintDialogPeer.java +++ b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WPrintDialogPeer.java @@ -32,6 +32,7 @@ import java.awt.dnd.DropTarget; import java.util.Vector; import sun.awt.CausedFocusEvent; import sun.awt.AWTAccessor; +import sun.misc.ManagedLocalsThread; class WPrintDialogPeer extends WWindowPeer implements DialogPeer { @@ -67,19 +68,21 @@ class WPrintDialogPeer extends WWindowPeer implements DialogPeer { @Override public void show() { - new Thread(new Runnable() { - @Override - public void run() { - try { - ((WPrintDialog)target).setRetVal(_show()); - } catch (Exception e) { - // No exception should be thrown by native dialog code, - // but if it is we need to trap it so the thread does - // not hide is called and the thread doesn't hang. - } - ((WPrintDialog)target).setVisible(false); + Runnable runnable = () -> { + try { + ((WPrintDialog)target).setRetVal(_show()); + } catch (Exception e) { + // No exception should be thrown by native dialog code, + // but if it is we need to trap it so the thread does + // not hide is called and the thread doesn't hang. } - }).start(); + ((WPrintDialog)target).setVisible(false); + }; + if (System.getSecurityManager() == null) { + new Thread(runnable).start(); + } else { + new ManagedLocalsThread(runnable).start(); + } } synchronized void setHWnd(long hwnd) { diff --git a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WToolkit.java b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WToolkit.java index 7915982c95a..50207fd0f52 100644 --- a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WToolkit.java +++ b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WToolkit.java @@ -49,6 +49,7 @@ import sun.awt.datatransfer.DataTransferer; import sun.java2d.d3d.D3DRenderQueue; import sun.java2d.opengl.OGLRenderQueue; +import sun.misc.InnocuousThread; import sun.print.PrintJob2D; import java.awt.dnd.DragSource; @@ -247,11 +248,17 @@ public final class WToolkit extends SunToolkit implements Runnable { */ AWTAutoShutdown.notifyToolkitThreadBusy(); - // Find a root TG and attach Appkit thread to it + // Find a root TG and attach toolkit thread to it ThreadGroup rootTG = AccessController.doPrivileged( (PrivilegedAction) ThreadGroupUtils::getRootThreadGroup); if (!startToolkitThread(this, rootTG)) { - Thread toolkitThread = new Thread(rootTG, this, "AWT-Windows"); + String name = "AWT-Windows"; + Thread toolkitThread; + if (System.getSecurityManager() == null) { + toolkitThread = new Thread(rootTG, this, name); + } else { + toolkitThread = new InnocuousThread(this, name); + } toolkitThread.setDaemon(true); toolkitThread.start(); } @@ -278,7 +285,12 @@ public final class WToolkit extends SunToolkit implements Runnable { private void registerShutdownHook() { AccessController.doPrivileged((PrivilegedAction) () -> { - Thread shutdown = new Thread(ThreadGroupUtils.getRootThreadGroup(), this::shutdown); + Thread shutdown; + if (System.getSecurityManager() == null) { + shutdown = new Thread(ThreadGroupUtils.getRootThreadGroup(), this::shutdown); + } else { + shutdown = new InnocuousThread(this::shutdown); + } shutdown.setContextClassLoader(null); Runtime.getRuntime().addShutdownHook(shutdown); return null; diff --git a/jdk/src/java.desktop/windows/classes/sun/java2d/d3d/D3DScreenUpdateManager.java b/jdk/src/java.desktop/windows/classes/sun/java2d/d3d/D3DScreenUpdateManager.java index 1ab30124296..fd4bd592402 100644 --- a/jdk/src/java.desktop/windows/classes/sun/java2d/d3d/D3DScreenUpdateManager.java +++ b/jdk/src/java.desktop/windows/classes/sun/java2d/d3d/D3DScreenUpdateManager.java @@ -48,6 +48,7 @@ import sun.java2d.SurfaceData; import sun.java2d.windows.GDIWindowSurfaceData; import sun.java2d.d3d.D3DSurfaceData.D3DWindowSurfaceData; import sun.java2d.windows.WindowsFlags; +import sun.misc.InnocuousThread; /** * This class handles rendering to the screen with the D3D pipeline. @@ -92,22 +93,25 @@ public class D3DScreenUpdateManager extends ScreenUpdateManager public D3DScreenUpdateManager() { done = false; - AccessController.doPrivileged( - (PrivilegedAction) () -> { - ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); - Thread shutdown = new Thread(rootTG, () -> { - done = true; - wakeUpUpdateThread(); - }); - shutdown.setContextClassLoader(null); - try { - Runtime.getRuntime().addShutdownHook(shutdown); - } catch (Exception e) { - done = true; - } - return null; - } - ); + AccessController.doPrivileged((PrivilegedAction) () -> { + Runnable shutdownRunnable = () -> { + done = true; + wakeUpUpdateThread(); + }; + Thread shutdown; + if (System.getSecurityManager() == null) { + shutdown = new Thread(ThreadGroupUtils.getRootThreadGroup(), shutdownRunnable); + } else { + shutdown = new InnocuousThread(shutdownRunnable); + } + shutdown.setContextClassLoader(null); + try { + Runtime.getRuntime().addShutdownHook(shutdown); + } catch (Exception e) { + done = true; + } + return null; + }); } /** @@ -345,17 +349,21 @@ public class D3DScreenUpdateManager extends ScreenUpdateManager */ private synchronized void startUpdateThread() { if (screenUpdater == null) { - screenUpdater = AccessController.doPrivileged( - (PrivilegedAction) () -> { - ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup(); - Thread t = new Thread(rootTG, - D3DScreenUpdateManager.this, - "D3D Screen Updater"); - // REMIND: should it be higher? - t.setPriority(Thread.NORM_PRIORITY + 2); - t.setDaemon(true); - return t; - }); + screenUpdater = AccessController.doPrivileged((PrivilegedAction) () -> { + Thread t; + String name = "D3D Screen Updater"; + if (System.getSecurityManager() == null) { + t = new Thread(ThreadGroupUtils.getRootThreadGroup(), + D3DScreenUpdateManager.this, + name); + } else { + t = new InnocuousThread(D3DScreenUpdateManager.this, name); + } + // REMIND: should it be higher? + t.setPriority(Thread.NORM_PRIORITY + 2); + t.setDaemon(true); + return t; + }); screenUpdater.start(); } else { wakeUpUpdateThread(); diff --git a/jdk/src/java.desktop/windows/classes/sun/print/PrintServiceLookupProvider.java b/jdk/src/java.desktop/windows/classes/sun/print/PrintServiceLookupProvider.java index b3f56c8b55c..903673efdbf 100644 --- a/jdk/src/java.desktop/windows/classes/sun/print/PrintServiceLookupProvider.java +++ b/jdk/src/java.desktop/windows/classes/sun/print/PrintServiceLookupProvider.java @@ -25,6 +25,8 @@ package sun.print; +import sun.misc.ManagedLocalsThread; + import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; @@ -97,7 +99,12 @@ public class PrintServiceLookupProvider extends PrintServiceLookup { return; } // start the printer listener thread - PrinterChangeListener thr = new PrinterChangeListener(); + Thread thr; + if (System.getSecurityManager() == null) { + thr = new Thread(new PrinterChangeListener()); + } else { + thr = new ManagedLocalsThread(new PrinterChangeListener()); + } thr.setDaemon(true); thr.start(); } /* else condition ought to never happen! */ @@ -316,12 +323,13 @@ public class PrintServiceLookupProvider extends PrintServiceLookup { return defaultPrintService; } - class PrinterChangeListener extends Thread { + class PrinterChangeListener implements Runnable { long chgObj; PrinterChangeListener() { chgObj = notifyFirstPrinterChange(null); } + @Override public void run() { if (chgObj != -1) { while (true) { diff --git a/jdk/src/java.desktop/windows/native/libawt/windows/awt.h b/jdk/src/java.desktop/windows/native/libawt/windows/awt.h index 83c3fcbeb8f..0a84f65e0a5 100644 --- a/jdk/src/java.desktop/windows/native/libawt/windows/awt.h +++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt.h @@ -228,7 +228,7 @@ extern JavaVM *jvm; /* * checks if the current thread is/isn't the toolkit thread */ -#if defined(DEBUG) || defined(INTERNAL_BUILD) +#if defined(DEBUG) #define CHECK_IS_TOOLKIT_THREAD() \ if (GetCurrentThreadId() != AwtToolkit::MainThread()) \ { JNU_ThrowInternalError(env,"Operation is not permitted on non-toolkit thread!\n"); } diff --git a/jdk/src/java.desktop/windows/native/libawt/windows/awt_InputTextInfor.cpp b/jdk/src/java.desktop/windows/native/libawt/windows/awt_InputTextInfor.cpp index 4ccf0d55e3e..de9248f1372 100644 --- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_InputTextInfor.cpp +++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_InputTextInfor.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -310,6 +310,8 @@ int AwtInputTextInfor::GetClauseInfor(int*& lpBndClauseW, jstring*& lpReadingCla readingMergedClauseW = new jstring[cMergedClauseW]; } catch (std::bad_alloc&) { delete [] bndMergedClauseW; + delete [] bndClauseW; + delete [] readingClauseW; throw; } @@ -394,6 +396,8 @@ int AwtInputTextInfor::GetAttributeInfor(int*& lpBndAttrW, BYTE*& lpValAttrW) { valMergedAttrW = new BYTE[cMergedAttrW]; } catch (std::bad_alloc&) { delete [] bndMergedAttrW; + delete [] bndAttrW; + delete [] valAttrW; throw; } bndMergedAttrW[0] = 0; diff --git a/jdk/src/java.desktop/windows/native/libawt/windows/awt_TrayIcon.cpp b/jdk/src/java.desktop/windows/native/libawt/windows/awt_TrayIcon.cpp index 7952f1e7382..ef376f31a3b 100644 --- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_TrayIcon.cpp +++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_TrayIcon.cpp @@ -709,7 +709,7 @@ void AwtTrayIcon::SetToolTip(LPCTSTR tooltip) { if (tooltip == NULL) { m_nid.szTip[0] = '\0'; - } else if (lstrlen(tooltip) > TRAY_ICON_TOOLTIP_MAX_SIZE) { + } else if (lstrlen(tooltip) >= TRAY_ICON_TOOLTIP_MAX_SIZE) { _tcsncpy(m_nid.szTip, tooltip, TRAY_ICON_TOOLTIP_MAX_SIZE); m_nid.szTip[TRAY_ICON_TOOLTIP_MAX_SIZE - 1] = '\0'; } else { @@ -814,7 +814,7 @@ void AwtTrayIcon::DisplayMessage(LPCTSTR caption, LPCTSTR text, LPCTSTR msgType) if (caption[0] == '\0') { m_nid.szInfoTitle[0] = '\0'; - } else if (lstrlen(caption) > TRAY_ICON_BALLOON_TITLE_MAX_SIZE) { + } else if (lstrlen(caption) >= TRAY_ICON_BALLOON_TITLE_MAX_SIZE) { _tcsncpy(m_nid.szInfoTitle, caption, TRAY_ICON_BALLOON_TITLE_MAX_SIZE); m_nid.szInfoTitle[TRAY_ICON_BALLOON_TITLE_MAX_SIZE - 1] = '\0'; @@ -827,7 +827,7 @@ void AwtTrayIcon::DisplayMessage(LPCTSTR caption, LPCTSTR text, LPCTSTR msgType) m_nid.szInfo[0] = ' '; m_nid.szInfo[1] = '\0'; - } else if (lstrlen(text) > TRAY_ICON_BALLOON_INFO_MAX_SIZE) { + } else if (lstrlen(text) >= TRAY_ICON_BALLOON_INFO_MAX_SIZE) { _tcsncpy(m_nid.szInfo, text, TRAY_ICON_BALLOON_INFO_MAX_SIZE); m_nid.szInfo[TRAY_ICON_BALLOON_INFO_MAX_SIZE - 1] = '\0'; diff --git a/jdk/src/java.logging/share/classes/java/util/logging/LogManager.java b/jdk/src/java.logging/share/classes/java/util/logging/LogManager.java index b852d8ae78c..972b74a7efb 100644 --- a/jdk/src/java.logging/share/classes/java/util/logging/LogManager.java +++ b/jdk/src/java.logging/share/classes/java/util/logging/LogManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,8 +31,10 @@ import java.util.*; import java.security.*; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import sun.misc.JavaAWTAccess; +import sun.misc.ManagedLocalsThread; import sun.misc.SharedSecrets; /** @@ -247,7 +249,7 @@ public class LogManager { // This private class is used as a shutdown hook. // It does a "reset" to close all open handlers. - private class Cleaner extends Thread { + private class Cleaner extends ManagedLocalsThread { private Cleaner() { /* Set context class loader to null in order to avoid @@ -579,7 +581,8 @@ public class LogManager { // added in the user context. class LoggerContext { // Table of named Loggers that maps names to Loggers. - private final Hashtable namedLoggers = new Hashtable<>(); + private final ConcurrentHashMap namedLoggers = + new ConcurrentHashMap<>(); // Tree of named Loggers private final LogNode root; private LoggerContext() { @@ -642,21 +645,44 @@ public class LogManager { } - synchronized Logger findLogger(String name) { - // ensure that this context is properly initialized before - // looking for loggers. - ensureInitialized(); + Logger findLogger(String name) { + // Attempt to find logger without locking. LoggerWeakRef ref = namedLoggers.get(name); - if (ref == null) { - return null; + Logger logger = ref == null ? null : ref.get(); + + // if logger is not null, then we can return it right away. + // if name is "" or "global" and logger is null + // we need to fall through and check that this context is + // initialized. + // if ref is not null and logger is null we also need to + // fall through. + if (logger != null || (ref == null && !name.isEmpty() + && !name.equals(Logger.GLOBAL_LOGGER_NAME))) { + return logger; } - Logger logger = ref.get(); - if (logger == null) { - // Hashtable holds stale weak reference - // to a logger which has been GC-ed. - ref.dispose(); + + // We either found a stale reference, or we were looking for + // "" or "global" and didn't find them. + // Make sure context is initialized (has the default loggers), + // and look up again, cleaning the stale reference if it hasn't + // been cleaned up in between. All this needs to be done inside + // a synchronized block. + synchronized(this) { + // ensure that this context is properly initialized before + // looking for loggers. + ensureInitialized(); + ref = namedLoggers.get(name); + if (ref == null) { + return null; + } + logger = ref.get(); + if (logger == null) { + // The namedLoggers map holds stale weak reference + // to a logger which has been GC-ed. + ref.dispose(); + } + return logger; } - return logger; } // This method is called before adding a logger to the @@ -752,7 +778,6 @@ public class LogManager { final LogManager owner = getOwner(); logger.setLogManager(owner); ref = owner.new LoggerWeakRef(logger); - namedLoggers.put(name, ref); // Apply any initial level defined for the new logger, unless // the logger's level is already initialized @@ -789,10 +814,17 @@ public class LogManager { node.walkAndSetParent(logger); // new LogNode is ready so tell the LoggerWeakRef about it ref.setNode(node); + + // Do not publish 'ref' in namedLoggers before the logger tree + // is fully updated - because the named logger will be visible as + // soon as it is published in namedLoggers (findLogger takes + // benefit of the ConcurrentHashMap implementation of namedLoggers + // to avoid synchronizing on retrieval when that is possible). + namedLoggers.put(name, ref); return true; } - synchronized void removeLoggerRef(String name, LoggerWeakRef ref) { + void removeLoggerRef(String name, LoggerWeakRef ref) { namedLoggers.remove(name, ref); } @@ -800,7 +832,7 @@ public class LogManager { // ensure that this context is properly initialized before // returning logger names. ensureInitialized(); - return namedLoggers.keys(); + return Collections.enumeration(namedLoggers.keySet()); } // If logger.getUseParentHandlers() returns 'true' and any of the logger's @@ -1379,7 +1411,19 @@ public class LogManager { reset(); // Load the properties - props.load(ins); + try { + props.load(ins); + } catch (IllegalArgumentException x) { + // props.load may throw an IllegalArgumentException if the stream + // contains malformed Unicode escape sequences. + // We wrap that in an IOException as readConfiguration is + // specified to throw IOException if there are problems reading + // from the stream. + // Note: new IOException(x.getMessage(), x) allow us to get a more + // concise error message than new IOException(x); + throw new IOException(x.getMessage(), x); + } + // Instantiate new configuration objects. String names[] = parseClassNames("config"); diff --git a/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientCommunicatorAdmin.java b/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientCommunicatorAdmin.java index b8549f255a9..85f248311cb 100644 --- a/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientCommunicatorAdmin.java +++ b/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientCommunicatorAdmin.java @@ -30,6 +30,7 @@ import java.io.InterruptedIOException; import com.sun.jmx.remote.util.ClassLogger; import com.sun.jmx.remote.util.EnvHelp; +import sun.misc.ManagedLocalsThread; public abstract class ClientCommunicatorAdmin { private static volatile long threadNo = 1; @@ -40,7 +41,11 @@ public abstract class ClientCommunicatorAdmin { if (period > 0) { checker = new Checker(); - Thread t = new Thread(checker, "JMX client heartbeat " + ++threadNo); + Thread t = new ManagedLocalsThread( + checker, + "JMX client heartbeat " + (++threadNo) + ); + t.setDaemon(true); t.start(); } else diff --git a/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java b/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java index 4d3ba6db0d8..05abd0ceeb5 100644 --- a/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java +++ b/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java @@ -52,6 +52,7 @@ import javax.management.remote.TargetedNotification; import com.sun.jmx.remote.util.ClassLogger; import com.sun.jmx.remote.util.EnvHelp; import java.rmi.UnmarshalException; +import sun.misc.ManagedLocalsThread; public abstract class ClientNotifForwarder { @@ -90,10 +91,8 @@ public abstract class ClientNotifForwarder { throw new IllegalArgumentException("More than one command"); this.command = command; if (thread == null) { - thread = new Thread() { - - @Override - public void run() { + thread = new ManagedLocalsThread( + ()-> { while (true) { Runnable r; synchronized (LinearExecutor.this) { @@ -107,10 +106,10 @@ public abstract class ClientNotifForwarder { } r.run(); } - } - }; + }, + "ClientNotifForwarder-" + ++threadId + ); thread.setDaemon(true); - thread.setName("ClientNotifForwarder-" + ++threadId); thread.start(); } } diff --git a/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerCommunicatorAdmin.java b/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerCommunicatorAdmin.java index bb09f62bdb9..f943bf5ce68 100644 --- a/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerCommunicatorAdmin.java +++ b/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerCommunicatorAdmin.java @@ -25,9 +25,9 @@ package com.sun.jmx.remote.internal; -import java.io.IOException; import com.sun.jmx.remote.util.ClassLogger; +import sun.misc.ManagedLocalsThread; public abstract class ServerCommunicatorAdmin { public ServerCommunicatorAdmin(long timeout) { @@ -42,7 +42,7 @@ public abstract class ServerCommunicatorAdmin { timestamp = 0; if (timeout < Long.MAX_VALUE) { Runnable timeoutTask = new Timeout(); - final Thread t = new Thread(timeoutTask); + final Thread t = new ManagedLocalsThread(timeoutTask); t.setName("JMX server connection timeout " + t.getId()); // If you change this name you will need to change a unit test // (NoServerTimeoutTest) diff --git a/jdk/src/java.management/share/classes/com/sun/management/DiagnosticCommandMBean.java b/jdk/src/java.management/share/classes/com/sun/management/DiagnosticCommandMBean.java index 93f741e7cc0..1d2a85e62b2 100644 --- a/jdk/src/java.management/share/classes/com/sun/management/DiagnosticCommandMBean.java +++ b/jdk/src/java.management/share/classes/com/sun/management/DiagnosticCommandMBean.java @@ -31,7 +31,7 @@ import javax.management.DynamicMBean; /** * Management interface for the diagnostic commands for the HotSpot Virtual Machine. * - *

                                The {code DiagnosticCommandMBean} is registered to the + *

                                The {@code DiagnosticCommandMBean} is registered to the * {@linkplain java.lang.management.ManagementFactory#getPlatformMBeanServer * platform MBeanServer} as are other platform MBeans. * @@ -93,7 +93,7 @@ import javax.management.DynamicMBean; * returns the diagnostic command description * (the same as the one return in the 'help' command) *

                              • {@link javax.management.MBeanOperationInfo#getImpact() getImpact()} - * returns ACTION_INFO
                              • + * returns {@code ACTION_INFO} *
                              • {@link javax.management.MBeanOperationInfo#getReturnType() getReturnType()} * returns {@code java.lang.String}
                              • *
                              • {@link javax.management.MBeanOperationInfo#getDescriptor() getDescriptor()} @@ -105,7 +105,6 @@ import javax.management.DynamicMBean; * meta-data for a JMX element. A field is a name and an associated value. * The additional meta-data provided for an operation associated with a * diagnostic command are described in the table below: - *

                                * *

                              • * @@ -161,7 +160,6 @@ import javax.management.DynamicMBean; * arguments supported by the diagnostic command (see below) * *
                                - *

                                * *

                                The description of parameters (options or arguments) of a diagnostic * command is provided within a Descriptor instance. In this Descriptor, diff --git a/jdk/src/java.management/share/classes/com/sun/management/GarbageCollectionNotificationInfo.java b/jdk/src/java.management/share/classes/com/sun/management/GarbageCollectionNotificationInfo.java index 5546f55d05e..68e88b79544 100644 --- a/jdk/src/java.management/share/classes/com/sun/management/GarbageCollectionNotificationInfo.java +++ b/jdk/src/java.management/share/classes/com/sun/management/GarbageCollectionNotificationInfo.java @@ -41,14 +41,14 @@ import sun.management.GarbageCollectionNotifInfoCompositeData; * when the Java virtual machine completes a garbage collection action * The notification emitted will contain the garbage collection notification * information about the status of the memory: - * + *

                                  *
                                • The name of the garbage collector used to perform the collection.
                                • *
                                • The action performed by the garbage collector.
                                • *
                                • The cause of the garbage collection action.
                                • *
                                • A {@link GcInfo} object containing some statistics about the GC cycle (start time, end time) and the memory usage before and after the GC cycle.
                                • - * + *
                                * *

                                * A {@link CompositeData CompositeData} representing @@ -81,7 +81,7 @@ import sun.management.GarbageCollectionNotifInfoCompositeData; *

                              • A {@linkplain #GARBAGE_COLLECTION_NOTIFICATION garbage collection notification}. *
                                Used by every notification emitted by the garbage collector, the details about * the notification are provided in the {@linkplain #getGcAction action} String - *

                              • + * *
                              **/ diff --git a/jdk/src/java.management/share/classes/com/sun/management/GcInfo.java b/jdk/src/java.management/share/classes/com/sun/management/GcInfo.java index 7257b6c6f62..5dc732d84f8 100644 --- a/jdk/src/java.management/share/classes/com/sun/management/GcInfo.java +++ b/jdk/src/java.management/share/classes/com/sun/management/GcInfo.java @@ -52,13 +52,13 @@ import sun.management.GcInfoBuilder; *
                          * *

                          - * GcInfo is a {@link CompositeData CompositeData} + * {@code GcInfo} is a {@link CompositeData CompositeData} * The GC-specific attributes can be obtained via the CompositeData * interface. This is a historical relic, and other classes should * not copy this pattern. Use {@link CompositeDataView} instead. * *

                          MXBean Mapping

                          - * GcInfo is mapped to a {@link CompositeData CompositeData} + * {@code GcInfo} is mapped to a {@link CompositeData CompositeData} * with attributes as specified in the {@link #from from} method. * * @author Mandy Chung @@ -152,11 +152,11 @@ public class GcInfo implements CompositeData, CompositeDataView { * Returns the memory usage of all memory pools * at the beginning of this GC. * This method returns - * a Map of the name of a memory pool + * a {@code Map} of the name of a memory pool * to the memory usage of the corresponding * memory pool before GC starts. * - * @return a Map of memory pool names to the memory + * @return a {@code Map} of memory pool names to the memory * usage of a memory pool before GC starts. */ public Map getMemoryUsageBeforeGc() { @@ -167,11 +167,11 @@ public class GcInfo implements CompositeData, CompositeDataView { * Returns the memory usage of all memory pools * at the end of this GC. * This method returns - * a Map of the name of a memory pool + * a {@code Map} of the name of a memory pool * to the memory usage of the corresponding * memory pool when GC finishes. * - * @return a Map of memory pool names to the memory + * @return a {@code Map} of memory pool names to the memory * usage of a memory pool when GC finishes. */ public Map getMemoryUsageAfterGc() { @@ -179,12 +179,11 @@ public class GcInfo implements CompositeData, CompositeDataView { } /** - * Returns a GcInfo object represented by the - * given CompositeData. The given - * CompositeData must contain + * Returns a {@code GcInfo} object represented by the + * given {@code CompositeData}. The given + * {@code CompositeData} must contain * all the following attributes: * - *

                          *

                          * * @@ -193,33 +192,33 @@ public class GcInfo implements CompositeData, CompositeDataView { * * * - * + * * * * - * + * * * * - * + * * * * - * + * * * * - * + * * *
                          indexjava.lang.Long{@code java.lang.Long}
                          startTimejava.lang.Long{@code java.lang.Long}
                          endTimejava.lang.Long{@code java.lang.Long}
                          memoryUsageBeforeGcjavax.management.openmbean.TabularData{@code javax.management.openmbean.TabularData}
                          memoryUsageAfterGcjavax.management.openmbean.TabularData{@code javax.management.openmbean.TabularData}
                          *
                          * - * @throws IllegalArgumentException if cd does not - * represent a GcInfo object with the attributes + * @throws IllegalArgumentException if {@code cd} does not + * represent a {@code GcInfo} object with the attributes * described above. * - * @return a GcInfo object represented by cd - * if cd is not null; null otherwise. + * @return a {@code GcInfo} object represented by {@code cd} + * if {@code cd} is not {@code null}; {@code null} otherwise. */ public static GcInfo from(CompositeData cd) { if (cd == null) { @@ -272,7 +271,7 @@ public class GcInfo implements CompositeData, CompositeDataView { } /** - *

                          Return the {@code CompositeData} representation of this + * Return the {@code CompositeData} representation of this * {@code GcInfo}, including any GC-specific attributes. The * returned value will have at least all the attributes described * in the {@link #from(CompositeData) from} method, plus optionally diff --git a/jdk/src/java.management/share/classes/com/sun/management/VMOption.java b/jdk/src/java.management/share/classes/com/sun/management/VMOption.java index 9c66af1ef5b..b1ba961923d 100644 --- a/jdk/src/java.management/share/classes/com/sun/management/VMOption.java +++ b/jdk/src/java.management/share/classes/com/sun/management/VMOption.java @@ -42,10 +42,10 @@ import javax.management.openmbean.CompositeData; * be set dynamically via a management interface after * the VM was started. * - * A VMOption contains the value of a VM option - * and the origin of that value at the time this VMOption + * A {@code VMOption} contains the value of a VM option + * and the origin of that value at the time this {@code VMOption} * object was constructed. The value of the VM option - * may be changed after the VMOption object was constructed, + * may be changed after the {@code VMOption} object was constructed, * * @see * Java Virtual Machine @@ -108,15 +108,15 @@ public class VMOption { } /** - * Constructs a VMOption. + * Constructs a {@code VMOption}. * * @param name Name of a VM option. * @param value Value of a VM option. - * @param writeable true if a VM option can be set dynamically, - * or false otherwise. + * @param writeable {@code true} if a VM option can be set dynamically, + * or {@code false} otherwise. * @param origin where the value of a VM option came from. * - * @throws NullPointerException if the name or value is null + * @throws NullPointerException if the name or value is {@code null} */ public VMOption(String name, String value, boolean writeable, Origin origin) { this.name = name; @@ -126,7 +126,7 @@ public class VMOption { } /** - * Constructs a VMOption object from a + * Constructs a {@code VMOption} object from a * {@link CompositeData CompositeData}. */ private VMOption(CompositeData cd) { @@ -150,10 +150,10 @@ public class VMOption { /** * Returns the value of this VM option at the time when - * this VMOption was created. The value could have been changed. + * this {@code VMOption} was created. The value could have been changed. * * @return the value of the VM option at the time when - * this VMOption was created. + * this {@code VMOption} was created. */ public String getValue() { return value; @@ -174,7 +174,7 @@ public class VMOption { * it can be set by the {@link HotSpotDiagnosticMXBean#setVMOption * HotSpotDiagnosticMXBean.setVMOption} method. * - * @return true if this VM option is writeable; false + * @return {@code true} if this VM option is writeable; {@code false} * otherwise. */ public boolean isWriteable() { @@ -189,10 +189,10 @@ public class VMOption { } /** - * Returns a VMOption object represented by the - * given CompositeData. The given CompositeData + * Returns a {@code VMOption} object represented by the + * given {@code CompositeData}. The given {@code CompositeData} * must contain the following attributes: - *

                          + * *

                          * * @@ -201,32 +201,32 @@ public class VMOption { * * * - * + * * * * - * + * * * * - * + * * * * - * + * * *
                          namejava.lang.String{@code java.lang.String}
                          valuejava.lang.String{@code java.lang.String}
                          originjava.lang.String{@code java.lang.String}
                          writeablejava.lang.Boolean{@code java.lang.Boolean}
                          *
                          * - * @param cd CompositeData representing a VMOption + * @param cd {@code CompositeData} representing a {@code VMOption} * - * @throws IllegalArgumentException if cd does not - * represent a VMOption with the attributes described + * @throws IllegalArgumentException if {@code cd} does not + * represent a {@code VMOption} with the attributes described * above. * - * @return a VMOption object represented by cd - * if cd is not null; - * null otherwise. + * @return a {@code VMOption} object represented by {@code cd} + * if {@code cd} is not {@code null}; + * {@code null} otherwise. */ public static VMOption from(CompositeData cd) { if (cd == null) { diff --git a/jdk/src/java.management/share/classes/javax/management/AttributeValueExp.java b/jdk/src/java.management/share/classes/javax/management/AttributeValueExp.java index f2d6f7684db..66475a899bf 100644 --- a/jdk/src/java.management/share/classes/javax/management/AttributeValueExp.java +++ b/jdk/src/java.management/share/classes/javax/management/AttributeValueExp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -93,11 +93,10 @@ public class AttributeValueExp implements ValueExp { * * @return The ValueExp. * - * @exception BadAttributeValueExpException - * @exception InvalidApplicationException - * @exception BadStringOperationException - * @exception BadBinaryOpValueExpException - * + * @throws BadStringOperationException {@inheritDoc} + * @throws BadBinaryOpValueExpException {@inheritDoc} + * @throws BadAttributeValueExpException {@inheritDoc} + * @throws InvalidApplicationException {@inheritDoc} */ @Override public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, diff --git a/jdk/src/java.management/share/classes/javax/management/DescriptorKey.java b/jdk/src/java.management/share/classes/javax/management/DescriptorKey.java index c9bd8b2963c..814e234d35c 100644 --- a/jdk/src/java.management/share/classes/javax/management/DescriptorKey.java +++ b/jdk/src/java.management/share/classes/javax/management/DescriptorKey.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -168,5 +168,9 @@ import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface DescriptorKey { + /** + * Returns the descriptor key. + * @return the descriptor key + */ String value(); } diff --git a/jdk/src/java.management/share/classes/javax/management/DynamicMBean.java b/jdk/src/java.management/share/classes/javax/management/DynamicMBean.java index 80e3007e7fd..129fb99a3f5 100644 --- a/jdk/src/java.management/share/classes/javax/management/DynamicMBean.java +++ b/jdk/src/java.management/share/classes/javax/management/DynamicMBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,7 +43,7 @@ public interface DynamicMBean { * * @return The value of the attribute retrieved. * - * @exception AttributeNotFoundException + * @exception AttributeNotFoundException if specified attribute does not exist or cannot be retrieved * @exception MBeanException Wraps a java.lang.Exception thrown by the MBean's getter. * @exception ReflectionException Wraps a java.lang.Exception thrown while trying to invoke the getter. * @@ -58,8 +58,8 @@ public interface DynamicMBean { * @param attribute The identification of the attribute to * be set and the value it is to be set to. * - * @exception AttributeNotFoundException - * @exception InvalidAttributeValueException + * @exception AttributeNotFoundException if specified attribute does not exist or cannot be retrieved + * @exception InvalidAttributeValueException if value specified is not valid for the attribute * @exception MBeanException Wraps a java.lang.Exception thrown by the MBean's setter. * @exception ReflectionException Wraps a java.lang.Exception thrown while trying to invoke the MBean's setter. * diff --git a/jdk/src/java.management/share/classes/javax/management/ImmutableDescriptor.java b/jdk/src/java.management/share/classes/javax/management/ImmutableDescriptor.java index 60e75fab315..eb0a02d41dd 100644 --- a/jdk/src/java.management/share/classes/javax/management/ImmutableDescriptor.java +++ b/jdk/src/java.management/share/classes/javax/management/ImmutableDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -65,6 +65,8 @@ public class ImmutableDescriptor implements Descriptor { /** * Construct a descriptor containing the given fields and values. * + * @param fieldNames the field names + * @param fieldValues the field values * @throws IllegalArgumentException if either array is null, or * if the arrays have different sizes, or * if a field name is null or empty, or if the same field name @@ -81,6 +83,7 @@ public class ImmutableDescriptor implements Descriptor { * is {@code a=b=c} then the field name is {@code a} and its value * is {@code b=c}. * + * @param fields the field names * @throws IllegalArgumentException if the parameter is null, or * if a field name is empty, or if the same field name appears * more than once, or if one of the strings does not contain @@ -94,6 +97,7 @@ public class ImmutableDescriptor implements Descriptor { *

                          Construct a descriptor where the names and values of the fields * are the keys and values of the given Map.

                          * + * @param fields the field names and values * @throws IllegalArgumentException if the parameter is null, or * if a field name is null or empty, or if the same field name appears * more than once (which can happen because field names are not case diff --git a/jdk/src/java.management/share/classes/javax/management/QueryExp.java b/jdk/src/java.management/share/classes/javax/management/QueryExp.java index e4f76577a6f..819855ee5e4 100644 --- a/jdk/src/java.management/share/classes/javax/management/QueryExp.java +++ b/jdk/src/java.management/share/classes/javax/management/QueryExp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,10 +53,13 @@ public interface QueryExp extends Serializable { * * @return True if the query was successfully applied to the MBean, false otherwise * - * @exception BadStringOperationException - * @exception BadBinaryOpValueExpException - * @exception BadAttributeValueExpException - * @exception InvalidApplicationException + * @throws BadStringOperationException when an invalid string + * operation is passed to a method for constructing a query + * @throws BadBinaryOpValueExpException when an invalid expression + * is passed to a method for constructing a query + * @throws BadAttributeValueExpException when an invalid MBean + * attribute is passed to a query constructing method + * @throws InvalidApplicationException when an invalid apply is attempted */ public boolean apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException ; diff --git a/jdk/src/java.management/share/classes/javax/management/StandardEmitterMBean.java b/jdk/src/java.management/share/classes/javax/management/StandardEmitterMBean.java index 250d109679a..c4ead04d5f4 100644 --- a/jdk/src/java.management/share/classes/javax/management/StandardEmitterMBean.java +++ b/jdk/src/java.management/share/classes/javax/management/StandardEmitterMBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -91,6 +91,7 @@ public class StandardEmitterMBean extends StandardMBean * that will have no effect on this object's * {@code getNotificationInfo()}.

                          * + * @param the implementation type of the MBean * @param implementation the implementation of the MBean interface. * @param mbeanInterface a Standard MBean interface. * @param emitter the object that will handle notifications. @@ -129,6 +130,7 @@ public class StandardEmitterMBean extends StandardMBean * that will have no effect on this object's * {@code getNotificationInfo()}.

                          * + * @param the implementation type of the MBean * @param implementation the implementation of the MBean interface. * @param mbeanInterface a Standard MBean interface. * @param isMXBean If true, the {@code mbeanInterface} parameter diff --git a/jdk/src/java.management/share/classes/javax/management/StringValueExp.java b/jdk/src/java.management/share/classes/javax/management/StringValueExp.java index 629117fb228..ed9b3c3539e 100644 --- a/jdk/src/java.management/share/classes/javax/management/StringValueExp.java +++ b/jdk/src/java.management/share/classes/javax/management/StringValueExp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -95,11 +95,12 @@ public class StringValueExp implements ValueExp { * * @return The ValueExp. * - * @exception BadStringOperationException - * @exception BadBinaryOpValueExpException - * @exception BadAttributeValueExpException - * @exception InvalidApplicationException + * @throws BadStringOperationException {@inheritDoc} + * @throws BadBinaryOpValueExpException {@inheritDoc} + * @throws BadAttributeValueExpException {@inheritDoc} + * @throws InvalidApplicationException {@inheritDoc} */ + @Override public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException { return this; diff --git a/jdk/src/java.management/share/classes/javax/management/ValueExp.java b/jdk/src/java.management/share/classes/javax/management/ValueExp.java index 7a0619122de..1afe1b6a44f 100644 --- a/jdk/src/java.management/share/classes/javax/management/ValueExp.java +++ b/jdk/src/java.management/share/classes/javax/management/ValueExp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. * 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,10 +80,13 @@ public interface ValueExp extends java.io.Serializable { * * @return The ValueExp. * - * @exception BadStringOperationException - * @exception BadBinaryOpValueExpException - * @exception BadAttributeValueExpException - * @exception InvalidApplicationException + * @throws BadStringOperationException when an invalid string + * operation is passed to a method for constructing a query + * @throws BadBinaryOpValueExpException when an invalid expression + * is passed to a method for constructing a query + * @throws BadAttributeValueExpException when an invalid MBean + * attribute is passed to a query constructing method + * @throws InvalidApplicationException when an invalid apply is attempted */ public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, diff --git a/jdk/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanInfo.java b/jdk/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanInfo.java index 8894ae882f7..642cddd3d27 100644 --- a/jdk/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanInfo.java +++ b/jdk/src/java.management/share/classes/javax/management/modelmbean/ModelMBeanInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -307,6 +307,7 @@ public interface ModelMBeanInfo /** * Creates and returns a copy of this object. + * @return a copy of this object */ public java.lang.Object clone(); diff --git a/jdk/src/java.management/share/classes/javax/management/monitor/Monitor.java b/jdk/src/java.management/share/classes/javax/management/monitor/Monitor.java index bf89b06cb9f..6276fb33b50 100644 --- a/jdk/src/java.management/share/classes/javax/management/monitor/Monitor.java +++ b/jdk/src/java.management/share/classes/javax/management/monitor/Monitor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -61,6 +61,7 @@ import javax.management.NotificationBroadcasterSupport; import javax.management.ObjectName; import javax.management.ReflectionException; import static javax.management.monitor.MonitorNotification.*; +import sun.misc.ManagedLocalsThread; /** * Defines the part common to all monitor MBeans. @@ -386,7 +387,7 @@ public abstract class Monitor * * @return The name of the monitor MBean registered. * - * @exception Exception + * @exception Exception if something goes wrong */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { @@ -415,7 +416,7 @@ public abstract class Monitor *

                          * Stops the monitor. * - * @exception Exception + * @exception Exception if something goes wrong */ public void preDeregister() throws Exception { @@ -1636,12 +1637,12 @@ public abstract class Monitor } public Thread newThread(Runnable r) { - Thread t = new Thread(group, - r, - namePrefix + - threadNumber.getAndIncrement() + - nameSuffix, - 0); + Thread t = new ManagedLocalsThread( + group, + r, + namePrefix + threadNumber.getAndIncrement() + nameSuffix + ); + t.setDaemon(true); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); diff --git a/jdk/src/java.management/share/classes/javax/management/openmbean/ArrayType.java b/jdk/src/java.management/share/classes/javax/management/openmbean/ArrayType.java index 2d12347044a..53665e8f2f9 100644 --- a/jdk/src/java.management/share/classes/javax/management/openmbean/ArrayType.java +++ b/jdk/src/java.management/share/classes/javax/management/openmbean/ArrayType.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -793,6 +793,7 @@ public class ArrayType extends OpenType { * array type description = 3-dimension array of java.lang.String * }

                          * + * @param the Java type that described instances must have * @param elementType the open type of element values contained * in the arrays described by this ArrayType * instance; must be an instance of either @@ -800,7 +801,7 @@ public class ArrayType extends OpenType { * TabularType or another ArrayType * with a SimpleType, CompositeType * or TabularType as its elementType. - * + * @return an {@code ArrayType} instance * @throws OpenDataException if elementType's className is not * one of the allowed Java class names for open * data. @@ -834,12 +835,14 @@ public class ArrayType extends OpenType { * array type description = 3-dimension array of int * } * + * @param the Java type that described instances must have * @param arrayClass a primitive array class such as {@code int[].class}, * {@code boolean[][].class}, etc. The {@link * #getElementOpenType()} method of the returned * {@code ArrayType} returns the {@link SimpleType} * corresponding to the wrapper type of the primitive * type of the array. + * @return an {@code ArrayType} instance * * @throws IllegalArgumentException if arrayClass is not * a primitive array. diff --git a/jdk/src/java.management/share/classes/javax/management/timer/Timer.java b/jdk/src/java.management/share/classes/javax/management/timer/Timer.java index 461b68e0dbd..b199e8e258a 100644 --- a/jdk/src/java.management/share/classes/javax/management/timer/Timer.java +++ b/jdk/src/java.management/share/classes/javax/management/timer/Timer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -195,7 +195,7 @@ public class Timer extends NotificationBroadcasterSupport * * @return The name of the timer MBean registered. * - * @exception java.lang.Exception + * @exception java.lang.Exception if something goes wrong */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws java.lang.Exception { @@ -217,7 +217,7 @@ public class Timer extends NotificationBroadcasterSupport *

                          * Stops the timer. * - * @exception java.lang.Exception + * @exception java.lang.Exception if something goes wrong */ public void preDeregister() throws java.lang.Exception { diff --git a/jdk/src/java.management/share/classes/sun/management/jdp/JdpController.java b/jdk/src/java.management/share/classes/sun/management/jdp/JdpController.java index a22873a0700..a90705d577a 100644 --- a/jdk/src/java.management/share/classes/sun/management/jdp/JdpController.java +++ b/jdk/src/java.management/share/classes/sun/management/jdp/JdpController.java @@ -34,6 +34,7 @@ import java.lang.management.RuntimeMXBean; import java.lang.reflect.Field; import java.lang.reflect.Method; import sun.management.VMManagement; +import sun.misc.ManagedLocalsThread; /** * JdpController is responsible to create and manage a broadcast loop @@ -219,7 +220,7 @@ public final class JdpController { controller = new JDPControllerRunner(bcast, packet, pause); - Thread t = new Thread(controller, "JDP broadcaster"); + Thread t = new ManagedLocalsThread(controller, "JDP broadcaster"); t.setDaemon(true); t.start(); } diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapURL.java b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapURL.java index 40b2b56cf42..5abbc9de0e8 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapURL.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapURL.java @@ -26,9 +26,6 @@ package com.sun.jndi.ldap; import javax.naming.*; -import javax.naming.directory.*; -import javax.naming.spi.*; -import java.net.URL; import java.net.MalformedURLException; import java.io.UnsupportedEncodingException; import java.util.StringTokenizer; @@ -211,44 +208,53 @@ final public class LdapURL extends Uri { // query begins with a '?' or is null - if (query == null) { + if (query == null || query.length() < 2) { return; } - int qmark2 = query.indexOf('?', 1); + int currentIndex = 1; + int nextQmark; + int endIndex; - if (qmark2 < 0) { - attributes = query.substring(1); + // attributes: + nextQmark = query.indexOf('?', currentIndex); + endIndex = nextQmark == -1 ? query.length() : nextQmark; + if (endIndex - currentIndex > 0) { + attributes = query.substring(currentIndex, endIndex); + } + currentIndex = endIndex + 1; + if (currentIndex >= query.length()) { return; - } else if (qmark2 != 1) { - attributes = query.substring(1, qmark2); } - int qmark3 = query.indexOf('?', qmark2 + 1); - - if (qmark3 < 0) { - scope = query.substring(qmark2 + 1); + // scope: + nextQmark = query.indexOf('?', currentIndex); + endIndex = nextQmark == -1 ? query.length() : nextQmark; + if (endIndex - currentIndex > 0) { + scope = query.substring(currentIndex, endIndex); + } + currentIndex = endIndex + 1; + if (currentIndex >= query.length()) { return; - } else if (qmark3 != qmark2 + 1) { - scope = query.substring(qmark2 + 1, qmark3); } - int qmark4 = query.indexOf('?', qmark3 + 1); - - if (qmark4 < 0) { - filter = query.substring(qmark3 + 1); - } else { - if (qmark4 != qmark3 + 1) { - filter = query.substring(qmark3 + 1, qmark4); - } - extensions = query.substring(qmark4 + 1); - if (extensions.length() > 0) { - extensions = UrlUtil.decode(extensions, "UTF8"); - } - } - if (filter != null && filter.length() > 0) { + // filter: + nextQmark = query.indexOf('?', currentIndex); + endIndex = nextQmark == -1 ? query.length() : nextQmark; + if (endIndex - currentIndex > 0) { + filter = query.substring(currentIndex, endIndex); filter = UrlUtil.decode(filter, "UTF8"); } + currentIndex = endIndex + 1; + if (currentIndex >= query.length()) { + return; + } + + // extensions: + if (query.length() - currentIndex > 0) { + extensions = query.substring(currentIndex); + extensions = UrlUtil.decode(extensions, "UTF8"); + } } /* diff --git a/jdk/src/java.prefs/macosx/classes/java/util/prefs/MacOSXPreferencesFile.java b/jdk/src/java.prefs/macosx/classes/java/util/prefs/MacOSXPreferencesFile.java index 6553ff6ed78..dc54a0d539b 100644 --- a/jdk/src/java.prefs/macosx/classes/java/util/prefs/MacOSXPreferencesFile.java +++ b/jdk/src/java.prefs/macosx/classes/java/util/prefs/MacOSXPreferencesFile.java @@ -31,6 +31,7 @@ import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import java.lang.ref.WeakReference; +import sun.misc.ManagedLocalsThread; /* @@ -343,7 +344,7 @@ class MacOSXPreferencesFile { { if (timer == null) { timer = new Timer(true); // daemon - Thread flushThread = new Thread() { + Thread flushThread = new ManagedLocalsThread() { @Override public void run() { flushWorld(); diff --git a/jdk/src/java.prefs/share/classes/java/util/prefs/AbstractPreferences.java b/jdk/src/java.prefs/share/classes/java/util/prefs/AbstractPreferences.java index a840dffab95..970aa19816d 100644 --- a/jdk/src/java.prefs/share/classes/java/util/prefs/AbstractPreferences.java +++ b/jdk/src/java.prefs/share/classes/java/util/prefs/AbstractPreferences.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. * 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,6 +29,7 @@ import java.util.*; import java.io.*; import java.security.AccessController; import java.security.PrivilegedAction; +import sun.misc.ManagedLocalsThread; // These imports needed only as a workaround for a JavaDoc bug import java.lang.Integer; import java.lang.Long; @@ -77,10 +78,9 @@ import java.lang.Double; * under which these calls cannot even enqueue the requested operation for * later processing. Even under these circumstances it is generally better to * simply ignore the invocation and return, rather than throwing an - * exception. Under these circumstances, however, all subsequent invocations - * of flush() and sync should return false, as - * returning true would imply that all previous operations had - * successfully been made permanent. + * exception. Under these circumstances, however, subsequently invoking + * flush() or sync would not imply that all previous + * operations had successfully been made permanent. * *

                          There is one circumstance under which putSpi, removeSpi and * childSpi should throw an exception: if the caller lacks @@ -121,6 +121,13 @@ import java.lang.Double; * @since 1.4 */ public abstract class AbstractPreferences extends Preferences { + /** + * The code point U+0000, assigned to the null control character, is the + * only character encoded in Unicode and ISO/IEC 10646 that is always + * invalid in any XML 1.0 and 1.1 document. + */ + static final int CODE_POINT_U0000 = '\u0000'; + /** * Our name relative to parent. */ @@ -233,6 +240,8 @@ public abstract class AbstractPreferences extends Preferences { * @throws IllegalArgumentException if key.length() exceeds * MAX_KEY_LENGTH or if value.length exceeds * MAX_VALUE_LENGTH. + * @throws IllegalArgumentException if either key or value contain + * the null control character, code point U+0000. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ @@ -243,6 +252,10 @@ public abstract class AbstractPreferences extends Preferences { throw new IllegalArgumentException("Key too long: "+key); if (value.length() > MAX_VALUE_LENGTH) throw new IllegalArgumentException("Value too long: "+value); + if (key.indexOf(CODE_POINT_U0000) != -1) + throw new IllegalArgumentException("Key contains code point U+0000"); + if (value.indexOf(CODE_POINT_U0000) != -1) + throw new IllegalArgumentException("Value contains code point U+0000"); synchronized(lock) { if (removed) @@ -274,10 +287,14 @@ public abstract class AbstractPreferences extends Preferences { * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. (A * null default is permitted.) + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. */ public String get(String key, String def) { if (key==null) throw new NullPointerException("Null key"); + if (key.indexOf(CODE_POINT_U0000) != -1) + throw new IllegalArgumentException("Key contains code point U+0000"); synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed."); @@ -305,10 +322,14 @@ public abstract class AbstractPreferences extends Preferences { * @param key key whose mapping is to be removed from the preference node. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. * @throws NullPointerException {@inheritDoc}. */ public void remove(String key) { Objects.requireNonNull(key, "Specified key cannot be null"); + if (key.indexOf(CODE_POINT_U0000) != -1) + throw new IllegalArgumentException("Key contains code point U+0000"); synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed."); @@ -352,6 +373,8 @@ public abstract class AbstractPreferences extends Preferences { * @throws NullPointerException if key is null. * @throws IllegalArgumentException if key.length() exceeds * MAX_KEY_LENGTH. + * @throws IllegalArgumentException if key contains + * the null control character, code point U+0000. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ @@ -380,6 +403,8 @@ public abstract class AbstractPreferences extends Preferences { * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. */ public int getInt(String key, int def) { int result = def; @@ -407,6 +432,8 @@ public abstract class AbstractPreferences extends Preferences { * @throws NullPointerException if key is null. * @throws IllegalArgumentException if key.length() exceeds * MAX_KEY_LENGTH. + * @throws IllegalArgumentException if key contains + * the null control character, code point U+0000. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ @@ -435,6 +462,8 @@ public abstract class AbstractPreferences extends Preferences { * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. */ public long getLong(String key, long def) { long result = def; @@ -462,6 +491,8 @@ public abstract class AbstractPreferences extends Preferences { * @throws NullPointerException if key is null. * @throws IllegalArgumentException if key.length() exceeds * MAX_KEY_LENGTH. + * @throws IllegalArgumentException if key contains + * the null control character, code point U+0000. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ @@ -493,6 +524,8 @@ public abstract class AbstractPreferences extends Preferences { * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. */ public boolean getBoolean(String key, boolean def) { boolean result = def; @@ -520,6 +553,8 @@ public abstract class AbstractPreferences extends Preferences { * @throws NullPointerException if key is null. * @throws IllegalArgumentException if key.length() exceeds * MAX_KEY_LENGTH. + * @throws IllegalArgumentException if key contains + * the null control character, code point U+0000. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ @@ -548,6 +583,8 @@ public abstract class AbstractPreferences extends Preferences { * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. */ public float getFloat(String key, float def) { float result = def; @@ -575,6 +612,8 @@ public abstract class AbstractPreferences extends Preferences { * @throws NullPointerException if key is null. * @throws IllegalArgumentException if key.length() exceeds * MAX_KEY_LENGTH. + * @throws IllegalArgumentException if key contains + * the null control character, code point U+0000. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ @@ -603,6 +642,8 @@ public abstract class AbstractPreferences extends Preferences { * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. */ public double getDouble(String key, double def) { double result = def; @@ -626,6 +667,8 @@ public abstract class AbstractPreferences extends Preferences { * @throws NullPointerException if key or value is null. * @throws IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH * or if value.length exceeds MAX_VALUE_LENGTH*3/4. + * @throws IllegalArgumentException if key contains + * the null control character, code point U+0000. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ @@ -649,6 +692,8 @@ public abstract class AbstractPreferences extends Preferences { * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. (A * null value for def is permitted.) + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. */ public byte[] getByteArray(String key, byte[] def) { byte[] result = def; @@ -1470,7 +1515,7 @@ public abstract class AbstractPreferences extends Preferences { * A single background thread ("the event notification thread") monitors * the event queue and delivers events that are placed on the queue. */ - private static class EventDispatchThread extends Thread { + private static class EventDispatchThread extends ManagedLocalsThread { public void run() { while(true) { // Wait on eventQueue till an event is present diff --git a/jdk/src/java.prefs/share/classes/java/util/prefs/Preferences.java b/jdk/src/java.prefs/share/classes/java/util/prefs/Preferences.java index beb0b0fa1a9..9edefc5affb 100644 --- a/jdk/src/java.prefs/share/classes/java/util/prefs/Preferences.java +++ b/jdk/src/java.prefs/share/classes/java/util/prefs/Preferences.java @@ -489,7 +489,7 @@ public abstract class Preferences { * MAX_VALUE_LENGTH. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. - * @throws IllegalArgumentException if either the key or the value contain + * @throws IllegalArgumentException if either key or value contain * the null control character, code point U+0000. */ public abstract void put(String key, String value); @@ -514,6 +514,8 @@ public abstract class Preferences { * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. (A * null value for def is permitted.) + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. */ public abstract String get(String key, String def); @@ -530,6 +532,8 @@ public abstract class Preferences { * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. */ public abstract void remove(String key); @@ -566,6 +570,8 @@ public abstract class Preferences { * MAX_KEY_LENGTH. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. + * @throws IllegalArgumentException if key contains + * the null control character, code point U+0000. * @see #getInt(String,int) */ public abstract void putInt(String key, int value); @@ -597,6 +603,8 @@ public abstract class Preferences { * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. * @see #putInt(String,int) * @see #get(String,String) */ @@ -616,6 +624,8 @@ public abstract class Preferences { * MAX_KEY_LENGTH. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. + * @throws IllegalArgumentException if key contains + * the null control character, code point U+0000. * @see #getLong(String,long) */ public abstract void putLong(String key, long value); @@ -647,6 +657,8 @@ public abstract class Preferences { * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. * @see #putLong(String,long) * @see #get(String,String) */ @@ -666,6 +678,8 @@ public abstract class Preferences { * MAX_KEY_LENGTH. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. + * @throws IllegalArgumentException if key contains + * the null control character, code point U+0000. * @see #getBoolean(String,boolean) * @see #get(String,String) */ @@ -702,6 +716,8 @@ public abstract class Preferences { * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. * @see #get(String,String) * @see #putBoolean(String,boolean) */ @@ -721,6 +737,8 @@ public abstract class Preferences { * MAX_KEY_LENGTH. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. + * @throws IllegalArgumentException if key contains + * the null control character, code point U+0000. * @see #getFloat(String,float) */ public abstract void putFloat(String key, float value); @@ -751,6 +769,8 @@ public abstract class Preferences { * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. * @see #putFloat(String,float) * @see #get(String,String) */ @@ -770,6 +790,8 @@ public abstract class Preferences { * MAX_KEY_LENGTH. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. + * @throws IllegalArgumentException if key contains + * the null control character, code point U+0000. * @see #getDouble(String,double) */ public abstract void putDouble(String key, double value); @@ -800,6 +822,8 @@ public abstract class Preferences { * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. * @see #putDouble(String,double) * @see #get(String,String) */ @@ -825,6 +849,8 @@ public abstract class Preferences { * or if value.length exceeds MAX_VALUE_LENGTH*3/4. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. + * @throws IllegalArgumentException if key contains + * the null control character, code point U+0000. * @see #getByteArray(String,byte[]) * @see #get(String,String) */ @@ -864,6 +890,8 @@ public abstract class Preferences { * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is null. (A * null value for def is permitted.) + * @throws IllegalArgumentException if key contains the null control + * character, code point U+0000. * @see #get(String,String) * @see #putByteArray(String,byte[]) */ diff --git a/jdk/src/java.prefs/unix/classes/java/util/prefs/FileSystemPreferences.java b/jdk/src/java.prefs/unix/classes/java/util/prefs/FileSystemPreferences.java index 7bcd1d3ad24..10188cc98c5 100644 --- a/jdk/src/java.prefs/unix/classes/java/util/prefs/FileSystemPreferences.java +++ b/jdk/src/java.prefs/unix/classes/java/util/prefs/FileSystemPreferences.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,7 @@ import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; - +import sun.misc.ManagedLocalsThread; import sun.util.logging.PlatformLogger; /** @@ -49,13 +49,6 @@ import sun.util.logging.PlatformLogger; */ class FileSystemPreferences extends AbstractPreferences { - /** - * The code point U+0000, assigned to the null control character, is the - * only character encoded in Unicode and ISO/IEC 10646 that is always - * invalid in any XML 1.0 and 1.1 document. - */ - private static final String CODE_POINT_U0000 = String.valueOf('\u0000'); - static { PrivilegedAction load = () -> { System.loadLibrary("prefs"); @@ -450,7 +443,7 @@ class FileSystemPreferences extends AbstractPreferences { // Add shutdown hook to flush cached prefs on normal termination AccessController.doPrivileged(new PrivilegedAction() { public Void run() { - Runtime.getRuntime().addShutdownHook(new Thread() { + Runtime.getRuntime().addShutdownHook(new ManagedLocalsThread() { public void run() { syncTimer.cancel(); syncWorld(); @@ -532,11 +525,6 @@ class FileSystemPreferences extends AbstractPreferences { } protected void putSpi(String key, String value) { - if (key.indexOf(CODE_POINT_U0000) != -1) { - throw new IllegalArgumentException("Key contains code point U+0000"); - } else if (value.indexOf(CODE_POINT_U0000) != -1) { - throw new IllegalArgumentException("Value contains code point U+0000"); - } initCacheIfNecessary(); changeLog.add(new Put(key, value)); prefsCache.put(key, value); diff --git a/jdk/src/java.prefs/windows/classes/java/util/prefs/WindowsPreferences.java b/jdk/src/java.prefs/windows/classes/java/util/prefs/WindowsPreferences.java index 6844234d39d..ec5b492ba9d 100644 --- a/jdk/src/java.prefs/windows/classes/java/util/prefs/WindowsPreferences.java +++ b/jdk/src/java.prefs/windows/classes/java/util/prefs/WindowsPreferences.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,8 +25,6 @@ package java.util.prefs; -import java.util.Map; -import java.util.TreeMap; import java.util.StringTokenizer; import java.io.ByteArrayOutputStream; import java.security.AccessController; @@ -46,7 +44,7 @@ import sun.util.logging.PlatformLogger; * @since 1.4 */ -class WindowsPreferences extends AbstractPreferences{ +class WindowsPreferences extends AbstractPreferences { static { PrivilegedAction load = () -> { @@ -620,22 +618,22 @@ class WindowsPreferences extends AbstractPreferences{ * @see #getSpi(String) */ protected void putSpi(String javaName, String value) { - int nativeHandle = openKey(KEY_SET_VALUE); - if (nativeHandle == NULL_NATIVE_HANDLE) { - isBackingStoreAvailable = false; - return; - } - int result = WindowsRegSetValueEx1(nativeHandle, - toWindowsName(javaName), toWindowsValueString(value)); - if (result != ERROR_SUCCESS) { - logger().warning("Could not assign value to key " + - byteArrayToString(toWindowsName(javaName))+ " at Windows registry node " - + byteArrayToString(windowsAbsolutePath()) + " at root 0x" - + Integer.toHexString(rootNativeHandle()) + - ". Windows RegSetValueEx(...) returned error code " + result + "."); - isBackingStoreAvailable = false; + int nativeHandle = openKey(KEY_SET_VALUE); + if (nativeHandle == NULL_NATIVE_HANDLE) { + isBackingStoreAvailable = false; + return; } - closeKey(nativeHandle); + int result = WindowsRegSetValueEx1(nativeHandle, + toWindowsName(javaName), toWindowsValueString(value)); + if (result != ERROR_SUCCESS) { + logger().warning("Could not assign value to key " + + byteArrayToString(toWindowsName(javaName))+ " at Windows registry node " + + byteArrayToString(windowsAbsolutePath()) + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + + ". Windows RegSetValueEx(...) returned error code " + result + "."); + isBackingStoreAvailable = false; + } + closeKey(nativeHandle); } /** @@ -645,18 +643,18 @@ class WindowsPreferences extends AbstractPreferences{ * @see #putSpi(String, String) */ protected String getSpi(String javaName) { - int nativeHandle = openKey(KEY_QUERY_VALUE); - if (nativeHandle == NULL_NATIVE_HANDLE) { - return null; - } - Object resultObject = WindowsRegQueryValueEx(nativeHandle, - toWindowsName(javaName)); - if (resultObject == null) { + int nativeHandle = openKey(KEY_QUERY_VALUE); + if (nativeHandle == NULL_NATIVE_HANDLE) { + return null; + } + Object resultObject = WindowsRegQueryValueEx(nativeHandle, + toWindowsName(javaName)); + if (resultObject == null) { + closeKey(nativeHandle); + return null; + } closeKey(nativeHandle); - return null; - } - closeKey(nativeHandle); - return toJavaValueString((byte[]) resultObject); + return toJavaValueString((byte[]) resultObject); } /** diff --git a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSContext.java b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSContext.java index 8c55da5fa98..63336da2e78 100644 --- a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSContext.java +++ b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -104,7 +104,7 @@ import java.io.OutputStream; * operations on the GSSContext object are presented, * including: object instantiation, setting of desired flags, context * establishment, query of actual context flags, per-message operations on - * application data, and finally context deletion.

                          + * application data, and finally context deletion. * *

                            *    // Create a context using default credentials
                          @@ -209,7 +209,7 @@ public interface GSSContext {
                                * Some mechanism providers might require that the caller be granted
                                * permission to initiate a security context. A failed permission check
                                * might cause a {@link java.lang.SecurityException SecurityException}
                          -     * to be thrown from this method.

                          + * to be thrown from this method. * * @return a byte[] containing the token to be sent to the * peer. null indicates that no token is generated. @@ -276,7 +276,7 @@ public interface GSSContext { * to be thrown from this method.

                          * * The following example code demonstrates how this method might be - * used:

                          + * used: *

                                *     InputStream is ...
                                *     OutputStream os ...
                          @@ -346,7 +346,7 @@ public interface GSSContext {
                                * to be thrown from this method.

                          * * The following example code demonstrates how this method might be - * used:

                          + * used: *

                                *     byte[] inToken;
                                *     byte[] outToken;
                          @@ -423,7 +423,7 @@ public interface GSSContext {
                                * to be thrown from this method.

                          * * The following example code demonstrates how this method might be - * used:

                          + * used: *

                                *     InputStream is ...
                                *     OutputStream os ...
                          @@ -510,7 +510,7 @@ public interface GSSContext {
                                * GSS-API implementations are recommended but not required to detect
                                * invalid QOP values when getWrapSizeLimit is called.
                                * This routine guarantees only a maximum message size, not the
                          -     * availability of specific QOP values for message protection.

                          + * availability of specific QOP values for message protection. * * @param qop the level of protection wrap will be asked to provide. * @param confReq true if wrap will be asked to provide @@ -595,7 +595,7 @@ public interface GSSContext { * * Since some application-level protocols may wish to use tokens * emitted by wrap to provide "secure framing", implementations should - * support the wrapping of zero-length messages.

                          + * support the wrapping of zero-length messages. * * @param inStream an InputStream containing the application data to be * protected. All of the data that is available in @@ -630,7 +630,7 @@ public interface GSSContext { * * Since some application-level protocols may wish to use tokens * emitted by wrap to provide "secure framing", implementations should - * support the wrapping and unwrapping of zero-length messages.

                          + * support the wrapping and unwrapping of zero-length messages. * * @param inBuf a byte array containing the wrap token received from * peer. @@ -679,7 +679,7 @@ public interface GSSContext { * * Other than the possible blocking behavior described above, this * method is equivalent to the byte array based {@link #unwrap(byte[], - * int, int, MessageProp) unwrap} method.

                          + * int, int, MessageProp) unwrap} method. * * @param inStream an InputStream that contains the wrap token generated * by the peer. @@ -827,7 +827,7 @@ public interface GSSContext { * * Other than the possible blocking behavior described above, this * method is equivalent to the byte array based {@link #verifyMIC(byte[], - * int, int, byte[], int, int, MessageProp) verifyMIC} method.

                          + * int, int, byte[], int, int, MessageProp) verifyMIC} method. * * @param tokStream an InputStream containing the token generated by the * peer's getMIC method. @@ -913,7 +913,7 @@ public interface GSSContext { * might require mutual authentication even if the application * doesn't. Therefore, the application should check to see if the * request was honored with the {@link #getMutualAuthState() - * getMutualAuthState} method.

                          + * getMutualAuthState} method. * * @param state a boolean value indicating whether mutual * authentication should be used or not. @@ -943,7 +943,7 @@ public interface GSSContext { * MessageProp#isOldToken() MessageProp.isOldToken} methods will return * valid results for the MessageProp object that is passed * in to the unwrap method or the verifyMIC - * method.

                          + * method. * * @param state a boolean value indicating whether replay detection * should be enabled over the established context or not. @@ -975,7 +975,7 @@ public interface GSSContext { * {@link MessageProp#isGapToken() MessageProp.isGapToken} methods will return * valid results for the MessageProp object that is passed * in to the unwrap method or the verifyMIC - * method.

                          + * method. * * @param state a boolean value indicating whether sequence checking * should be enabled over the established context or not. @@ -1001,7 +1001,7 @@ public interface GSSContext { * delegation must not be used, then the mechanism will honor the * request and delegation will not occur. This is an exception * to the general rule that a mechanism may enable a service even if it - * is not requested.

                          + * is not requested. * * @param state a boolean value indicating whether the credentials * should be delegated or not. @@ -1021,7 +1021,7 @@ public interface GSSContext { * * Not all mechanisms support anonymity for the initiator. Therefore, the * application should check to see if the request was honored with the - * {@link #getAnonymityState() getAnonymityState} method.

                          + * {@link #getAnonymityState() getAnonymityState} method. * * @param state a boolean value indicating if the initiator should * be authenticated to the acceptor as an anonymous principal. @@ -1048,7 +1048,7 @@ public interface GSSContext { * object that is passed in to the wrap method.

                          * * Enabling confidentiality will also automatically enable - * integrity.

                          + * integrity. * * @param state a boolean value indicating whether confidentiality * should be enabled or not. @@ -1075,7 +1075,7 @@ public interface GSSContext { * the {@link #getIntegState() getIntegState} method.

                          * * Disabling integrity will also automatically disable - * confidentiality.

                          + * confidentiality. * * @param state a boolean value indicating whether integrity * should be enabled or not. @@ -1095,7 +1095,7 @@ public interface GSSContext { * * The actual lifetime of the context will depend on the capabilities of * the underlying mechanism and the application should call the {@link - * #getLifetime() getLifetime} method to determine this.

                          + * #getLifetime() getLifetime} method to determine this. * * @param lifetime the desired context lifetime in seconds. Use * INDEFINITE_LIFETIME to request an indefinite lifetime @@ -1133,7 +1133,7 @@ public interface GSSContext { * initiator requests that delegation not be allowed the {@link * #requestCredDeleg(boolean) requestCredDeleg} method will honor that * request and this method will return false on the - * initiator's side from that point onwards.

                          + * initiator's side from that point onwards. * * @return true if delegation is enabled, false otherwise. * @see #requestCredDeleg(boolean) @@ -1147,7 +1147,7 @@ public interface GSSContext { * called only after context establishment is complete. An initiator * that requests mutual authentication can call this method after * context completion and dispose the context if its request was not - * honored.

                          + * honored. * * @return true if mutual authentication is enabled, false otherwise. * @see #requestMutualAuth(boolean) @@ -1161,7 +1161,7 @@ public interface GSSContext { * definitive answer this method must be called only after context * establishment is complete. An initiator that requests replay * detection can call this method after context completion and - * dispose the context if its request was not honored.

                          + * dispose the context if its request was not honored. * * @return true if replay detection is enabled, false otherwise. * @see #requestReplayDet(boolean) @@ -1175,7 +1175,7 @@ public interface GSSContext { * definitive answer this method must be called only after context * establishment is complete. An initiator that requests sequence * checking can call this method after context completion and - * dispose the context if its request was not honored.

                          + * dispose the context if its request was not honored. * * @return true if sequence checking is enabled, false otherwise. * @see #requestSequenceDet(boolean) @@ -1195,7 +1195,7 @@ public interface GSSContext { * should be sent to the peer or the context aborted. On the * acceptor side, a call to this method determines if any of the tokens * processed by acceptSecContext thus far have divulged - * the identity of the initiator.

                          + * the identity of the initiator. * * @return true if the context initiator is still anonymous, false * otherwise. @@ -1235,7 +1235,7 @@ public interface GSSContext { * #isProtReady() isProtReady} or {@link #isEstablished() * isEstablished} return true. If this method returns * true, so will {@link #getIntegState() - * getIntegState}

                          + * getIntegState} * * @return true if confidentiality services are available, false * otherwise. @@ -1250,7 +1250,7 @@ public interface GSSContext { * #isProtReady() isProtReady} or {@link #isEstablished() * isEstablished} return true. This method will always * return true if {@link #getConfState() getConfState} - * returns true.

                          + * returns true. * * @return true if integrity services are available, false otherwise. * @see #requestInteg(boolean) @@ -1262,7 +1262,7 @@ public interface GSSContext { * context is. It can be called by both the context initiator and the * context acceptor, but for a definitive answer it should be called * only after {@link #isEstablished() isEstablished} returns - * true.

                          + * true. * * @return the remaining lifetime in seconds * @see #requestLifetime(int) diff --git a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSCredential.java b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSCredential.java index fbe379ef2e6..6c304bed59a 100644 --- a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSCredential.java +++ b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSCredential.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,7 +35,7 @@ package org.ietf.jgss; * may be used to perform context initiation, acceptance, or both.

                          * * Credentials are instantiated using one of the - * createCredential methods in the {@link GSSManager + * {@code createCredential} methods in the {@link GSSManager * GSSManager} class. GSS-API credential creation is not * intended to provide a "login to the network" function, as such a * function would involve the creation of new credentials rather than @@ -57,7 +57,7 @@ package org.ietf.jgss; * * This example code demonstrates the creation of a GSSCredential * implementation for a specific entity, querying of its fields, and its - * release when it is no longer needed:

                          + * release when it is no longer needed: *

                            *    GSSManager manager = GSSManager.getInstance();
                            *
                          @@ -75,7 +75,7 @@ package org.ietf.jgss;
                            *
                            *    Oid [] mechs = cred.getMechs();
                            *    if (mechs != null) {
                          - *            for (int i = 0; i < mechs.length; i++)
                          + *            for (int i = 0; i{@literal <} mechs.length; i++)
                            *                    System.out.println(mechs[i].toString());
                            *    }
                            *
                          @@ -297,8 +297,8 @@ public interface GSSCredential extends Cloneable{
                                * with a variety of clients using different security mechanisms.

                          * * This routine adds the new credential element "in-place". To add the - * element in a new credential, first call clone to obtain a - * copy of this credential, then call its add method.

                          + * element in a new credential, first call {@code clone} to obtain a + * copy of this credential, then call its {@code add} method.

                          * * As always, GSS-API implementations must impose a local access-control * policy on callers to prevent unauthorized callers from acquiring @@ -311,7 +311,7 @@ public interface GSSCredential extends Cloneable{ * getRemainingAcceptLifetime} on the credential. * * @param name the name of the principal for whom this credential is to - * be acquired. Use null to specify the default + * be acquired. Use {@code null} to specify the default * principal. * @param initLifetime the number of seconds that the credential element * should remain valid for initiating of security contexts. Use {@link @@ -354,8 +354,8 @@ public interface GSSCredential extends Cloneable{ * object. The two credentials must be acquired over the same * mechanisms and must refer to the same principal. * - * @return true if the two GSSCredentials assert the same - * entity; false otherwise. + * @return {@code true} if the two GSSCredentials assert the same + * entity; {@code false} otherwise. * @param another another GSSCredential for comparison to this one */ public boolean equals(Object another); diff --git a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSException.java b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSException.java index cfde0e58fe2..ed7e3ad6332 100644 --- a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSException.java +++ b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,7 +34,7 @@ package org.ietf.jgss; * mechanism implementation is responsible for setting appropriate minor * status codes when throwing this exception. Aside from delivering the * numeric error codes to the caller, this class performs the mapping from - * their numeric values to textual representations.

                          + * their numeric values to textual representations. * * @author Mayank Upadhyay * @since 1.4 diff --git a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSManager.java b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSManager.java index 3bf99e409ab..f9ae3efafee 100644 --- a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSManager.java +++ b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,7 +55,7 @@ import java.security.Provider; * of this and recover cleanly by catching the exception.

                          * * It is envisioned that there will be three most common ways in which - * providers will be used:

                          + * providers will be used: *

                            *
                          1. The application does not care about what provider is used (the * default case). @@ -87,7 +87,7 @@ import java.security.Provider; * the addProviderAtFront method on a GSSManager that has * already created an object.

                            * - * Here is some sample code showing how the GSSManager might be used:

                            + * Here is some sample code showing how the GSSManager might be used: *

                              *     GSSManager manager = GSSManager.getInstance();
                              *
                            @@ -116,7 +116,7 @@ import java.security.Provider;
                              *                                                GSSContext.DEFAULT_LIFETIME);
                              * 

                            * - * The server side might use the following variation of this source:

                            + * The server side might use the following variation of this source: * *

                              *     // Acquire credentials for the server
                            @@ -387,7 +387,7 @@ public abstract class GSSManager {
                                  * Non-default values for lifetime cannot always be honored by the
                                  * underlying mechanisms, thus applications should be prepared to call
                                  * {@link GSSCredential#getRemainingLifetime() getRemainingLifetime}
                            -     * on the returned credential.

                            + * on the returned credential. * * @param name the name of the principal for whom this credential is to be * acquired. Use null to specify the default principal. @@ -442,7 +442,7 @@ public abstract class GSSManager { * Non-default values for lifetime cannot always be honored by the * underlying mechanisms, thus applications should be prepared to call * {@link GSSCredential#getRemainingLifetime() getRemainingLifetime} - * on the returned credential.

                            + * on the returned credential. * * @param name the name of the principal for whom this credential is to * be acquired. Use null to specify the default @@ -492,7 +492,7 @@ public abstract class GSSManager { * Non-default values for lifetime cannot always be honored by the * underlying mechanism, thus applications should be prepared to call * {@link GSSContext#getLifetime() getLifetime} on the returned - * context.

                            + * context. * * @param peer the name of the target peer. * @param mech the Oid of the desired mechanism. Use null @@ -610,7 +610,7 @@ public abstract class GSSManager { * operation is unavailable.

                            * * Suppose an application desired that the provider A always be checked - * first when any mechanism is needed, it would call:

                            + * first when any mechanism is needed, it would call: *

                                  *         GSSManager mgr = GSSManager.getInstance();
                                  *         // mgr may at this point have its own pre-configured list
                            @@ -621,7 +621,7 @@ public abstract class GSSManager {
                                  * 
                            * Now if it also desired that the mechanism of Oid m1 always be * obtained from the provider B before the previously set A was checked, - * it would call:

                            + * it would call: *

                                  *         mgr.addProviderAtFront(B, m1);
                                  * 
                            @@ -632,7 +632,7 @@ public abstract class GSSManager { * directly.

                            * * Suppose at a later time the following call is made to the same - * GSSManager instance:

                            + * GSSManager instance: *

                                  *         mgr.addProviderAtFront(B, null)
                                  * 
                            @@ -684,14 +684,14 @@ public abstract class GSSManager { * Suppose an application desired that when a mechanism of Oid m1 is * needed the system default providers always be checked first, and only * when they do not support m1 should a provider A be checked. It would - * then make the call:

                            + * then make the call: *

                                  *         GSSManager mgr = GSSManager.getInstance();
                                  *         mgr.addProviderAtEnd(A, m1);
                                  * 
                            * Now, if it also desired that for all mechanisms the provider B be * checked after all configured providers have been checked, it would - * then call:

                            + * then call: *

                                  *         mgr.addProviderAtEnd(B, null);
                                  * 
                            @@ -699,7 +699,7 @@ public abstract class GSSManager { * null)}.

                            * * Suppose at a later time the following call is made to the same - * GSSManager instance:

                            + * GSSManager instance: *

                                  *         mgr.addProviderAtEnd(B, m2)
                                  * 
                            @@ -708,7 +708,7 @@ public abstract class GSSManager { * request is made for the already existing pairs of (A, m1) or (B, * null).

                            * - * Please note, however, that the following call:

                            + * Please note, however, that the following call: *

                                  *         mgr.addProviderAtEnd(A, null)
                                  * 
                            diff --git a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSName.java b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSName.java index 580ab39383a..185a6c2f7b4 100644 --- a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSName.java +++ b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/GSSName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -48,7 +48,7 @@ package org.ietf.jgss; * The code below creates a GSSName, converts it to an MN, performs a * comparison, obtains a printable representation of the name, exports it * to a byte array and then re-imports to obtain a - * new GSSName.

                            + * new GSSName. *

                              *      GSSManager manager = GSSManager.getInstance();
                              *
                            @@ -236,7 +236,8 @@ public interface GSSName {
                                  * method {@link GSSManager#createName(byte[], Oid)
                                  * GSSManager.createName} and specifying the NT_EXPORT_NAME as the name
                                  * type object identifier. The resulting GSSName name will
                            -     * also be a MN.

                            + * also be a MN. + * * @return a byte[] containing the exported name. RFC 2743 defines the * "Mechanism-Independent Exported Name Object Format" for these bytes. * diff --git a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/MessageProp.java b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/MessageProp.java index 2f776ebc2e6..8568f57ef11 100644 --- a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/MessageProp.java +++ b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/MessageProp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ package org.ietf.jgss; * false. Upon return from these methods, this object will also * contain any supplementary status values applicable to the processed * token. The supplementary status values can indicate old tokens, out - * of sequence tokens, gap tokens or duplicate tokens.

                            + * of sequence tokens, gap tokens or duplicate tokens. * * @see GSSContext#wrap * @see GSSContext#unwrap diff --git a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/package.html b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/package.html index 1dc1ec4985b..2049a263abe 100644 --- a/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/package.html +++ b/jdk/src/java.security.jgss/share/classes/org/ietf/jgss/package.html @@ -2,7 +2,7 @@ diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTDomainPrincipal.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTDomainPrincipal.java index e3a46debeed..995732efa16 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTDomainPrincipal.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTDomainPrincipal.java @@ -28,19 +28,19 @@ package com.sun.security.auth; import java.security.Principal; /** - *

                            This class implements the Principal interface + * This class implements the {@code Principal} interface * and represents the name of the Windows NT domain into which the * user authenticated. This will be a domain name if the user logged * into a Windows NT domain, a workgroup name if the user logged into * a workgroup, or a machine name if the user logged into a standalone * configuration. * - *

                            Principals such as this NTDomainPrincipal - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code NTDomainPrincipal} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * * @see java.security.Principal * @see javax.security.auth.Subject @@ -56,14 +56,12 @@ public class NTDomainPrincipal implements Principal, java.io.Serializable { private String name; /** - * Create an NTDomainPrincipal with a Windows NT domain name. + * Create an {@code NTDomainPrincipal} with a Windows NT domain name. * - *

                            + * @param name the Windows NT domain name for this user. * - * @param name the Windows NT domain name for this user.

                            - * - * @exception NullPointerException if the name - * is null. + * @exception NullPointerException if the {@code name} + * is {@code null}. */ public NTDomainPrincipal(String name) { if (name == null) { @@ -79,23 +77,19 @@ public class NTDomainPrincipal implements Principal, java.io.Serializable { /** * Return the Windows NT domain name for this - * NTDomainPrincipal. - * - *

                            + * {@code NTDomainPrincipal}. * * @return the Windows NT domain name for this - * NTDomainPrincipal + * {@code NTDomainPrincipal} */ public String getName() { return name; } /** - * Return a string representation of this NTDomainPrincipal. + * Return a string representation of this {@code NTDomainPrincipal}. * - *

                            - * - * @return a string representation of this NTDomainPrincipal. + * @return a string representation of this {@code NTDomainPrincipal}. */ public String toString() { java.text.MessageFormat form = new java.text.MessageFormat @@ -107,18 +101,16 @@ public class NTDomainPrincipal implements Principal, java.io.Serializable { } /** - * Compares the specified Object with this NTDomainPrincipal + * Compares the specified Object with this {@code NTDomainPrincipal} * for equality. Returns true if the given object is also a - * NTDomainPrincipal and the two NTDomainPrincipals + * {@code NTDomainPrincipal} and the two NTDomainPrincipals * have the same name. * - *

                            - * * @param o Object to be compared for equality with this - * NTDomainPrincipal. + * {@code NTDomainPrincipal}. * * @return true if the specified Object is equal to this - * NTDomainPrincipal. + * {@code NTDomainPrincipal}. */ public boolean equals(Object o) { if (o == null) @@ -137,11 +129,9 @@ public class NTDomainPrincipal implements Principal, java.io.Serializable { } /** - * Return a hash code for this NTDomainPrincipal. + * Return a hash code for this {@code NTDomainPrincipal}. * - *

                            - * - * @return a hash code for this NTDomainPrincipal. + * @return a hash code for this {@code NTDomainPrincipal}. */ public int hashCode() { return this.getName().hashCode(); diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTNumericCredential.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTNumericCredential.java index 59208603c19..eca81587468 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTNumericCredential.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTNumericCredential.java @@ -26,9 +26,8 @@ package com.sun.security.auth; /** - *

                            This class abstracts an NT security token + * This class abstracts an NT security token * and provides a mechanism to do same-process security impersonation. - * */ @jdk.Exported @@ -37,12 +36,9 @@ public class NTNumericCredential { private long impersonationToken; /** - * Create an NTNumericCredential with an integer value. - * - *

                            - * - * @param token the Windows NT security token for this user.

                            + * Create an {@code NTNumericCredential} with an integer value. * + * @param token the Windows NT security token for this user. */ public NTNumericCredential(long token) { this.impersonationToken = token; @@ -50,23 +46,19 @@ public class NTNumericCredential { /** * Return an integer representation of this - * NTNumericCredential. - * - *

                            + * {@code NTNumericCredential}. * * @return an integer representation of this - * NTNumericCredential. + * {@code NTNumericCredential}. */ public long getToken() { return impersonationToken; } /** - * Return a string representation of this NTNumericCredential. + * Return a string representation of this {@code NTNumericCredential}. * - *

                            - * - * @return a string representation of this NTNumericCredential. + * @return a string representation of this {@code NTNumericCredential}. */ public String toString() { java.text.MessageFormat form = new java.text.MessageFormat @@ -78,18 +70,16 @@ public class NTNumericCredential { } /** - * Compares the specified Object with this NTNumericCredential + * Compares the specified Object with this {@code NTNumericCredential} * for equality. Returns true if the given object is also a - * NTNumericCredential and the two NTNumericCredentials + * {@code NTNumericCredential} and the two NTNumericCredentials * represent the same NT security token. * - *

                            - * * @param o Object to be compared for equality with this - * NTNumericCredential. + * {@code NTNumericCredential}. * * @return true if the specified Object is equal to this - * NTNumericCredential. + * {@code NTNumericCredential}. */ public boolean equals(Object o) { if (o == null) @@ -108,11 +98,9 @@ public class NTNumericCredential { } /** - * Return a hash code for this NTNumericCredential. + * Return a hash code for this {@code NTNumericCredential}. * - *

                            - * - * @return a hash code for this NTNumericCredential. + * @return a hash code for this {@code NTNumericCredential}. */ public int hashCode() { return (int)this.impersonationToken; diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSid.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSid.java index 28b40b9302f..a304eeb148d 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSid.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSid.java @@ -28,7 +28,7 @@ package com.sun.security.auth; import java.security.Principal; /** - *

                            This class implements the Principal interface + * This class implements the {@code Principal} interface * and represents information about a Windows NT user, group or realm. * *

                            Windows NT chooses to represent users, groups and realms (or domains) @@ -37,12 +37,12 @@ import java.security.Principal; * also provides services that render these SIDs into string forms. * This class represents these string forms. * - *

                            Principals such as this NTSid - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code NTSid} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * * @see java.security.Principal * @see javax.security.auth.Subject @@ -58,16 +58,14 @@ public class NTSid implements Principal, java.io.Serializable { private String sid; /** - * Create an NTSid with a Windows NT SID. + * Create an {@code NTSid} with a Windows NT SID. * - *

                            + * @param stringSid the Windows NT SID. * - * @param stringSid the Windows NT SID.

                            + * @exception NullPointerException if the {@code String} + * is {@code null}. * - * @exception NullPointerException if the String - * is null. - * - * @exception IllegalArgumentException if the String + * @exception IllegalArgumentException if the {@code String} * has zero length. */ public NTSid (String stringSid) { @@ -89,22 +87,18 @@ public class NTSid implements Principal, java.io.Serializable { } /** - * Return a string version of this NTSid. + * Return a string version of this {@code NTSid}. * - *

                            - * - * @return a string version of this NTSid + * @return a string version of this {@code NTSid} */ public String getName() { return sid; } /** - * Return a string representation of this NTSid. + * Return a string representation of this {@code NTSid}. * - *

                            - * - * @return a string representation of this NTSid. + * @return a string representation of this {@code NTSid}. */ public String toString() { java.text.MessageFormat form = new java.text.MessageFormat @@ -116,18 +110,16 @@ public class NTSid implements Principal, java.io.Serializable { } /** - * Compares the specified Object with this NTSid + * Compares the specified Object with this {@code NTSid} * for equality. Returns true if the given object is also a - * NTSid and the two NTSids have the same String + * {@code NTSid} and the two NTSids have the same String * representation. * - *

                            - * * @param o Object to be compared for equality with this - * NTSid. + * {@code NTSid}. * * @return true if the specified Object is equal to this - * NTSid. + * {@code NTSid}. */ public boolean equals(Object o) { if (o == null) @@ -147,11 +139,9 @@ public class NTSid implements Principal, java.io.Serializable { } /** - * Return a hash code for this NTSid. + * Return a hash code for this {@code NTSid}. * - *

                            - * - * @return a hash code for this NTSid. + * @return a hash code for this {@code NTSid}. */ public int hashCode() { return sid.hashCode(); diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidDomainPrincipal.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidDomainPrincipal.java index e065ea49a08..0911f797efe 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidDomainPrincipal.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidDomainPrincipal.java @@ -26,19 +26,19 @@ package com.sun.security.auth; /** - *

                            This class extends NTSid + * This class extends {@code NTSid} * and represents a Windows NT user's domain SID. * *

                            An NT user only has a domain SID if in fact they are logged * into an NT domain. If the user is logged into a workgroup or * just a standalone configuration, they will NOT have a domain SID. * - *

                            Principals such as this NTSidDomainPrincipal - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code NTSidDomainPrincipal} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * * @see java.security.Principal * @see javax.security.auth.Subject @@ -49,27 +49,23 @@ public class NTSidDomainPrincipal extends NTSid { private static final long serialVersionUID = 5247810785821650912L; /** - * Create an NTSidDomainPrincipal with a Windows NT SID. - * - *

                            + * Create an {@code NTSidDomainPrincipal} with a Windows NT SID. * * @param name a string version of the Windows NT SID for this - * user's domain.

                            + * user's domain. * - * @exception NullPointerException if the name - * is null. + * @exception NullPointerException if the {@code name} + * is {@code null}. */ public NTSidDomainPrincipal(String name) { super(name); } /** - * Return a string representation of this NTSidDomainPrincipal. - * - *

                            + * Return a string representation of this {@code NTSidDomainPrincipal}. * * @return a string representation of this - * NTSidDomainPrincipal. + * {@code NTSidDomainPrincipal}. */ public String toString() { java.text.MessageFormat form = new java.text.MessageFormat @@ -81,18 +77,16 @@ public class NTSidDomainPrincipal extends NTSid { } /** - * Compares the specified Object with this NTSidDomainPrincipal + * Compares the specified Object with this {@code NTSidDomainPrincipal} * for equality. Returns true if the given object is also a - * NTSidDomainPrincipal and the two NTSidDomainPrincipals + * {@code NTSidDomainPrincipal} and the two NTSidDomainPrincipals * have the same SID. * - *

                            - * * @param o Object to be compared for equality with this - * NTSidDomainPrincipal. + * {@code NTSidDomainPrincipal}. * * @return true if the specified Object is equal to this - * NTSidDomainPrincipal. + * {@code NTSidDomainPrincipal}. */ public boolean equals(Object o) { if (o == null) diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidGroupPrincipal.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidGroupPrincipal.java index 5f509e22ec3..9bdc87b9dc5 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidGroupPrincipal.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidGroupPrincipal.java @@ -26,15 +26,15 @@ package com.sun.security.auth; /** - *

                            This class extends NTSid + * This class extends {@code NTSid} * and represents one of the groups to which a Windows NT user belongs. * - *

                            Principals such as this NTSidGroupPrincipal - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code NTSidGroupPrincipal} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * * @see java.security.Principal * @see javax.security.auth.Subject @@ -46,25 +46,21 @@ public class NTSidGroupPrincipal extends NTSid { private static final long serialVersionUID = -1373347438636198229L; /** - * Create an NTSidGroupPrincipal with a Windows NT group name. + * Create an {@code NTSidGroupPrincipal} with a Windows NT group name. * - *

                            + * @param name the Windows NT group SID for this user. * - * @param name the Windows NT group SID for this user.

                            - * - * @exception NullPointerException if the name - * is null. + * @exception NullPointerException if the {@code name} + * is {@code null}. */ public NTSidGroupPrincipal(String name) { super(name); } /** - * Return a string representation of this NTSidGroupPrincipal. + * Return a string representation of this {@code NTSidGroupPrincipal}. * - *

                            - * - * @return a string representation of this NTSidGroupPrincipal. + * @return a string representation of this {@code NTSidGroupPrincipal}. */ public String toString() { java.text.MessageFormat form = new java.text.MessageFormat @@ -76,18 +72,16 @@ public class NTSidGroupPrincipal extends NTSid { } /** - * Compares the specified Object with this NTSidGroupPrincipal + * Compares the specified Object with this {@code NTSidGroupPrincipal} * for equality. Returns true if the given object is also a - * NTSidGroupPrincipal and the two NTSidGroupPrincipals + * {@code NTSidGroupPrincipal} and the two NTSidGroupPrincipals * have the same SID. * - *

                            - * * @param o Object to be compared for equality with this - * NTSidGroupPrincipal. + * {@code NTSidGroupPrincipal}. * * @return true if the specified Object is equal to this - * NTSidGroupPrincipal. + * {@code NTSidGroupPrincipal}. */ public boolean equals(Object o) { if (o == null) diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidPrimaryGroupPrincipal.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidPrimaryGroupPrincipal.java index 4578f271df6..1d33ee3909a 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidPrimaryGroupPrincipal.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidPrimaryGroupPrincipal.java @@ -26,15 +26,15 @@ package com.sun.security.auth; /** - *

                            This class extends NTSid + * This class extends {@code NTSid} * and represents a Windows NT user's primary group SID. * - *

                            Principals such as this NTSidPrimaryGroupPrincipal - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code NTSidPrimaryGroupPrincipal} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * * @see java.security.Principal * @see javax.security.auth.Subject @@ -45,15 +45,13 @@ public class NTSidPrimaryGroupPrincipal extends NTSid { private static final long serialVersionUID = 8011978367305190527L; /** - * Create an NTSidPrimaryGroupPrincipal with a Windows NT + * Create an {@code NTSidPrimaryGroupPrincipal} with a Windows NT * group SID. * - *

                            + * @param name the primary Windows NT group SID for this user. * - * @param name the primary Windows NT group SID for this user.

                            - * - * @exception NullPointerException if the name - * is null. + * @exception NullPointerException if the {@code name} + * is {@code null}. */ public NTSidPrimaryGroupPrincipal(String name) { super(name); @@ -61,12 +59,10 @@ public class NTSidPrimaryGroupPrincipal extends NTSid { /** * Return a string representation of this - * NTSidPrimaryGroupPrincipal. - * - *

                            + * {@code NTSidPrimaryGroupPrincipal}. * * @return a string representation of this - * NTSidPrimaryGroupPrincipal. + * {@code NTSidPrimaryGroupPrincipal}. */ public String toString() { java.text.MessageFormat form = new java.text.MessageFormat @@ -79,18 +75,16 @@ public class NTSidPrimaryGroupPrincipal extends NTSid { /** * Compares the specified Object with this - * NTSidPrimaryGroupPrincipal + * {@code NTSidPrimaryGroupPrincipal} * for equality. Returns true if the given object is also a - * NTSidPrimaryGroupPrincipal and the two + * {@code NTSidPrimaryGroupPrincipal} and the two * NTSidPrimaryGroupPrincipals have the same SID. * - *

                            - * * @param o Object to be compared for equality with this - * NTSidPrimaryGroupPrincipal. + * {@code NTSidPrimaryGroupPrincipal}. * * @return true if the specified Object is equal to this - * NTSidPrimaryGroupPrincipal. + * {@code NTSidPrimaryGroupPrincipal}. */ public boolean equals(Object o) { if (o == null) diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidUserPrincipal.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidUserPrincipal.java index 98b318d4f4a..c95d82a4d0a 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidUserPrincipal.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTSidUserPrincipal.java @@ -26,15 +26,15 @@ package com.sun.security.auth; /** - *

                            This class extends NTSid + * This class extends {@code NTSid} * and represents a Windows NT user's SID. * - *

                            Principals such as this NTSidUserPrincipal - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code NTSidUserPrincipal} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * * @see java.security.Principal * @see javax.security.auth.Subject @@ -45,25 +45,21 @@ public class NTSidUserPrincipal extends NTSid { private static final long serialVersionUID = -5573239889517749525L; /** - * Create an NTSidUserPrincipal with a Windows NT SID. + * Create an {@code NTSidUserPrincipal} with a Windows NT SID. * - *

                            + * @param name a string version of the Windows NT SID for this user. * - * @param name a string version of the Windows NT SID for this user.

                            - * - * @exception NullPointerException if the name - * is null. + * @exception NullPointerException if the {@code name} + * is {@code null}. */ public NTSidUserPrincipal(String name) { super(name); } /** - * Return a string representation of this NTSidUserPrincipal. + * Return a string representation of this {@code NTSidUserPrincipal}. * - *

                            - * - * @return a string representation of this NTSidUserPrincipal. + * @return a string representation of this {@code NTSidUserPrincipal}. */ public String toString() { java.text.MessageFormat form = new java.text.MessageFormat @@ -75,18 +71,16 @@ public class NTSidUserPrincipal extends NTSid { } /** - * Compares the specified Object with this NTSidUserPrincipal + * Compares the specified Object with this {@code NTSidUserPrincipal} * for equality. Returns true if the given object is also a - * NTSidUserPrincipal and the two NTSidUserPrincipals + * {@code NTSidUserPrincipal} and the two NTSidUserPrincipals * have the same SID. * - *

                            - * * @param o Object to be compared for equality with this - * NTSidUserPrincipal. + * {@code NTSidUserPrincipal}. * * @return true if the specified Object is equal to this - * NTSidUserPrincipal. + * {@code NTSidUserPrincipal}. */ public boolean equals(Object o) { if (o == null) diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTUserPrincipal.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTUserPrincipal.java index 55e88e17625..1005793f737 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTUserPrincipal.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/NTUserPrincipal.java @@ -28,15 +28,15 @@ package com.sun.security.auth; import java.security.Principal; /** - *

                            This class implements the Principal interface + * This class implements the {@code Principal} interface * and represents a Windows NT user. * - *

                            Principals such as this NTUserPrincipal - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code NTUserPrincipal} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * * @see java.security.Principal * @see javax.security.auth.Subject @@ -52,14 +52,12 @@ public class NTUserPrincipal implements Principal, java.io.Serializable { private String name; /** - * Create an NTUserPrincipal with a Windows NT username. + * Create an {@code NTUserPrincipal} with a Windows NT username. * - *

                            + * @param name the Windows NT username for this user. * - * @param name the Windows NT username for this user.

                            - * - * @exception NullPointerException if the name - * is null. + * @exception NullPointerException if the {@code name} + * is {@code null}. */ public NTUserPrincipal(String name) { if (name == null) { @@ -74,22 +72,18 @@ public class NTUserPrincipal implements Principal, java.io.Serializable { } /** - * Return the Windows NT username for this NTPrincipal. + * Return the Windows NT username for this {@code NTPrincipal}. * - *

                            - * - * @return the Windows NT username for this NTPrincipal + * @return the Windows NT username for this {@code NTPrincipal} */ public String getName() { return name; } /** - * Return a string representation of this NTPrincipal. + * Return a string representation of this {@code NTPrincipal}. * - *

                            - * - * @return a string representation of this NTPrincipal. + * @return a string representation of this {@code NTPrincipal}. */ public String toString() { java.text.MessageFormat form = new java.text.MessageFormat @@ -101,18 +95,16 @@ public class NTUserPrincipal implements Principal, java.io.Serializable { } /** - * Compares the specified Object with this NTUserPrincipal + * Compares the specified Object with this {@code NTUserPrincipal} * for equality. Returns true if the given object is also a - * NTUserPrincipal and the two NTUserPrincipals + * {@code NTUserPrincipal} and the two NTUserPrincipals * have the same name. * - *

                            - * * @param o Object to be compared for equality with this - * NTPrincipal. + * {@code NTPrincipal}. * * @return true if the specified Object is equal to this - * NTPrincipal. + * {@code NTPrincipal}. */ public boolean equals(Object o) { if (o == null) @@ -131,11 +123,9 @@ public class NTUserPrincipal implements Principal, java.io.Serializable { } /** - * Return a hash code for this NTUserPrincipal. + * Return a hash code for this {@code NTUserPrincipal}. * - *

                            - * - * @return a hash code for this NTUserPrincipal. + * @return a hash code for this {@code NTUserPrincipal}. */ public int hashCode() { return this.getName().hashCode(); diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/PolicyFile.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/PolicyFile.java index a6402eb68ee..e61e821eca0 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/PolicyFile.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/PolicyFile.java @@ -31,25 +31,25 @@ import javax.security.auth.Subject; /** * This class represents a default implementation for - * javax.security.auth.Policy. + * {@code javax.security.auth.Policy}. * *

                            This object stores the policy for entire Java runtime, * and is the amalgamation of multiple static policy * configurations that resides in files. * The algorithm for locating the policy file(s) and reading their - * information into this Policy object is: + * information into this {@code Policy} object is: * *

                              *
                            1. * Loop through the security properties, * auth.policy.url.1, auth.policy.url.2, ..., * auth.policy.url.X". - * Each property value specifies a URL pointing to a + * Each property value specifies a {@code URL} pointing to a * policy file to be loaded. Read in and load each policy. * *
                            2. - * The java.lang.System property java.security.auth.policy - * may also be set to a URL pointing to another policy file + * The {@code java.lang.System} property java.security.auth.policy + * may also be set to a {@code URL} pointing to another policy file * (which is the case when a user uses the -D switch at runtime). * If this property is defined, and its use is allowed by the * security property file (the Security property, @@ -83,35 +83,35 @@ import javax.security.auth.Subject; * doesn't matter and some are optional, as noted below). * Italicized items represent variable values. * - *

                              A grant entry must begin with the word grant. - * The signedBy and codeBase + *

                              A grant entry must begin with the word {@code grant}. + * The {@code signedBy} and {@code codeBase} * name/value pairs are optional. * If they are not present, then any signer (including unsigned code) * will match, and any codeBase will match. Note that the - * principal name/value pair is not optional. - * This Policy implementation only permits + * {@code principal} name/value pair is not optional. + * This {@code Policy} implementation only permits * Principal-based grant entries. Note that the principalClass * may be set to the wildcard value, *, which allows it to match - * any Principal class. In addition, the principalName + * any {@code Principal} class. In addition, the principalName * may also be set to the wildcard value, *, allowing it to match - * any Principal name. When setting the principalName + * any {@code Principal} name. When setting the principalName * to the *, do not surround the * with quotes. * - *

                              A permission entry must begin with the word permission. - * The word Type in the template above is - * a specific permission type, such as java.io.FilePermission - * or java.lang.RuntimePermission. + *

                              A permission entry must begin with the word {@code permission}. + * The word {@code Type} in the template above is + * a specific permission type, such as {@code java.io.FilePermission} + * or {@code java.lang.RuntimePermission}. * *

                              The "action" is required for - * many permission types, such as java.io.FilePermission + * many permission types, such as {@code java.io.FilePermission} * (where it specifies what type of file access that is permitted). * It is not required for categories such as - * java.lang.RuntimePermission + * {@code java.lang.RuntimePermission} * where it is not necessary - you either have the - * permission specified by the "name" + * permission specified by the "{@code name}" * value following the type name or you don't. * - *

                              The signedBy name/value pair for a permission entry + *

                              The {@code signedBy} name/value pair for a permission entry * is optional. If present, it indicates a signed permission. That is, * the permission class itself must be signed by the given alias in * order for it to be granted. For example, @@ -124,18 +124,18 @@ import javax.security.auth.Subject; *

                            * *

                            Then this permission of type Foo is granted if the - * Foo.class permission has been signed by the - * "FooSoft" alias, or if Foo.class is a + * {@code Foo.class} permission has been signed by the + * "FooSoft" alias, or if {@code Foo.class} is a * system class (i.e., is found on the CLASSPATH). * *

                            Items that appear in an entry must appear in the specified order - * (permission, Type, "name", and + * ({@code permission}, Type, "name", and * "action"). An entry is terminated with a semicolon. * - *

                            Case is unimportant for the identifiers (permission, - * signedBy, codeBase, etc.) but is + *

                            Case is unimportant for the identifiers ({@code permission}, + * {@code signedBy}, {@code codeBase}, etc.) but is * significant for the Type - * or for any string that is passed in as a value.

                            + * or for any string that is passed in as a value. * *

                            An example of two entries in a policy configuration file is *

                            @@ -153,15 +153,15 @@ import javax.security.auth.Subject;
                              *         permission java.util.PropertyPermission "java.vendor";
                              * 
                            * - *

                            This Policy implementation supports + *

                            This {@code Policy} implementation supports * special handling for PrivateCredentialPermissions. * If a grant entry is configured with a - * PrivateCredentialPermission, + * {@code PrivateCredentialPermission}, * and the "Principal Class/Principal Name" for that - * PrivateCredentialPermission is "self", - * then the entry grants the specified Subject permission to + * {@code PrivateCredentialPermission} is "self", + * then the entry grants the specified {@code Subject} permission to * access its own private Credential. For example, - * the following grants the Subject "Duke" + * the following grants the {@code Subject} "Duke" * access to its own a.b.Credential. * *

                            @@ -172,7 +172,7 @@ import javax.security.auth.Subject;
                              *    };
                              * 
                            * - * The following grants the Subject "Duke" + * The following grants the {@code Subject} "Duke" * access to all of its own private Credentials: * *
                            @@ -184,7 +184,7 @@ import javax.security.auth.Subject;
                              * 
                            * * The following grants all Subjects authenticated as a - * SolarisPrincipal (regardless of their respective names) + * {@code SolarisPrincipal} (regardless of their respective names) * permission to access their own private Credentials: * *
                            @@ -207,7 +207,7 @@ import javax.security.auth.Subject;
                              * 
                            * @deprecated As of JDK 1.4, replaced by - * sun.security.provider.PolicyFile. + * {@code sun.security.provider.PolicyFile}. * This class is entirely deprecated. * * @see java.security.CodeSource @@ -232,10 +232,8 @@ public class PolicyFile extends javax.security.auth.Policy { /** * Refreshes the policy object by re-reading all the policy files. * - *

                            - * * @exception SecurityException if the caller doesn't have permission - * to refresh the Policy. + * to refresh the {@code Policy}. */ @Override public void refresh() { @@ -243,59 +241,56 @@ public class PolicyFile extends javax.security.auth.Policy { } /** - * Examines this Policy and returns the Permissions granted - * to the specified Subject and CodeSource. + * Examines this {@code Policy} and returns the Permissions granted + * to the specified {@code Subject} and {@code CodeSource}. * *

                            Permissions for a particular grant entry are returned - * if the CodeSource constructed using the codebase and - * signedby values specified in the entry implies - * the CodeSource provided to this method, and if the - * Subject provided to this method contains all of the + * if the {@code CodeSource} constructed using the codebase and + * signedby values specified in the entry {@code implies} + * the {@code CodeSource} provided to this method, and if the + * {@code Subject} provided to this method contains all of the * Principals specified in the entry. * - *

                            The Subject provided to this method contains all + *

                            The {@code Subject} provided to this method contains all * of the Principals specified in the entry if, for each - * Principal, "P1", specified in the grant entry + * {@code Principal}, "P1", specified in the grant entry * one of the following two conditions is met: * - *

                            *

                              - *
                            1. the Subject has a - * Principal, "P2", where - * P2.getClass().getName() equals the + *
                            2. the {@code Subject} has a + * {@code Principal}, "P2", where + * {@code P2.getClass().getName()} equals the * P1's class name, and where - * P2.getName() equals the P1's name. + * {@code P2.getName()} equals the P1's name. * *
                            3. P1 implements - * com.sun.security.auth.PrincipalComparator, - * and P1.implies the provided Subject. + * {@code com.sun.security.auth.PrincipalComparator}, + * and {@code P1.implies} the provided {@code Subject}. *
                            * - *

                            Note that this Policy implementation has + *

                            Note that this {@code Policy} implementation has * special handling for PrivateCredentialPermissions. - * When this method encounters a PrivateCredentialPermission - * which specifies "self" as the Principal class and name, - * it does not add that Permission to the returned - * PermissionCollection. Instead, it builds - * a new PrivateCredentialPermission - * for each Principal associated with the provided - * Subject. Each new PrivateCredentialPermission + * When this method encounters a {@code PrivateCredentialPermission} + * which specifies "self" as the {@code Principal} class and name, + * it does not add that {@code Permission} to the returned + * {@code PermissionCollection}. Instead, it builds + * a new {@code PrivateCredentialPermission} + * for each {@code Principal} associated with the provided + * {@code Subject}. Each new {@code PrivateCredentialPermission} * contains the same Credential class as specified in the * originally granted permission, as well as the Class and name - * for the respective Principal. + * for the respective {@code Principal}. * - *

                            - * - * @param subject the Permissions granted to this Subject - * and the additionally provided CodeSource - * are returned.

                            - * - * @param codesource the Permissions granted to this CodeSource - * and the additionally provided Subject + * @param subject the Permissions granted to this {@code Subject} + * and the additionally provided {@code CodeSource} * are returned. * - * @return the Permissions granted to the provided Subject - * CodeSource. + * @param codesource the Permissions granted to this {@code CodeSource} + * and the additionally provided {@code Subject} + * are returned. + * + * @return the Permissions granted to the provided {@code Subject} + * {@code CodeSource}. */ @Override public PermissionCollection getPermissions(final Subject subject, diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/PrincipalComparator.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/PrincipalComparator.java index 8d8e12424a5..bb0aab1f2f2 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/PrincipalComparator.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/PrincipalComparator.java @@ -26,25 +26,25 @@ package com.sun.security.auth; /** - * An object that implements the java.security.Principal + * An object that implements the {@code java.security.Principal} * interface typically also implements this interface to provide - * a means for comparing that object to a specified Subject. + * a means for comparing that object to a specified {@code Subject}. * - *

                            The comparison is achieved via the implies method. - * The implementation of the implies method determines - * whether this object "implies" the specified Subject. + *

                            The comparison is achieved via the {@code implies} method. + * The implementation of the {@code implies} method determines + * whether this object "implies" the specified {@code Subject}. * One example application of this method may be for - * a "group" object to imply a particular Subject - * if that Subject belongs to the group. + * a "group" object to imply a particular {@code Subject} + * if that {@code Subject} belongs to the group. * Another example application of this method would be for - * "role" object to imply a particular Subject - * if that Subject is currently acting in that role. + * "role" object to imply a particular {@code Subject} + * if that {@code Subject} is currently acting in that role. * *

                            Although classes that implement this interface typically - * also implement the java.security.Principal interface, + * also implement the {@code java.security.Principal} interface, * it is not required. In other words, classes may implement the - * java.security.Principal interface by itself, - * the PrincipalComparator interface by itself, + * {@code java.security.Principal} interface by itself, + * the {@code PrincipalComparator} interface by itself, * or both at the same time. * * @see java.security.Principal @@ -53,12 +53,10 @@ package com.sun.security.auth; @jdk.Exported public interface PrincipalComparator { /** - * Check if the specified Subject is implied by + * Check if the specified {@code Subject} is implied by * this object. * - *

                            - * - * @return true if the specified Subject is implied by + * @return true if the specified {@code Subject} is implied by * this object, or false otherwise. */ boolean implies(javax.security.auth.Subject subject); diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/SolarisNumericGroupPrincipal.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/SolarisNumericGroupPrincipal.java index 27e77307703..377e6165fcd 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/SolarisNumericGroupPrincipal.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/SolarisNumericGroupPrincipal.java @@ -28,15 +28,15 @@ package com.sun.security.auth; import java.security.Principal; /** - *

                            This class implements the Principal interface + * This class implements the {@code Principal} interface * and represents a user's Solaris group identification number (GID). * - *

                            Principals such as this SolarisNumericGroupPrincipal - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code SolarisNumericGroupPrincipal} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * @deprecated As of JDK 1.4, replaced by * {@link UnixNumericGroupPrincipal}. @@ -73,20 +73,18 @@ public class SolarisNumericGroupPrincipal implements private boolean primaryGroup; /** - * Create a SolarisNumericGroupPrincipal using a - * String representation of the user's + * Create a {@code SolarisNumericGroupPrincipal} using a + * {@code String} representation of the user's * group identification number (GID). * - *

                            - * * @param name the user's group identification number (GID) - * for this user.

                            + * for this user. * * @param primaryGroup true if the specified GID represents the * primary group to which this user belongs. * - * @exception NullPointerException if the name - * is null. + * @exception NullPointerException if the {@code name} + * is {@code null}. */ public SolarisNumericGroupPrincipal(String name, boolean primaryGroup) { if (name == null) @@ -97,13 +95,11 @@ public class SolarisNumericGroupPrincipal implements } /** - * Create a SolarisNumericGroupPrincipal using a + * Create a {@code SolarisNumericGroupPrincipal} using a * long representation of the user's group identification number (GID). * - *

                            - * * @param name the user's group identification number (GID) for this user - * represented as a long.

                            + * represented as a long. * * @param primaryGroup true if the specified GID represents the * primary group to which this user belongs. @@ -116,12 +112,10 @@ public class SolarisNumericGroupPrincipal implements /** * Return the user's group identification number (GID) for this - * SolarisNumericGroupPrincipal. - * - *

                            + * {@code SolarisNumericGroupPrincipal}. * * @return the user's group identification number (GID) for this - * SolarisNumericGroupPrincipal + * {@code SolarisNumericGroupPrincipal} */ public String getName() { return name; @@ -129,12 +123,10 @@ public class SolarisNumericGroupPrincipal implements /** * Return the user's group identification number (GID) for this - * SolarisNumericGroupPrincipal as a long. - * - *

                            + * {@code SolarisNumericGroupPrincipal} as a long. * * @return the user's group identification number (GID) for this - * SolarisNumericGroupPrincipal as a long. + * {@code SolarisNumericGroupPrincipal} as a long. */ public long longValue() { return Long.parseLong(name); @@ -144,8 +136,6 @@ public class SolarisNumericGroupPrincipal implements * Return whether this group identification number (GID) represents * the primary group to which this user belongs. * - *

                            - * * @return true if this group identification number (GID) represents * the primary group to which this user belongs, * or false otherwise. @@ -156,12 +146,10 @@ public class SolarisNumericGroupPrincipal implements /** * Return a string representation of this - * SolarisNumericGroupPrincipal. - * - *

                            + * {@code SolarisNumericGroupPrincipal}. * * @return a string representation of this - * SolarisNumericGroupPrincipal. + * {@code SolarisNumericGroupPrincipal}. */ public String toString() { return((primaryGroup ? @@ -173,19 +161,17 @@ public class SolarisNumericGroupPrincipal implements /** * Compares the specified Object with this - * SolarisNumericGroupPrincipal + * {@code SolarisNumericGroupPrincipal} * for equality. Returns true if the given object is also a - * SolarisNumericGroupPrincipal and the two + * {@code SolarisNumericGroupPrincipal} and the two * SolarisNumericGroupPrincipals * have the same group identification number (GID). * - *

                            - * * @param o Object to be compared for equality with this - * SolarisNumericGroupPrincipal. + * {@code SolarisNumericGroupPrincipal}. * * @return true if the specified Object is equal to this - * SolarisNumericGroupPrincipal. + * {@code SolarisNumericGroupPrincipal}. */ public boolean equals(Object o) { if (o == null) @@ -205,11 +191,9 @@ public class SolarisNumericGroupPrincipal implements } /** - * Return a hash code for this SolarisNumericGroupPrincipal. + * Return a hash code for this {@code SolarisNumericGroupPrincipal}. * - *

                            - * - * @return a hash code for this SolarisNumericGroupPrincipal. + * @return a hash code for this {@code SolarisNumericGroupPrincipal}. */ public int hashCode() { return toString().hashCode(); diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/SolarisNumericUserPrincipal.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/SolarisNumericUserPrincipal.java index 0369a7830f6..5497856f28a 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/SolarisNumericUserPrincipal.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/SolarisNumericUserPrincipal.java @@ -28,15 +28,15 @@ package com.sun.security.auth; import java.security.Principal; /** - *

                            This class implements the Principal interface + * This class implements the {@code Principal} interface * and represents a user's Solaris identification number (UID). * - *

                            Principals such as this SolarisNumericUserPrincipal - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code SolarisNumericUserPrincipal} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * @deprecated As of JDK 1.4, replaced by * {@link UnixNumericUserPrincipal}. * This class is entirely deprecated. @@ -68,16 +68,14 @@ public class SolarisNumericUserPrincipal implements private String name; /** - * Create a SolarisNumericUserPrincipal using a - * String representation of the + * Create a {@code SolarisNumericUserPrincipal} using a + * {@code String} representation of the * user's identification number (UID). * - *

                            - * * @param name the user identification number (UID) for this user. * - * @exception NullPointerException if the name - * is null. + * @exception NullPointerException if the {@code name} + * is {@code null}. */ public SolarisNumericUserPrincipal(String name) { if (name == null) @@ -87,11 +85,9 @@ public class SolarisNumericUserPrincipal implements } /** - * Create a SolarisNumericUserPrincipal using a + * Create a {@code SolarisNumericUserPrincipal} using a * long representation of the user's identification number (UID). * - *

                            - * * @param name the user identification number (UID) for this user * represented as a long. */ @@ -101,12 +97,10 @@ public class SolarisNumericUserPrincipal implements /** * Return the user identification number (UID) for this - * SolarisNumericUserPrincipal. - * - *

                            + * {@code SolarisNumericUserPrincipal}. * * @return the user identification number (UID) for this - * SolarisNumericUserPrincipal + * {@code SolarisNumericUserPrincipal} */ public String getName() { return name; @@ -114,12 +108,10 @@ public class SolarisNumericUserPrincipal implements /** * Return the user identification number (UID) for this - * SolarisNumericUserPrincipal as a long. - * - *

                            + * {@code SolarisNumericUserPrincipal} as a long. * * @return the user identification number (UID) for this - * SolarisNumericUserPrincipal as a long. + * {@code SolarisNumericUserPrincipal} as a long. */ public long longValue() { return Long.parseLong(name); @@ -127,12 +119,10 @@ public class SolarisNumericUserPrincipal implements /** * Return a string representation of this - * SolarisNumericUserPrincipal. - * - *

                            + * {@code SolarisNumericUserPrincipal}. * * @return a string representation of this - * SolarisNumericUserPrincipal. + * {@code SolarisNumericUserPrincipal}. */ public String toString() { return(rb.getString("SolarisNumericUserPrincipal.") + name); @@ -140,19 +130,17 @@ public class SolarisNumericUserPrincipal implements /** * Compares the specified Object with this - * SolarisNumericUserPrincipal + * {@code SolarisNumericUserPrincipal} * for equality. Returns true if the given object is also a - * SolarisNumericUserPrincipal and the two + * {@code SolarisNumericUserPrincipal} and the two * SolarisNumericUserPrincipals * have the same user identification number (UID). * - *

                            - * * @param o Object to be compared for equality with this - * SolarisNumericUserPrincipal. + * {@code SolarisNumericUserPrincipal}. * * @return true if the specified Object is equal to this - * SolarisNumericUserPrincipal. + * {@code SolarisNumericUserPrincipal}. */ public boolean equals(Object o) { if (o == null) @@ -167,15 +155,14 @@ public class SolarisNumericUserPrincipal implements if (this.getName().equals(that.getName())) return true; - return false; + + return false; } /** - * Return a hash code for this SolarisNumericUserPrincipal. + * Return a hash code for this {@code SolarisNumericUserPrincipal}. * - *

                            - * - * @return a hash code for this SolarisNumericUserPrincipal. + * @return a hash code for this {@code SolarisNumericUserPrincipal}. */ public int hashCode() { return name.hashCode(); diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/SolarisPrincipal.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/SolarisPrincipal.java index 6fd78fa5cb1..4aef765e813 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/SolarisPrincipal.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/SolarisPrincipal.java @@ -28,15 +28,15 @@ package com.sun.security.auth; import java.security.Principal; /** - *

                            This class implements the Principal interface + * This class implements the {@code Principal} interface * and represents a Solaris user. * - *

                            Principals such as this SolarisPrincipal - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code SolarisPrincipal} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * * @deprecated As of JDK 1.4, replaced by * {@link UnixPrincipal}. @@ -68,12 +68,10 @@ public class SolarisPrincipal implements Principal, java.io.Serializable { /** * Create a SolarisPrincipal with a Solaris username. * - *

                            - * * @param name the Unix username for this user. * - * @exception NullPointerException if the name - * is null. + * @exception NullPointerException if the {@code name} + * is {@code null}. */ public SolarisPrincipal(String name) { if (name == null) @@ -83,40 +81,34 @@ public class SolarisPrincipal implements Principal, java.io.Serializable { } /** - * Return the Unix username for this SolarisPrincipal. + * Return the Unix username for this {@code SolarisPrincipal}. * - *

                            - * - * @return the Unix username for this SolarisPrincipal + * @return the Unix username for this {@code SolarisPrincipal} */ public String getName() { return name; } /** - * Return a string representation of this SolarisPrincipal. + * Return a string representation of this {@code SolarisPrincipal}. * - *

                            - * - * @return a string representation of this SolarisPrincipal. + * @return a string representation of this {@code SolarisPrincipal}. */ public String toString() { return(rb.getString("SolarisPrincipal.") + name); } /** - * Compares the specified Object with this SolarisPrincipal + * Compares the specified Object with this {@code SolarisPrincipal} * for equality. Returns true if the given object is also a - * SolarisPrincipal and the two SolarisPrincipals + * {@code SolarisPrincipal} and the two SolarisPrincipals * have the same username. * - *

                            - * * @param o Object to be compared for equality with this - * SolarisPrincipal. + * {@code SolarisPrincipal}. * * @return true if the specified Object is equal to this - * SolarisPrincipal. + * {@code SolarisPrincipal}. */ public boolean equals(Object o) { if (o == null) @@ -135,11 +127,9 @@ public class SolarisPrincipal implements Principal, java.io.Serializable { } /** - * Return a hash code for this SolarisPrincipal. + * Return a hash code for this {@code SolarisPrincipal}. * - *

                            - * - * @return a hash code for this SolarisPrincipal. + * @return a hash code for this {@code SolarisPrincipal}. */ public int hashCode() { return name.hashCode(); diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/UnixNumericGroupPrincipal.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/UnixNumericGroupPrincipal.java index 5edb8d2a4ec..4a96480db01 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/UnixNumericGroupPrincipal.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/UnixNumericGroupPrincipal.java @@ -28,15 +28,15 @@ package com.sun.security.auth; import java.security.Principal; /** - *

                            This class implements the Principal interface + * This class implements the {@code Principal} interface * and represents a user's Unix group identification number (GID). * - *

                            Principals such as this UnixNumericGroupPrincipal - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code UnixNumericGroupPrincipal} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * * @see java.security.Principal * @see javax.security.auth.Subject @@ -59,20 +59,18 @@ public class UnixNumericGroupPrincipal implements private boolean primaryGroup; /** - * Create a UnixNumericGroupPrincipal using a - * String representation of the user's + * Create a {@code UnixNumericGroupPrincipal} using a + * {@code String} representation of the user's * group identification number (GID). * - *

                            - * * @param name the user's group identification number (GID) - * for this user.

                            + * for this user. * * @param primaryGroup true if the specified GID represents the * primary group to which this user belongs. * - * @exception NullPointerException if the name - * is null. + * @exception NullPointerException if the {@code name} + * is {@code null}. */ public UnixNumericGroupPrincipal(String name, boolean primaryGroup) { if (name == null) { @@ -89,13 +87,11 @@ public class UnixNumericGroupPrincipal implements } /** - * Create a UnixNumericGroupPrincipal using a + * Create a {@code UnixNumericGroupPrincipal} using a * long representation of the user's group identification number (GID). * - *

                            - * * @param name the user's group identification number (GID) for this user - * represented as a long.

                            + * represented as a long. * * @param primaryGroup true if the specified GID represents the * primary group to which this user belongs. @@ -108,12 +104,10 @@ public class UnixNumericGroupPrincipal implements /** * Return the user's group identification number (GID) for this - * UnixNumericGroupPrincipal. - * - *

                            + * {@code UnixNumericGroupPrincipal}. * * @return the user's group identification number (GID) for this - * UnixNumericGroupPrincipal + * {@code UnixNumericGroupPrincipal} */ public String getName() { return name; @@ -121,12 +115,10 @@ public class UnixNumericGroupPrincipal implements /** * Return the user's group identification number (GID) for this - * UnixNumericGroupPrincipal as a long. - * - *

                            + * {@code UnixNumericGroupPrincipal} as a long. * * @return the user's group identification number (GID) for this - * UnixNumericGroupPrincipal as a long. + * {@code UnixNumericGroupPrincipal} as a long. */ public long longValue() { return Long.parseLong(name); @@ -136,8 +128,6 @@ public class UnixNumericGroupPrincipal implements * Return whether this group identification number (GID) represents * the primary group to which this user belongs. * - *

                            - * * @return true if this group identification number (GID) represents * the primary group to which this user belongs, * or false otherwise. @@ -148,12 +138,10 @@ public class UnixNumericGroupPrincipal implements /** * Return a string representation of this - * UnixNumericGroupPrincipal. - * - *

                            + * {@code UnixNumericGroupPrincipal}. * * @return a string representation of this - * UnixNumericGroupPrincipal. + * {@code UnixNumericGroupPrincipal}. */ public String toString() { @@ -176,19 +164,17 @@ public class UnixNumericGroupPrincipal implements /** * Compares the specified Object with this - * UnixNumericGroupPrincipal + * {@code UnixNumericGroupPrincipal} * for equality. Returns true if the given object is also a - * UnixNumericGroupPrincipal and the two + * {@code UnixNumericGroupPrincipal} and the two * UnixNumericGroupPrincipals * have the same group identification number (GID). * - *

                            - * * @param o Object to be compared for equality with this - * UnixNumericGroupPrincipal. + * {@code UnixNumericGroupPrincipal}. * * @return true if the specified Object is equal to this - * UnixNumericGroupPrincipal. + * {@code UnixNumericGroupPrincipal}. */ public boolean equals(Object o) { if (o == null) @@ -208,11 +194,9 @@ public class UnixNumericGroupPrincipal implements } /** - * Return a hash code for this UnixNumericGroupPrincipal. + * Return a hash code for this {@code UnixNumericGroupPrincipal}. * - *

                            - * - * @return a hash code for this UnixNumericGroupPrincipal. + * @return a hash code for this {@code UnixNumericGroupPrincipal}. */ public int hashCode() { return toString().hashCode(); diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/UnixNumericUserPrincipal.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/UnixNumericUserPrincipal.java index bb45c642459..cb252a8966e 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/UnixNumericUserPrincipal.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/UnixNumericUserPrincipal.java @@ -28,15 +28,15 @@ package com.sun.security.auth; import java.security.Principal; /** - *

                            This class implements the Principal interface + * This class implements the {@code Principal} interface * and represents a user's Unix identification number (UID). * - *

                            Principals such as this UnixNumericUserPrincipal - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code UnixNumericUserPrincipal} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * * @see java.security.Principal * @see javax.security.auth.Subject @@ -53,16 +53,14 @@ public class UnixNumericUserPrincipal implements private String name; /** - * Create a UnixNumericUserPrincipal using a - * String representation of the + * Create a {@code UnixNumericUserPrincipal} using a + * {@code String} representation of the * user's identification number (UID). * - *

                            - * * @param name the user identification number (UID) for this user. * - * @exception NullPointerException if the name - * is null. + * @exception NullPointerException if the {@code name} + * is {@code null}. */ public UnixNumericUserPrincipal(String name) { if (name == null) { @@ -78,11 +76,9 @@ public class UnixNumericUserPrincipal implements } /** - * Create a UnixNumericUserPrincipal using a + * Create a {@code UnixNumericUserPrincipal} using a * long representation of the user's identification number (UID). * - *

                            - * * @param name the user identification number (UID) for this user * represented as a long. */ @@ -92,12 +88,10 @@ public class UnixNumericUserPrincipal implements /** * Return the user identification number (UID) for this - * UnixNumericUserPrincipal. - * - *

                            + * {@code UnixNumericUserPrincipal}. * * @return the user identification number (UID) for this - * UnixNumericUserPrincipal + * {@code UnixNumericUserPrincipal} */ public String getName() { return name; @@ -105,12 +99,10 @@ public class UnixNumericUserPrincipal implements /** * Return the user identification number (UID) for this - * UnixNumericUserPrincipal as a long. - * - *

                            + * {@code UnixNumericUserPrincipal} as a long. * * @return the user identification number (UID) for this - * UnixNumericUserPrincipal as a long. + * {@code UnixNumericUserPrincipal} as a long. */ public long longValue() { return Long.parseLong(name); @@ -118,12 +110,10 @@ public class UnixNumericUserPrincipal implements /** * Return a string representation of this - * UnixNumericUserPrincipal. - * - *

                            + * {@code UnixNumericUserPrincipal}. * * @return a string representation of this - * UnixNumericUserPrincipal. + * {@code UnixNumericUserPrincipal}. */ public String toString() { java.text.MessageFormat form = new java.text.MessageFormat @@ -136,19 +126,17 @@ public class UnixNumericUserPrincipal implements /** * Compares the specified Object with this - * UnixNumericUserPrincipal + * {@code UnixNumericUserPrincipal} * for equality. Returns true if the given object is also a - * UnixNumericUserPrincipal and the two + * {@code UnixNumericUserPrincipal} and the two * UnixNumericUserPrincipals * have the same user identification number (UID). * - *

                            - * * @param o Object to be compared for equality with this - * UnixNumericUserPrincipal. + * {@code UnixNumericUserPrincipal}. * * @return true if the specified Object is equal to this - * UnixNumericUserPrincipal. + * {@code UnixNumericUserPrincipal}. */ public boolean equals(Object o) { if (o == null) @@ -167,11 +155,9 @@ public class UnixNumericUserPrincipal implements } /** - * Return a hash code for this UnixNumericUserPrincipal. + * Return a hash code for this {@code UnixNumericUserPrincipal}. * - *

                            - * - * @return a hash code for this UnixNumericUserPrincipal. + * @return a hash code for this {@code UnixNumericUserPrincipal}. */ public int hashCode() { return name.hashCode(); diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/UnixPrincipal.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/UnixPrincipal.java index 140bd8ffcd8..9694bc7a443 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/UnixPrincipal.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/UnixPrincipal.java @@ -28,15 +28,15 @@ package com.sun.security.auth; import java.security.Principal; /** - *

                            This class implements the Principal interface + * This class implements the {@code Principal} interface * and represents a Unix user. * - *

                            Principals such as this UnixPrincipal - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code UnixPrincipal} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * * @see java.security.Principal * @see javax.security.auth.Subject @@ -54,12 +54,10 @@ public class UnixPrincipal implements Principal, java.io.Serializable { /** * Create a UnixPrincipal with a Unix username. * - *

                            - * * @param name the Unix username for this user. * - * @exception NullPointerException if the name - * is null. + * @exception NullPointerException if the {@code name} + * is {@code null}. */ public UnixPrincipal(String name) { if (name == null) { @@ -75,22 +73,18 @@ public class UnixPrincipal implements Principal, java.io.Serializable { } /** - * Return the Unix username for this UnixPrincipal. + * Return the Unix username for this {@code UnixPrincipal}. * - *

                            - * - * @return the Unix username for this UnixPrincipal + * @return the Unix username for this {@code UnixPrincipal} */ public String getName() { return name; } /** - * Return a string representation of this UnixPrincipal. + * Return a string representation of this {@code UnixPrincipal}. * - *

                            - * - * @return a string representation of this UnixPrincipal. + * @return a string representation of this {@code UnixPrincipal}. */ public String toString() { java.text.MessageFormat form = new java.text.MessageFormat @@ -102,18 +96,16 @@ public class UnixPrincipal implements Principal, java.io.Serializable { } /** - * Compares the specified Object with this UnixPrincipal + * Compares the specified Object with this {@code UnixPrincipal} * for equality. Returns true if the given object is also a - * UnixPrincipal and the two UnixPrincipals + * {@code UnixPrincipal} and the two UnixPrincipals * have the same username. * - *

                            - * * @param o Object to be compared for equality with this - * UnixPrincipal. + * {@code UnixPrincipal}. * * @return true if the specified Object is equal to this - * UnixPrincipal. + * {@code UnixPrincipal}. */ public boolean equals(Object o) { if (o == null) @@ -132,11 +124,9 @@ public class UnixPrincipal implements Principal, java.io.Serializable { } /** - * Return a hash code for this UnixPrincipal. + * Return a hash code for this {@code UnixPrincipal}. * - *

                            - * - * @return a hash code for this UnixPrincipal. + * @return a hash code for this {@code UnixPrincipal}. */ public int hashCode() { return name.hashCode(); diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/X500Principal.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/X500Principal.java index c4b12bdb28b..52fdcf868c9 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/X500Principal.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/X500Principal.java @@ -29,17 +29,17 @@ import java.security.Principal; import sun.security.x509.X500Name; /** - *

                            This class represents an X.500 Principal. + * This class represents an X.500 {@code Principal}. * X500Principals have names such as, * "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US" * (RFC 1779 style). * - *

                            Principals such as this X500Principal - * may be associated with a particular Subject - * to augment that Subject with an additional - * identity. Refer to the Subject class for more information + *

                            Principals such as this {@code X500Principal} + * may be associated with a particular {@code Subject} + * to augment that {@code Subject} with an additional + * identity. Refer to the {@code Subject} class for more information * on how to achieve this. Authorization decisions can then be based upon - * the Principals associated with a Subject. + * the Principals associated with a {@code Subject}. * * @see java.security.Principal * @see javax.security.auth.Subject @@ -76,14 +76,12 @@ public class X500Principal implements Principal, java.io.Serializable { * such as "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US" * (RFC 1779 style). * - *

                            - * * @param name the X.500 name * - * @exception NullPointerException if the name - * is null.

                            + * @exception NullPointerException if the {@code name} + * is {@code null}. * - * @exception IllegalArgumentException if the name + * @exception IllegalArgumentException if the {@code name} * is improperly specified. */ public X500Principal(String name) { @@ -100,38 +98,32 @@ public class X500Principal implements Principal, java.io.Serializable { } /** - * Return the Unix username for this X500Principal. + * Return the Unix username for this {@code X500Principal}. * - *

                            - * - * @return the Unix username for this X500Principal + * @return the Unix username for this {@code X500Principal} */ public String getName() { return thisX500Name.getName(); } /** - * Return a string representation of this X500Principal. + * Return a string representation of this {@code X500Principal}. * - *

                            - * - * @return a string representation of this X500Principal. + * @return a string representation of this {@code X500Principal}. */ public String toString() { return thisX500Name.toString(); } /** - * Compares the specified Object with this X500Principal + * Compares the specified Object with this {@code X500Principal} * for equality. * - *

                            - * * @param o Object to be compared for equality with this - * X500Principal. + * {@code X500Principal}. * * @return true if the specified Object is equal to this - * X500Principal. + * {@code X500Principal}. */ public boolean equals(Object o) { if (o == null) @@ -159,11 +151,9 @@ public class X500Principal implements Principal, java.io.Serializable { } /** - * Return a hash code for this X500Principal. + * Return a hash code for this {@code X500Principal}. * - *

                            - * - * @return a hash code for this X500Principal. + * @return a hash code for this {@code X500Principal}. */ public int hashCode() { return thisX500Name.hashCode(); diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/JndiLoginModule.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/JndiLoginModule.java index e287f858804..08e359b9b8e 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/JndiLoginModule.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/JndiLoginModule.java @@ -44,28 +44,28 @@ import com.sun.security.auth.UnixNumericGroupPrincipal; /** - *

                            The module prompts for a username and password + * The module prompts for a username and password * and then verifies the password against the password stored in * a directory service configured under JNDI. * - *

                            This LoginModule interoperates with + *

                            This {@code LoginModule} interoperates with * any conformant JNDI service provider. To direct this - * LoginModule to use a specific JNDI service provider, - * two options must be specified in the login Configuration - * for this LoginModule. + * {@code LoginModule} to use a specific JNDI service provider, + * two options must be specified in the login {@code Configuration} + * for this {@code LoginModule}. *

                              *      user.provider.url=name_service_url
                              *      group.provider.url=name_service_url
                              * 
                            * * name_service_url specifies - * the directory service and path where this LoginModule + * the directory service and path where this {@code LoginModule} * can access the relevant user and group information. Because this - * LoginModule only performs one-level searches to - * find the relevant user information, the URL + * {@code LoginModule} only performs one-level searches to + * find the relevant user information, the {@code URL} * must point to a directory one level above where the user and group * information is stored in the directory service. - * For example, to instruct this LoginModule + * For example, to instruct this {@code LoginModule} * to contact a NIS server, the following URLs must be specified: *
                              *    user.provider.url="nis://NISServerHostName/NISDomain/user"
                            @@ -90,14 +90,14 @@ import com.sun.security.auth.UnixNumericGroupPrincipal;
                              *
                              * 

                            The format in which the user's information must be stored in * the directory service is specified in RFC 2307. Specifically, - * this LoginModule will search for the user's entry in the + * this {@code LoginModule} will search for the user's entry in the * directory service using the user's uid attribute, * where uid=username. If the search succeeds, - * this LoginModule will then + * this {@code LoginModule} will then * obtain the user's encrypted password from the retrieved entry * using the userPassword attribute. - * This LoginModule assumes that the password is stored - * as a byte array, which when converted to a String, + * This {@code LoginModule} assumes that the password is stored + * as a byte array, which when converted to a {@code String}, * has the following format: *

                              *      "{crypt}encrypted_password"
                            @@ -106,12 +106,12 @@ import com.sun.security.auth.UnixNumericGroupPrincipal;
                              * The LDAP directory server must be configured
                              * to permit read access to the userPassword attribute.
                              * If the user entered a valid username and password,
                            - * this LoginModule associates a
                            - * UnixPrincipal, UnixNumericUserPrincipal,
                            + * this {@code LoginModule} associates a
                            + * {@code UnixPrincipal}, {@code UnixNumericUserPrincipal},
                              * and the relevant UnixNumericGroupPrincipals with the
                            - * Subject.
                            + * {@code Subject}.
                              *
                            - * 

                            This LoginModule also recognizes the following Configuration + *

                            This LoginModule also recognizes the following {@code Configuration} * options: *

                              *    debug          if, true, debug messages are output to System.out.
                            @@ -144,7 +144,7 @@ import com.sun.security.auth.UnixNumericGroupPrincipal;
                              *                   exist for the username and password in the shared state,
                              *                   or if authentication fails.
                              *
                            - *    clearPass     if, true, this LoginModule clears the
                            + *    clearPass     if, true, this {@code LoginModule} clears the
                              *                  username and password stored in the module's shared state
                              *                  after both phases of authentication (login and commit)
                              *                  have completed.
                            @@ -208,21 +208,19 @@ public class JndiLoginModule implements LoginModule {
                                 private static final String PWD = "javax.security.auth.login.password";
                             
                                 /**
                            -     * Initialize this LoginModule.
                            +     * Initialize this {@code LoginModule}.
                                  *
                            -     * 

                            + * @param subject the {@code Subject} to be authenticated. * - * @param subject the Subject to be authenticated.

                            - * - * @param callbackHandler a CallbackHandler for communicating + * @param callbackHandler a {@code CallbackHandler} for communicating * with the end user (prompting for usernames and - * passwords, for example).

                            + * passwords, for example). * - * @param sharedState shared LoginModule state.

                            + * @param sharedState shared {@code LoginModule} state. * * @param options options specified in the login - * Configuration for this particular - * LoginModule. + * {@code Configuration} for this particular + * {@code LoginModule}. */ // Unchecked warning from (Map)sharedState is safe // since javax.security.auth.login.LoginContext passes a raw HashMap. @@ -255,17 +253,15 @@ public class JndiLoginModule implements LoginModule { } /** - *

                            Prompt for username and password. + * Prompt for username and password. * Verify the password against the relevant name service. * - *

                            - * - * @return true always, since this LoginModule + * @return true always, since this {@code LoginModule} * should not be ignored. * - * @exception FailedLoginException if the authentication fails.

                            + * @exception FailedLoginException if the authentication fails. * - * @exception LoginException if this LoginModule + * @exception LoginException if this {@code LoginModule} * is unable to perform the authentication. */ public boolean login() throws LoginException { @@ -367,15 +363,13 @@ public class JndiLoginModule implements LoginModule { * *

                            If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the - * login method), then this method associates a - * UnixPrincipal - * with the Subject located in the - * LoginModule. If this LoginModule's own + * {@code login} method), then this method associates a + * {@code UnixPrincipal} + * with the {@code Subject} located in the + * {@code LoginModule}. If this LoginModule's own * authentication attempted failed, then this method removes * any state that was originally saved. * - *

                            - * * @exception LoginException if the commit fails * * @return true if this LoginModule's own login and commit @@ -418,18 +412,16 @@ public class JndiLoginModule implements LoginModule { } /** - *

                            This method is called if the LoginContext's + * This method is called if the LoginContext's * overall authentication failed. * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules * did not succeed). * *

                            If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the - * login and commit methods), + * {@code login} and {@code commit} methods), * then this method cleans up any state that was originally saved. * - *

                            - * * @exception LoginException if the abort fails. * * @return false if this LoginModule's own login and/or commit attempts @@ -464,13 +456,11 @@ public class JndiLoginModule implements LoginModule { * Logout a user. * *

                            This method removes the Principals - * that were added by the commit method. - * - *

                            + * that were added by the {@code commit} method. * * @exception LoginException if the logout fails. * - * @return true in all cases since this LoginModule + * @return true in all cases since this {@code LoginModule} * should not be ignored. */ public boolean logout() throws LoginException { @@ -506,8 +496,6 @@ public class JndiLoginModule implements LoginModule { /** * Attempt authentication * - *

                            - * * @param getPasswdFromSharedState boolean that tells this method whether * to retrieve the password from the sharedState. */ @@ -674,8 +662,6 @@ public class JndiLoginModule implements LoginModule { * values in the shared state in case subsequent LoginModules * want to use them via use/tryFirstPass. * - *

                            - * * @param getPasswdFromSharedState boolean that tells this method whether * to retrieve the password from the sharedState. */ diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/KeyStoreLoginModule.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/KeyStoreLoginModule.java index 248afb53a9b..ece0d3f8afb 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/KeyStoreLoginModule.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/KeyStoreLoginModule.java @@ -55,53 +55,53 @@ import sun.security.util.Password; /** * Provides a JAAS login module that prompts for a key store alias and * populates the subject with the alias's principal and credentials. Stores - * an X500Principal for the subject distinguished name of the + * an {@code X500Principal} for the subject distinguished name of the * first certificate in the alias's credentials in the subject's principals, * the alias's certificate path in the subject's public credentials, and a - * X500PrivateCredential whose certificate is the first + * {@code X500PrivateCredential} whose certificate is the first * certificate in the alias's certificate path and whose private key is the * alias's private key in the subject's private credentials.

                            * * Recognizes the following options in the configuration file: *

                            * - *
                            keyStoreURL
                            + *
                            {@code keyStoreURL}
                            *
                            A URL that specifies the location of the key store. Defaults to * a URL pointing to the .keystore file in the directory specified by the - * user.home system property. The input stream from this - * URL is passed to the KeyStore.load method. - * "NONE" may be specified if a null stream must be - * passed to the KeyStore.load method. + * {@code user.home} system property. The input stream from this + * URL is passed to the {@code KeyStore.load} method. + * "NONE" may be specified if a {@code null} stream must be + * passed to the {@code KeyStore.load} method. * "NONE" should be specified if the KeyStore resides * on a hardware token device, for example.
                            * - *
                            keyStoreType
                            + *
                            {@code keyStoreType}
                            *
                            The key store type. If not specified, defaults to the result of - * calling KeyStore.getDefaultType(). + * calling {@code KeyStore.getDefaultType()}. * If the type is "PKCS11", then keyStoreURL must be "NONE" * and privateKeyPasswordURL must not be specified.
                            * - *
                            keyStoreProvider
                            + *
                            {@code keyStoreProvider}
                            *
                            The key store provider. If not specified, uses the standard search * order to find the provider.
                            * - *
                            keyStoreAlias
                            + *
                            {@code keyStoreAlias}
                            *
                            The alias in the key store to login as. Required when no callback * handler is provided. No default value.
                            * - *
                            keyStorePasswordURL
                            + *
                            {@code keyStorePasswordURL}
                            *
                            A URL that specifies the location of the key store password. Required * when no callback handler is provided and - * protected is false. + * {@code protected} is false. * No default value.
                            * - *
                            privateKeyPasswordURL
                            + *
                            {@code privateKeyPasswordURL}
                            *
                            A URL that specifies the location of the specific private key password * needed to access the private key for this alias. * The keystore password * is used if this value is needed and not specified.
                            * - *
                            protected
                            + *
                            {@code protected}
                            *
                            This value should be set to "true" if the KeyStore * has a separate, protected authentication path * (for example, a dedicated PIN-pad attached to a smart card). @@ -174,22 +174,20 @@ public class KeyStoreLoginModule implements LoginModule { /* -- Methods -- */ /** - * Initialize this LoginModule. + * Initialize this {@code LoginModule}. * - *

                            + * @param subject the {@code Subject} to be authenticated. * - * @param subject the Subject to be authenticated.

                            - * - * @param callbackHandler a CallbackHandler for communicating + * @param callbackHandler a {@code CallbackHandler} for communicating * with the end user (prompting for usernames and * passwords, for example), - * which may be null.

                            + * which may be {@code null}. * - * @param sharedState shared LoginModule state.

                            + * @param sharedState shared {@code LoginModule} state. * * @param options options specified in the login - * Configuration for this particular - * LoginModule. + * {@code Configuration} for this particular + * {@code LoginModule}. */ // Unchecked warning from (Map)sharedState is safe // since javax.security.auth.login.LoginContext passes a raw HashMap. @@ -258,11 +256,9 @@ public class KeyStoreLoginModule implements LoginModule { *

                            Get the Keystore alias and relevant passwords. * Retrieve the alias's principal and credentials from the Keystore. * - *

                            + * @exception FailedLoginException if the authentication fails. * - * @exception FailedLoginException if the authentication fails.

                            - * - * @return true in all cases (this LoginModule + * @return true in all cases (this {@code LoginModule} * should not be ignored). */ @@ -719,19 +715,17 @@ public class KeyStoreLoginModule implements LoginModule { * *

                            If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the - * login method), then this method associates a - * X500Principal for the subject distinguished name of the + * {@code login} method), then this method associates a + * {@code X500Principal} for the subject distinguished name of the * first certificate in the alias's credentials in the subject's * principals,the alias's certificate path in the subject's public - * credentials, and aX500PrivateCredential whose certificate + * credentials, and a {@code X500PrivateCredential} whose certificate * is the first certificate in the alias's certificate path and whose * private key is the alias's private key in the subject's private * credentials. If this LoginModule's own * authentication attempted failed, then this method removes * any state that was originally saved. * - *

                            - * * @exception LoginException if the commit fails * * @return true if this LoginModule's own login and commit @@ -774,21 +768,19 @@ public class KeyStoreLoginModule implements LoginModule { } /** - *

                            This method is called if the LoginContext's + * This method is called if the LoginContext's * overall authentication failed. * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules * did not succeed). * *

                            If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the - * login and commit methods), + * {@code login} and {@code commit} methods), * then this method cleans up any state that was originally saved. * *

                            If the loaded KeyStore's provider extends - * java.security.AuthProvider, - * then the provider's logout method is invoked. - * - *

                            + * {@code java.security.AuthProvider}, + * then the provider's {@code logout} method is invoked. * * @exception LoginException if the abort fails. * @@ -815,17 +807,15 @@ public class KeyStoreLoginModule implements LoginModule { * Logout a user. * *

                            This method removes the Principals, public credentials and the - * private credentials that were added by the commit method. + * private credentials that were added by the {@code commit} method. * *

                            If the loaded KeyStore's provider extends - * java.security.AuthProvider, - * then the provider's logout method is invoked. - * - *

                            + * {@code java.security.AuthProvider}, + * then the provider's {@code logout} method is invoked. * * @exception LoginException if the logout fails. * - * @return true in all cases since this LoginModule + * @return true in all cases since this {@code LoginModule} * should not be ignored. */ diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Krb5LoginModule.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Krb5LoginModule.java index 12ee20b126b..5bd179db91a 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Krb5LoginModule.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Krb5LoginModule.java @@ -47,147 +47,142 @@ import sun.security.krb5.Credentials; import sun.misc.HexDumpEncoder; /** - *

                            This LoginModule authenticates users using + * This {@code LoginModule} authenticates users using * Kerberos protocols. * - *

                            The configuration entry for Krb5LoginModule has + *

                            The configuration entry for {@code Krb5LoginModule} has * several options that control the authentication process and - * additions to the Subject's private credential - * set. Irrespective of these options, the Subject's + * additions to the {@code Subject}'s private credential + * set. Irrespective of these options, the {@code Subject}'s * principal set and private credentials set are updated only when - * commit is called. - * When commit is called, the KerberosPrincipal - * is added to the Subject's principal set (unless the - * principal is specified as "*"). If isInitiator - * is true, the KerberosTicket is - * added to the Subject's private credentials. + * {@code commit} is called. + * When {@code commit} is called, the {@code KerberosPrincipal} + * is added to the {@code Subject}'s principal set (unless the + * {@code principal} is specified as "*"). If {@code isInitiator} + * is true, the {@code KerberosTicket} is + * added to the {@code Subject}'s private credentials. * - *

                            If the configuration entry for KerberosLoginModule - * has the option storeKey set to true, then - * KerberosKey or KeyTab will also be added to the - * subject's private credentials. KerberosKey, the principal's - * key(s) will be derived from user's password, and KeyTab is - * the keytab used when useKeyTab is set to true. The - * KeyTab object is restricted to be used by the specified + *

                            If the configuration entry for {@code KerberosLoginModule} + * has the option {@code storeKey} set to true, then + * {@code KerberosKey} or {@code KeyTab} will also be added to the + * subject's private credentials. {@code KerberosKey}, the principal's + * key(s) will be derived from user's password, and {@code KeyTab} is + * the keytab used when {@code useKeyTab} is set to true. The + * {@code KeyTab} object is restricted to be used by the specified * principal unless the principal value is "*". * - *

                            This LoginModule recognizes the doNotPrompt + *

                            This {@code LoginModule} recognizes the {@code doNotPrompt} * option. If set to true the user will not be prompted for the password. * *

                            The user can specify the location of the ticket cache by using - * the option ticketCache in the configuration entry. + * the option {@code ticketCache} in the configuration entry. * *

                            The user can specify the keytab location by using - * the option keyTab + * the option {@code keyTab} * in the configuration entry. * *

                            The principal name can be specified in the configuration entry - * by using the option principal. The principal name + * by using the option {@code principal}. The principal name * can either be a simple user name, a service name such as - * host/mission.eng.sun.com, or "*". The principal can also - * be set using the system property sun.security.krb5.principal. + * {@code host/mission.eng.sun.com}, or "*". The principal can also + * be set using the system property {@code sun.security.krb5.principal}. * This property is checked during login. If this property is not set, then * the principal name from the configuration is used. In the * case where the principal property is not set and the principal * entry also does not exist, the user is prompted for the name. - * When this property of entry is set, and useTicketCache + * When this property of entry is set, and {@code useTicketCache} * is set to true, only TGT belonging to this principal is used. * *

                            The following is a list of configuration options supported - * for Krb5LoginModule: + * for {@code Krb5LoginModule}: *

                            - *
                            refreshKrb5Config:
                            + *
                            {@code refreshKrb5Config}:
                            *
                            Set this to true, if you want the configuration - * to be refreshed before the login method is called.
                            - *
                            useTicketCache:
                            + * to be refreshed before the {@code login} method is called.
                            + *
                            {@code useTicketCache}:
                            *
                            Set this to true, if you want the - * TGT to be obtained - * from the ticket cache. Set this option + * TGT to be obtained from the ticket cache. Set this option * to false if you do not want this module to use the ticket cache. * (Default is False). - * This module will - * search for the ticket - * cache in the following locations: - * On Solaris and Linux - * it will look for the ticket cache in /tmp/krb5cc_uid - * where the uid is numeric user - * identifier. If the ticket cache is + * This module will search for the ticket + * cache in the following locations: On Solaris and Linux + * it will look for the ticket cache in /tmp/krb5cc_{@code uid} + * where the uid is numeric user identifier. If the ticket cache is * not available in the above location, or if we are on a * Windows platform, it will look for the cache as * {user.home}{file.separator}krb5cc_{user.name}. * You can override the ticket cache location by using - * ticketCache. + * {@code ticketCache}. * For Windows, if a ticket cannot be retrieved from the file ticket cache, * it will use Local Security Authority (LSA) API to get the TGT. - *
                            ticketCache:
                            + *
                            {@code ticketCache}:
                            *
                            Set this to the name of the ticket * cache that contains user's TGT. - * If this is set, useTicketCache + * If this is set, {@code useTicketCache} * must also be set to true; Otherwise a configuration error will * be returned.
                            - *
                            renewTGT:
                            + *
                            {@code renewTGT}:
                            *
                            Set this to true, if you want to renew - * the TGT. If this is set, useTicketCache must also be + * the TGT. If this is set, {@code useTicketCache} must also be * set to true; otherwise a configuration error will be returned.
                            - *
                            doNotPrompt:
                            + *
                            {@code doNotPrompt}:
                            *
                            Set this to true if you do not want to be * prompted for the password * if credentials can not be obtained from the cache, the keytab, * or through shared state.(Default is false) * If set to true, credential must be obtained through cache, keytab, * or shared state. Otherwise, authentication will fail.
                            - *
                            useKeyTab:
                            + *
                            {@code useKeyTab}:
                            *
                            Set this to true if you * want the module to get the principal's key from the * the keytab.(default value is False) - * If keytab - * is not set then + * If {@code keytab} is not set then * the module will locate the keytab from the * Kerberos configuration file. * If it is not specified in the Kerberos configuration file * then it will look for the file - * {user.home}{file.separator}krb5.keytab.
                            - *
                            keyTab:
                            + * {@code {user.home}{file.separator}}krb5.keytab. + *
                            {@code keyTab}:
                            *
                            Set this to the file name of the * keytab to get principal's secret key.
                            - *
                            storeKey:
                            + *
                            {@code storeKey}:
                            *
                            Set this to true to if you want the keytab or the * principal's key to be stored in the Subject's private credentials. - * For isInitiator being false, if principal + * For {@code isInitiator} being false, if {@code principal} * is "*", the {@link KeyTab} stored can be used by anyone, otherwise, * it's restricted to be used by the specified principal only.
                            - *
                            principal:
                            + *
                            {@code principal}:
                            *
                            The name of the principal that should * be used. The principal can be a simple username such as - * "testuser" or a service name such as - * "host/testhost.eng.sun.com". You can use the - * principal option to set the principal when there are + * "{@code testuser}" or a service name such as + * "{@code host/testhost.eng.sun.com}". You can use the + * {@code principal} option to set the principal when there are * credentials for multiple principals in the - * keyTab or when you want a specific ticket cache only. + * {@code keyTab} or when you want a specific ticket cache only. * The principal can also be set using the system property - * sun.security.krb5.principal. In addition, if this + * {@code sun.security.krb5.principal}. In addition, if this * system property is defined, then it will be used. If this property * is not set, then the principal name from the configuration will be * used. - * The principal name can be set to "*" when isInitiator is false. + * The principal name can be set to "*" when {@code isInitiator} is false. * In this case, the acceptor is not bound to a single principal. It can * act as any principal an initiator requests if keys for that principal - * can be found. When isInitiator is true, the principal name + * can be found. When {@code isInitiator} is true, the principal name * cannot be set to "*". *
                            - *
                            isInitiator:
                            + *
                            {@code isInitiator}:
                            *
                            Set this to true, if initiator. Set this to false, if acceptor only. * (Default is true). * Note: Do not set this value to false for initiators.
                            *
                            * - *

                            This LoginModule also recognizes the following additional - * Configuration + *

                            This {@code LoginModule} also recognizes the following additional + * {@code Configuration} * options that enable you to share username and passwords across different * authentication modules: *

                            * - *
                            useFirstPass:
                            + *
                            {@code useFirstPass}:
                            *
                            if, true, this LoginModule retrieves the * username and password from the module's shared state, * using "javax.security.auth.login.name" and @@ -197,7 +192,7 @@ import sun.misc.HexDumpEncoder; * is made, and the failure is reported back to the * calling application.
                            * - *
                            tryFirstPass:
                            + *
                            {@code tryFirstPass}:
                            *
                            if, true, this LoginModule retrieves the * the username and password from the module's shared * state using "javax.security.auth.login.name" and @@ -210,7 +205,7 @@ import sun.misc.HexDumpEncoder; * is made. If the authentication fails, * the failure is reported back to the calling application
                            * - *
                            storePass:
                            + *
                            {@code storePass}:
                            *
                            if, true, this LoginModule stores the username and * password obtained from the CallbackHandler in the * modules shared state, using @@ -220,7 +215,7 @@ import sun.misc.HexDumpEncoder; * exist for the username and password in the shared * state, or if authentication fails.
                            * - *
                            clearPass:
                            + *
                            {@code clearPass}:
                            *
                            if, true, this LoginModule clears the * username and password stored in the module's shared * state after both phases of authentication @@ -236,148 +231,137 @@ import sun.misc.HexDumpEncoder; *
                          2. shared state *
                          3. user prompt *
                          + * *

                          Note that if any step fails, it will fallback to the next step. * There's only one exception, if the shared state step fails and - * useFirstPass=true, no user prompt is made. + * {@code useFirstPass = true}, no user prompt is made. *

                          Examples of some configuration values for Krb5LoginModule in * JAAS config file and the results are: - *

                            - *

                            doNotPrompt=true; - *

                          - *

                          This is an illegal combination since none of useTicketCache, - * useKeyTab, useFirstPass and tryFirstPass - * is set and the user can not be prompted for the password. - *

                            - *

                            ticketCache = <filename>; - *

                          - *

                          This is an illegal combination since useTicketCache + *

                          + *
                          {@code
                          + * doNotPrompt = true}
                          + * This is an illegal combination since none of {@code useTicketCache, + * useKeyTab, useFirstPass} and {@code tryFirstPass} + * is set and the user can not be prompted for the password.
                          + * + *
                          {@code
                          + * ticketCache = }
                          + * This is an illegal combination since {@code useTicketCache} * is not set to true and the ticketCache is set. A configuration error - * will occur. - *
                            - *

                            renewTGT=true; - *

                          - *

                          This is an illegal combination since useTicketCache is - * not set to true and renewTGT is set. A configuration error will occur. - *

                            - *

                            storeKey=true - * useTicketCache = true - * doNotPrompt=true;; - *

                          - *

                          This is an illegal combination since storeKey is set to + * will occur.

                          + * + *
                          {@code
                          + * renewTGT = true}
                          + * This is an illegal combination since {@code useTicketCache} is + * not set to true and renewTGT is set. A configuration error will occur.
                          + * + *
                          {@code
                          + * storeKey = true  useTicketCache = true  doNotPrompt = true}
                          + * This is an illegal combination since {@code storeKey} is set to * true but the key can not be obtained either by prompting the user or from - * the keytab, or from the shared state. A configuration error will occur. - *
                            - *

                            keyTab = <filename> doNotPrompt=true ; - *

                          - *

                          This is an illegal combination since useKeyTab is not set to true and - * the keyTab is set. A configuration error will occur. - *

                            - *

                            debug=true - *

                          - *

                          Prompt the user for the principal name and the password. + * the keytab, or from the shared state. A configuration error will occur.

                          + * + *
                          {@code
                          + * keyTab =   doNotPrompt = true}
                          + * This is an illegal combination since useKeyTab is not set to true and + * the keyTab is set. A configuration error will occur.
                          + * + *
                          {@code
                          + * debug = true}
                          + * Prompt the user for the principal name and the password. * Use the authentication exchange to get TGT from the KDC and - * populate the Subject with the principal and TGT. - * Output debug messages. - *
                            - *

                            useTicketCache = true doNotPrompt=true; - *

                          - *

                          Check the default cache for TGT and populate the Subject + * populate the {@code Subject} with the principal and TGT. + * Output debug messages.

                          + * + *
                          {@code
                          + * useTicketCache = true  doNotPrompt = true}
                          + * Check the default cache for TGT and populate the {@code Subject} * with the principal and TGT. If the TGT is not available, - * do not prompt the user, instead fail the authentication. - *
                            - *

                            principal=<name>useTicketCache = true - * doNotPrompt=true; - *

                          - *

                          Get the TGT from the default cache for the principal and populate the + * do not prompt the user, instead fail the authentication.

                          + * + *
                          {@code
                          + * principal =   useTicketCache = true  doNotPrompt = true}
                          + * Get the TGT from the default cache for the principal and populate the * Subject's principal and private creds set. If ticket cache is * not available or does not contain the principal's TGT - * authentication will fail. - *
                            - *

                            useTicketCache = true - * ticketCache=<file name>useKeyTab = true - * keyTab=<keytab filename> - * principal = <principal name> - * doNotPrompt=true; - *

                          - *

                          Search the cache for the principal's TGT. If it is not available + * authentication will fail.

                          + * + *
                          {@code
                          + * useTicketCache = true
                          + * ticketCache = 
                          + * useKeyTab = true
                          + * keyTab = 
                          + * principal = 
                          + * doNotPrompt = true}
                          + * Search the cache for the principal's TGT. If it is not available * use the key in the keytab to perform authentication exchange with the * KDC and acquire the TGT. * The Subject will be populated with the principal and the TGT. - * If the key is not available or valid then authentication will fail. - *
                            - *

                            useTicketCache = true - * ticketCache=<file name> - *

                          - *

                          The TGT will be obtained from the cache specified. + * If the key is not available or valid then authentication will fail.

                          + * + *
                          {@code
                          + * useTicketCache = true  ticketCache = }
                          + * The TGT will be obtained from the cache specified. * The Kerberos principal name used will be the principal name in * the Ticket cache. If the TGT is not available in the * ticket cache the user will be prompted for the principal name * and the password. The TGT will be obtained using the authentication * exchange with the KDC. - * The Subject will be populated with the TGT. - *
                            - *

                            useKeyTab = true - * keyTab=<keytab filename> - * principal= <principal name> - * storeKey=true; - *

                          - *

                          The key for the principal will be retrieved from the keytab. + * The Subject will be populated with the TGT.

                          + * + *
                          {@code
                          + * useKeyTab = true  keyTab=  principal =   storeKey = true}
                          + * The key for the principal will be retrieved from the keytab. * If the key is not available in the keytab the user will be prompted * for the principal's password. The Subject will be populated * with the principal's key either from the keytab or derived from the - * password entered. - *
                            - *

                            useKeyTab = true - * keyTab=<keytabname> - * storeKey=true - * doNotPrompt=false; - *

                          - *

                          The user will be prompted for the service principal name. + * password entered.

                          + * + *
                          {@code
                          + * useKeyTab = true  keyTab =   storeKey = true  doNotPrompt = false}
                          + * The user will be prompted for the service principal name. * If the principal's * longterm key is available in the keytab , it will be added to the * Subject's private credentials. An authentication exchange will be * attempted with the principal name and the key from the Keytab. * If successful the TGT will be added to the - * Subject's private credentials set. Otherwise the authentication will - * fail. - *
                            - *

                            isInitiator = false useKeyTab = true - * keyTab=<keytabname> - * storeKey=true - * principal=*; - *

                          - *

                          The acceptor will be an unbound acceptor and it can act as any principal - * as long that principal has keys in the keytab. - *

                            - *

                            - * useTicketCache=true - * ticketCache=<file name>; - * useKeyTab = true - * keyTab=<file name> storeKey=true - * principal= <principal name> - *

                          - *

                          + * Subject's private credentials set. Otherwise the authentication will fail.

                          + * + *
                          {@code
                          + * isInitiator = false  useKeyTab = true  keyTab =   storeKey = true  principal = *}
                          + * The acceptor will be an unbound acceptor and it can act as any principal + * as long that principal has keys in the keytab.
                          + * + *
                          {@code
                          + * useTicketCache = true
                          + * ticketCache = 
                          + * useKeyTab = true
                          + * keyTab = 
                          + * storeKey = true
                          + * principal = }
                          * The client's TGT will be retrieved from the ticket cache and added to the - * Subject's private credentials. If the TGT is not available + * {@code Subject}'s private credentials. If the TGT is not available * in the ticket cache, or the TGT's client name does not match the principal * name, Java will use a secret key to obtain the TGT using the authentication * exchange and added to the Subject's private credentials. * This secret key will be first retrieved from the keytab. If the key * is not available, the user will be prompted for the password. In either * case, the key derived from the password will be added to the - * Subject's private credentials set. - *
                            - *

                            isInitiator = false - *

                          - *

                          Configured to act as acceptor only, credentials are not acquired + * Subject's private credentials set.

                          + * + *
                          {@code
                          + * isInitiator = false}
                          + * Configured to act as acceptor only, credentials are not acquired * via AS exchange. For acceptors only, set this value to false. - * For initiators, do not set this value to false. - *
                            - *

                            isInitiator = true - *

                          - *

                          Configured to act as initiator, credentials are acquired + * For initiators, do not set this value to false.

                          + * + *
                          {@code
                          + * isInitiator = true}
                          + * Configured to act as initiator, credentials are acquired * via AS exchange. For initiators, set this value to true, or leave this - * option unset, in which case default value (true) will be used. + * option unset, in which case default value (true) will be used.
                          + * + *
                          * * @author Ram Marti */ @@ -445,20 +429,19 @@ public class Krb5LoginModule implements LoginModule { ); /** - * Initialize this LoginModule. + * Initialize this {@code LoginModule}. * - *

                          - * @param subject the Subject to be authenticated.

                          + * @param subject the {@code Subject} to be authenticated. * - * @param callbackHandler a CallbackHandler for + * @param callbackHandler a {@code CallbackHandler} for * communication with the end user (prompting for - * usernames and passwords, for example).

                          + * usernames and passwords, for example). * - * @param sharedState shared LoginModule state.

                          + * @param sharedState shared {@code LoginModule} state. * * @param options options specified in the login - * Configuration for this particular - * LoginModule. + * {@code Configuration} for this particular + * {@code LoginModule}. */ // Unchecked warning from (Map)sharedState is safe // since javax.security.auth.login.LoginContext passes a raw HashMap. @@ -536,14 +519,12 @@ public class Krb5LoginModule implements LoginModule { /** * Authenticate the user * - *

                          - * - * @return true in all cases since this LoginModule + * @return true in all cases since this {@code LoginModule} * should not be ignored. * - * @exception FailedLoginException if the authentication fails.

                          + * @exception FailedLoginException if the authentication fails. * - * @exception LoginException if this LoginModule + * @exception LoginException if this {@code LoginModule} * is unable to perform the authentication. */ public boolean login() throws LoginException { @@ -1019,23 +1000,21 @@ public class Krb5LoginModule implements LoginModule { } /** - *

                          This method is called if the LoginContext's + * This method is called if the LoginContext's * overall authentication succeeded * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL * LoginModules succeeded). * *

                          If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the - * login method), then this method associates a - * Krb5Principal - * with the Subject located in the - * LoginModule. It adds Kerberos Credentials to the + * {@code login} method), then this method associates a + * {@code Krb5Principal} + * with the {@code Subject} located in the + * {@code LoginModule}. It adds Kerberos Credentials to the * the Subject's private credentials set. If this LoginModule's own * authentication attempted failed, then this method removes * any state that was originally saved. * - *

                          - * * @exception LoginException if the commit fails. * * @return true if this LoginModule's own login and commit @@ -1147,18 +1126,16 @@ public class Krb5LoginModule implements LoginModule { } /** - *

                          This method is called if the LoginContext's + * This method is called if the LoginContext's * overall authentication failed. * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL * LoginModules did not succeed). * *

                          If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the - * login and commit methods), + * {@code login} and {@code commit} methods), * then this method cleans up any state that was originally saved. * - *

                          - * * @exception LoginException if the abort fails. * * @return false if this LoginModule's own login and/or commit attempts @@ -1183,14 +1160,12 @@ public class Krb5LoginModule implements LoginModule { /** * Logout the user. * - *

                          This method removes the Krb5Principal - * that was added by the commit method. - * - *

                          + *

                          This method removes the {@code Krb5Principal} + * that was added by the {@code commit} method. * * @exception LoginException if the logout fails. * - * @return true in all cases since this LoginModule + * @return true in all cases since this {@code LoginModule} * should not be ignored. */ public boolean logout() throws LoginException { diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/LdapLoginModule.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/LdapLoginModule.java index 1de82aa98b6..167530a4b79 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/LdapLoginModule.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/LdapLoginModule.java @@ -70,8 +70,8 @@ import com.sun.security.auth.UserPrincipal; * conjunction with a specified search filter. * If successful then authentication is attempted using the user's * distinguished name and the supplied password. - * To enable this mode, set the userFilter option and omit the - * authIdentity option. + * To enable this mode, set the {@code userFilter} option and omit the + * {@code authIdentity} option. * Use search-first mode when the user's distinguished name is not * known in advance. * @@ -79,22 +79,22 @@ import com.sun.security.auth.UserPrincipal; * supplied username and password and then the LDAP directory is searched. * If authentication is successful then a search is performed using the * supplied username in conjunction with a specified search filter. - * To enable this mode, set the authIdentity and the - * userFilter options. + * To enable this mode, set the {@code authIdentity} and the + * {@code userFilter} options. * Use authentication-first mode when accessing an LDAP directory * that has been configured to disallow anonymous searches. * *

                          In authentication-only mode, authentication is attempted using the * supplied username and password. The LDAP directory is not searched because * the user's distinguished name is already known. - * To enable this mode, set the authIdentity option to a valid - * distinguished name and omit the userFilter option. + * To enable this mode, set the {@code authIdentity} option to a valid + * distinguished name and omit the {@code userFilter} option. * Use authentication-only mode when the user's distinguished name is * known in advance. * *

                          The following option is mandatory and must be specified in this * module's login {@link Configuration}: - *

                          + *
                          *
                          *
                          userProvider=ldap_urls *
                          @@ -106,7 +106,7 @@ import com.sun.security.auth.UserPrincipal; * When several LDAP URLs are specified then each is attempted, * in turn, until the first successful connection is established. * Spaces in the distinguished name component of the URL must be escaped - * using the standard mechanism of percent character ('%') + * using the standard mechanism of percent character ('{@code %}') * followed by two hexadecimal digits (see {@link java.net.URI}). * Query components must also be omitted from the URL. * @@ -120,33 +120,33 @@ import com.sun.security.auth.UserPrincipal; * *

                          This module also recognizes the following optional {@link Configuration} * options: - *

                          + *
                          *
                          *
                          userFilter=ldap_filter
                          *
                          This option specifies the search filter to use to locate a user's * entry in the LDAP directory. It is used to determine a user's * distinguished name. - * ldap_filter is an LDAP filter string + * {@code ldap_filter} is an LDAP filter string * (RFC 2254). - * If it contains the special token "{USERNAME}" + * If it contains the special token "{@code {USERNAME}}" * then that token will be replaced with the supplied username value * before the filter is used to search the directory.
                          * *
                          authIdentity=auth_id
                          *
                          This option specifies the identity to use when authenticating a user * to the LDAP directory. - * auth_id may be an LDAP distinguished name string + * {@code auth_id} may be an LDAP distinguished name string * (RFC 2253) or some * other string name. - * It must contain the special token "{USERNAME}" + * It must contain the special token "{@code {USERNAME}}" * which will be replaced with the supplied username value before the * name is used for authentication. * Note that if this option does not contain a distinguished name then - * the userFilter option must also be specified.
                          + * the {@code userFilter} option must also be specified.
                          * *
                          authzIdentity=authz_id
                          *
                          This option specifies an authorization identity for the user. - * authz_id is any string name. + * {@code authz_id} is any string name. * If it comprises a single special token with curly braces then * that token is treated as a attribute name and will be replaced with a * single value of that attribute from the user's LDAP entry. @@ -156,23 +156,23 @@ import com.sun.security.auth.UserPrincipal; * is created using the authorization identity and it is associated with * the current {@link Subject}.
                          * - *
                          useSSL
                          - *
                          if false, this module does not establish an SSL connection + *
                          {@code useSSL}
                          + *
                          if {@code false}, this module does not establish an SSL connection * to the LDAP server before attempting authentication. SSL is used to * protect the privacy of the user's password because it is transmitted * in the clear over LDAP. * By default, this module uses SSL.
                          * - *
                          useFirstPass
                          - *
                          if true, this module retrieves the username and password + *
                          {@code useFirstPass}
                          + *
                          if {@code true}, this module retrieves the username and password * from the module's shared state, using "javax.security.auth.login.name" * and "javax.security.auth.login.password" as the respective keys. The * retrieved values are used for authentication. If authentication fails, * no attempt for a retry is made, and the failure is reported back to * the calling application.
                          * - *
                          tryFirstPass
                          - *
                          if true, this module retrieves the username and password + *
                          {@code tryFirstPass}
                          + *
                          if {@code true}, this module retrieves the username and password * from the module's shared state, using "javax.security.auth.login.name" * and "javax.security.auth.login.password" as the respective keys. The * retrieved values are used for authentication. If authentication fails, @@ -181,8 +181,8 @@ import com.sun.security.auth.UserPrincipal; * authentication fails, the failure is reported back to the calling * application.
                          * - *
                          storePass
                          - *
                          if true, this module stores the username and password + *
                          {@code storePass}
                          + *
                          if {@code true}, this module stores the username and password * obtained from the {@link CallbackHandler} in the module's shared state, * using * "javax.security.auth.login.name" and @@ -190,13 +190,13 @@ import com.sun.security.auth.UserPrincipal; * not performed if existing values already exist for the username and * password in the shared state, or if authentication fails.
                          * - *
                          clearPass
                          - *
                          if true, this module clears the username and password + *
                          {@code clearPass}
                          + *
                          if {@code true}, this module clears the username and password * stored in the module's shared state after both phases of authentication * (login and commit) have completed.
                          * - *
                          debug
                          - *
                          if true, debug messages are displayed on the standard + *
                          {@code debug}
                          + *
                          if {@code true}, debug messages are displayed on the standard * output stream. *
                          *
                          @@ -209,36 +209,36 @@ import com.sun.security.auth.UserPrincipal; * Note that the following four JNDI properties are set by this module directly * and are ignored if also present in the configuration: *
                            - *
                          • java.naming.provider.url - *
                          • java.naming.security.principal - *
                          • java.naming.security.credentials - *
                          • java.naming.security.protocol + *
                          • {@code java.naming.provider.url} + *
                          • {@code java.naming.security.principal} + *
                          • {@code java.naming.security.credentials} + *
                          • {@code java.naming.security.protocol} *
                          * *

                          * Three sample {@link Configuration}s are shown below. * The first one activates search-first mode. It identifies the LDAP server - * and specifies that users' entries be located by their uid and - * objectClass attributes. It also specifies that an identity - * based on the user's employeeNumber attribute should be created. + * and specifies that users' entries be located by their {@code uid} and + * {@code objectClass} attributes. It also specifies that an identity + * based on the user's {@code employeeNumber} attribute should be created. * The second one activates authentication-first mode. It requests that the * LDAP server be located dynamically, that authentication be performed using * the supplied username directly but without the protection of SSL and that * users' entries be located by one of three naming attributes and their - * objectClass attribute. + * {@code objectClass} attribute. * The third one activates authentication-only mode. It identifies alternative * LDAP servers, it specifies the distinguished name to use for * authentication and a fixed identity to use for authorization. No directory * search is performed. * - *

                          + * 
                          {@literal
                            *
                            *     ExampleApplication {
                            *         com.sun.security.auth.module.LdapLoginModule REQUIRED
                          - *             userProvider="ldap://ldap-svr/ou=people,dc=example,dc=com"
                          - *             userFilter="(&(uid={USERNAME})(objectClass=inetOrgPerson))"
                          - *             authzIdentity="{EMPLOYEENUMBER}"
                          - *             debug=true;
                          + *              userProvider="ldap://ldap-svr/ou=people,dc=example,dc=com"
                          + *              userFilter="(&(uid={USERNAME})(objectClass=inetOrgPerson))"
                          + *              authzIdentity="{EMPLOYEENUMBER}"
                          + *              debug=true;
                            *     };
                            *
                            *     ExampleApplication {
                          @@ -258,7 +258,7 @@ import com.sun.security.auth.UserPrincipal;
                            *             debug=true;
                            *     };
                            *
                          - * 
                          + * }
                          * *
                          *
                          Note:
                          @@ -282,7 +282,6 @@ import com.sun.security.auth.UserPrincipal; * caller-specified {@link Configuration} then the application * must be granted the permissions required by the {@link LoginModule}. * This module requires the following two permissions: - *

                          *

                            *
                          • The {@link SocketPermission} to connect to an LDAP server. *
                          • The {@link AuthPermission} to modify the set of {@link Principal}s @@ -373,15 +372,15 @@ public class LdapLoginModule implements LoginModule { private SearchControls constraints = null; /** - * Initialize this LoginModule. + * Initialize this {@code LoginModule}. * - * @param subject the Subject to be authenticated. - * @param callbackHandler a CallbackHandler to acquire the + * @param subject the {@code Subject} to be authenticated. + * @param callbackHandler a {@code CallbackHandler} to acquire the * username and password. - * @param sharedState shared LoginModule state. + * @param sharedState shared {@code LoginModule} state. * @param options options specified in the login - * Configuration for this particular - * LoginModule. + * {@code Configuration} for this particular + * {@code LoginModule}. */ // Unchecked warning from (Map)sharedState is safe // since javax.security.auth.login.LoginContext passes a raw HashMap. @@ -492,10 +491,10 @@ public class LdapLoginModule implements LoginModule { *

                            Acquire the user's credentials and verify them against the * specified LDAP directory. * - * @return true always, since this LoginModule + * @return true always, since this {@code LoginModule} * should not be ignored. * @exception FailedLoginException if the authentication fails. - * @exception LoginException if this LoginModule + * @exception LoginException if this {@code LoginModule} * is unable to perform the authentication. */ public boolean login() throws LoginException { @@ -593,10 +592,10 @@ public class LdapLoginModule implements LoginModule { * *

                            If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the - * login method), then this method associates an - * LdapPrincipal and one or more UserPrincipals - * with the Subject located in the - * LoginModule. If this LoginModule's own + * {@code login} method), then this method associates an + * {@code LdapPrincipal} and one or more {@code UserPrincipal}s + * with the {@code Subject} located in the + * {@code LoginModule}. If this LoginModule's own * authentication attempted failed, then this method removes * any state that was originally saved. * @@ -662,7 +661,7 @@ public class LdapLoginModule implements LoginModule { * *

                            If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the - * login and commit methods), + * {@code login} and {@code commit} methods), * then this method cleans up any state that was originally saved. * * @exception LoginException if the abort fails. @@ -697,10 +696,10 @@ public class LdapLoginModule implements LoginModule { * Logout a user. * *

                            This method removes the Principals - * that were added by the commit method. + * that were added by the {@code commit} method. * * @exception LoginException if the logout fails. - * @return true in all cases since this LoginModule + * @return true in all cases since this {@code LoginModule} * should not be ignored. */ public boolean logout() throws LoginException { diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/NTLoginModule.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/NTLoginModule.java index d228b0550f2..828b5b9f748 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/NTLoginModule.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/NTLoginModule.java @@ -41,10 +41,10 @@ import com.sun.security.auth.NTSidGroupPrincipal; import com.sun.security.auth.NTNumericCredential; /** - *

                            This LoginModule + * This {@code LoginModule} * renders a user's NT security information as some number of - * Principals - * and associates them with a Subject. + * {@code Principal}s + * and associates them with a {@code Subject}. * *

                            This LoginModule recognizes the debug option. * If set to true in the login Configuration, @@ -85,23 +85,21 @@ public class NTLoginModule implements LoginModule { private NTNumericCredential iToken; // impersonation token /** - * Initialize this LoginModule. + * Initialize this {@code LoginModule}. * - *

                            + * @param subject the {@code Subject} to be authenticated. * - * @param subject the Subject to be authenticated.

                            - * - * @param callbackHandler a CallbackHandler for communicating + * @param callbackHandler a {@code CallbackHandler} for communicating * with the end user (prompting for usernames and * passwords, for example). This particular LoginModule only * extracts the underlying NT system information, so this - * parameter is ignored.

                            + * parameter is ignored. * - * @param sharedState shared LoginModule state.

                            + * @param sharedState shared {@code LoginModule} state. * * @param options options specified in the login - * Configuration for this particular - * LoginModule. + * {@code Configuration} for this particular + * {@code LoginModule}. */ public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, @@ -125,14 +123,12 @@ public class NTLoginModule implements LoginModule { /** * Import underlying NT system identity information. * - *

                            - * - * @return true in all cases since this LoginModule + * @return true in all cases since this {@code LoginModule} * should not be ignored. * - * @exception FailedLoginException if the authentication fails.

                            + * @exception FailedLoginException if the authentication fails. * - * @exception LoginException if this LoginModule + * @exception LoginException if this {@code LoginModule} * is unable to perform the authentication. */ public boolean login() throws LoginException { @@ -221,22 +217,20 @@ public class NTLoginModule implements LoginModule { } /** - *

                            This method is called if the LoginContext's + * This method is called if the LoginContext's * overall authentication succeeded * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules * succeeded). * *

                            If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the - * login method), then this method associates some - * number of various Principals - * with the Subject located in the - * LoginModuleContext. If this LoginModule's own + * {@code login} method), then this method associates some + * number of various {@code Principal}s + * with the {@code Subject} located in the + * {@code LoginModuleContext}. If this LoginModule's own * authentication attempted failed, then this method removes * any state that was originally saved. * - *

                            - * * @exception LoginException if the commit fails. * * @return true if this LoginModule's own login and commit @@ -290,18 +284,16 @@ public class NTLoginModule implements LoginModule { /** - *

                            This method is called if the LoginContext's + * This method is called if the LoginContext's * overall authentication failed. * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules * did not succeed). * *

                            If this LoginModule's own authentication attempt * succeeded (checked by retrieving the private state saved by the - * login and commit methods), + * {@code login} and {@code commit} methods), * then this method cleans up any state that was originally saved. * - *

                            - * * @exception LoginException if the abort fails. * * @return false if this LoginModule's own login and/or commit attempts @@ -336,17 +328,15 @@ public class NTLoginModule implements LoginModule { /** * Logout the user. * - *

                            This method removes the NTUserPrincipal, - * NTDomainPrincipal, NTSidUserPrincipal, - * NTSidDomainPrincipal, NTSidGroupPrincipals, - * and NTSidPrimaryGroupPrincipal - * that may have been added by the commit method. - * - *

                            + *

                            This method removes the {@code NTUserPrincipal}, + * {@code NTDomainPrincipal}, {@code NTSidUserPrincipal}, + * {@code NTSidDomainPrincipal}, {@code NTSidGroupPrincipal}s, + * and {@code NTSidPrimaryGroupPrincipal} + * that may have been added by the {@code commit} method. * * @exception LoginException if the logout fails. * - * @return true in all cases since this LoginModule + * @return true in all cases since this {@code LoginModule} * should not be ignored. */ public boolean logout() throws LoginException { diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/NTSystem.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/NTSystem.java index 0a51492d620..54fa4c23348 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/NTSystem.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/NTSystem.java @@ -26,7 +26,7 @@ package com.sun.security.auth.module; /** - *

                            This class implementation retrieves and makes available NT + * This class implementation retrieves and makes available NT * security information for the current user. * */ @@ -45,7 +45,7 @@ public class NTSystem { private long impersonationToken; /** - * Instantiate an NTSystem and load + * Instantiate an {@code NTSystem} and load * the native library to access the underlying system information. */ public NTSystem() { @@ -53,7 +53,7 @@ public class NTSystem { } /** - * Instantiate an NTSystem and load + * Instantiate an {@code NTSystem} and load * the native library to access the underlying system information. */ NTSystem(boolean debug) { @@ -64,8 +64,6 @@ public class NTSystem { /** * Get the username for the current NT user. * - *

                            - * * @return the username for the current NT user. */ public String getName() { @@ -75,8 +73,6 @@ public class NTSystem { /** * Get the domain for the current NT user. * - *

                            - * * @return the domain for the current NT user. */ public String getDomain() { @@ -86,8 +82,6 @@ public class NTSystem { /** * Get a printable SID for the current NT user's domain. * - *

                            - * * @return a printable SID for the current NT user's domain. */ public String getDomainSID() { @@ -97,8 +91,6 @@ public class NTSystem { /** * Get a printable SID for the current NT user. * - *

                            - * * @return a printable SID for the current NT user. */ public String getUserSID() { @@ -108,8 +100,6 @@ public class NTSystem { /** * Get a printable primary group SID for the current NT user. * - *

                            - * * @return the primary group SID for the current NT user. */ public String getPrimaryGroupID() { @@ -119,8 +109,6 @@ public class NTSystem { /** * Get the printable group SIDs for the current NT user. * - *

                            - * * @return the group SIDs for the current NT user. */ public String[] getGroupIDs() { @@ -130,8 +118,6 @@ public class NTSystem { /** * Get an impersonation token for the current NT user. * - *

                            - * * @return an impersonation token for the current NT user. */ public synchronized long getImpersonationToken() { diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/SolarisLoginModule.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/SolarisLoginModule.java index 0b71ac4ce77..9b5adb0c3cf 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/SolarisLoginModule.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/SolarisLoginModule.java @@ -36,17 +36,17 @@ import com.sun.security.auth.SolarisNumericUserPrincipal; import com.sun.security.auth.SolarisNumericGroupPrincipal; /** - *

                            This LoginModule imports a user's Solaris - * Principal information (SolarisPrincipal, - * SolarisNumericUserPrincipal, - * and SolarisNumericGroupPrincipal) - * and associates them with the current Subject. + * This {@code LoginModule} imports a user's Solaris + * {@code Principal} information ({@code SolarisPrincipal}, + * {@code SolarisNumericUserPrincipal}, + * and {@code SolarisNumericGroupPrincipal}) + * and associates them with the current {@code Subject}. * *

                            This LoginModule recognizes the debug option. * If set to true in the login Configuration, * debug messages will be output to the output stream, System.out. * @deprecated As of JDK1.4, replaced by - * com.sun.security.auth.module.UnixLoginModule. + * {@code com.sun.security.auth.module.UnixLoginModule}. * This LoginModule is entirely deprecated and * is here to allow for a smooth transition to the new * UnixLoginModule. @@ -80,21 +80,19 @@ public class SolarisLoginModule implements LoginModule { new LinkedList<>(); /** - * Initialize this LoginModule. + * Initialize this {@code LoginModule}. * - *

                            + * @param subject the {@code Subject} to be authenticated. * - * @param subject the Subject to be authenticated.

                            - * - * @param callbackHandler a CallbackHandler for communicating + * @param callbackHandler a {@code CallbackHandler} for communicating * with the end user (prompting for usernames and - * passwords, for example).

                            + * passwords, for example). * - * @param sharedState shared LoginModule state.

                            + * @param sharedState shared {@code LoginModule} state. * * @param options options specified in the login - * Configuration for this particular - * LoginModule. + * {@code Configuration} for this particular + * {@code LoginModule}. */ public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, @@ -114,15 +112,13 @@ public class SolarisLoginModule implements LoginModule { * Authenticate the user (first phase). * *

                            The implementation of this method attempts to retrieve the user's - * Solaris Subject information by making a native Solaris + * Solaris {@code Subject} information by making a native Solaris * system call. * - *

                            - * * @exception FailedLoginException if attempts to retrieve the underlying * system information fail. * - * @return true in all cases (this LoginModule + * @return true in all cases (this {@code LoginModule} * should not be ignored). */ public boolean login() throws LoginException { @@ -175,13 +171,11 @@ public class SolarisLoginModule implements LoginModule { *

                            If this LoginModule's own authentication attempt * succeeded (the importing of the Solaris authentication information * succeeded), then this method associates the Solaris Principals - * with the Subject currently tied to the - * LoginModule. If this LoginModule's + * with the {@code Subject} currently tied to the + * {@code LoginModule}. If this LoginModule's * authentication attempted failed, then this method removes * any state that was originally saved. * - *

                            - * * @exception LoginException if the commit fails * * @return true if this LoginModule's own login and commit attempts @@ -232,10 +226,8 @@ public class SolarisLoginModule implements LoginModule { * did not succeed). * *

                            This method cleans up any state that was originally saved - * as part of the authentication attempt from the login - * and commit methods. - * - *

                            + * as part of the authentication attempt from the {@code login} + * and {@code commit} methods. * * @exception LoginException if the abort fails * @@ -272,13 +264,11 @@ public class SolarisLoginModule implements LoginModule { * Logout the user * *

                            This method removes the Principals associated - * with the Subject. - * - *

                            + * with the {@code Subject}. * * @exception LoginException if the logout fails * - * @return true in all cases (this LoginModule + * @return true in all cases (this {@code LoginModule} * should not be ignored). */ public boolean logout() throws LoginException { diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/SolarisSystem.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/SolarisSystem.java index f06f28c22dd..98f6f4c70a0 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/SolarisSystem.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/SolarisSystem.java @@ -26,7 +26,7 @@ package com.sun.security.auth.module; /** - *

                            This class implementation retrieves and makes available Solaris + * This class implementation retrieves and makes available Solaris * UID/GID/groups information for the current user. * * @deprecated replaced by {@link UnixSystem}. @@ -43,7 +43,7 @@ public class SolarisSystem { protected long[] groups; /** - * Instantiate a SolarisSystem and load + * Instantiate a {@code SolarisSystem} and load * the native library to access the underlying system information. */ public SolarisSystem() { @@ -54,8 +54,6 @@ public class SolarisSystem { /** * Get the username for the current Solaris user. * - *

                            - * * @return the username for the current Solaris user. */ public String getUsername() { @@ -65,8 +63,6 @@ public class SolarisSystem { /** * Get the UID for the current Solaris user. * - *

                            - * * @return the UID for the current Solaris user. */ public long getUid() { @@ -76,8 +72,6 @@ public class SolarisSystem { /** * Get the GID for the current Solaris user. * - *

                            - * * @return the GID for the current Solaris user. */ public long getGid() { @@ -87,8 +81,6 @@ public class SolarisSystem { /** * Get the supplementary groups for the current Solaris user. * - *

                            - * * @return the supplementary groups for the current Solaris user. */ public long[] getGroups() { diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/UnixLoginModule.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/UnixLoginModule.java index 8123ba68e9d..704b11dc33c 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/UnixLoginModule.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/UnixLoginModule.java @@ -36,11 +36,11 @@ import com.sun.security.auth.UnixNumericUserPrincipal; import com.sun.security.auth.UnixNumericGroupPrincipal; /** - *

                            This LoginModule imports a user's Unix - * Principal information (UnixPrincipal, - * UnixNumericUserPrincipal, - * and UnixNumericGroupPrincipal) - * and associates them with the current Subject. + * This {@code LoginModule} imports a user's Unix + * {@code Principal} information ({@code UnixPrincipal}, + * {@code UnixNumericUserPrincipal}, + * and {@code UnixNumericGroupPrincipal}) + * and associates them with the current {@code Subject}. * *

                            This LoginModule recognizes the debug option. * If set to true in the login Configuration, @@ -74,21 +74,19 @@ public class UnixLoginModule implements LoginModule { new LinkedList<>(); /** - * Initialize this LoginModule. + * Initialize this {@code LoginModule}. * - *

                            + * @param subject the {@code Subject} to be authenticated. * - * @param subject the Subject to be authenticated.

                            - * - * @param callbackHandler a CallbackHandler for communicating + * @param callbackHandler a {@code CallbackHandler} for communicating * with the end user (prompting for usernames and - * passwords, for example).

                            + * passwords, for example). * - * @param sharedState shared LoginModule state.

                            + * @param sharedState shared {@code LoginModule} state. * * @param options options specified in the login - * Configuration for this particular - * LoginModule. + * {@code Configuration} for this particular + * {@code LoginModule}. */ public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, @@ -107,15 +105,13 @@ public class UnixLoginModule implements LoginModule { * Authenticate the user (first phase). * *

                            The implementation of this method attempts to retrieve the user's - * Unix Subject information by making a native Unix + * Unix {@code Subject} information by making a native Unix * system call. * - *

                            - * * @exception FailedLoginException if attempts to retrieve the underlying * system information fail. * - * @return true in all cases (this LoginModule + * @return true in all cases (this {@code LoginModule} * should not be ignored). */ public boolean login() throws LoginException { @@ -169,13 +165,11 @@ public class UnixLoginModule implements LoginModule { *

                            If this LoginModule's own authentication attempt * succeeded (the importing of the Unix authentication information * succeeded), then this method associates the Unix Principals - * with the Subject currently tied to the - * LoginModule. If this LoginModule's + * with the {@code Subject} currently tied to the + * {@code LoginModule}. If this LoginModule's * authentication attempted failed, then this method removes * any state that was originally saved. * - *

                            - * * @exception LoginException if the commit fails * * @return true if this LoginModule's own login and commit attempts @@ -228,10 +222,8 @@ public class UnixLoginModule implements LoginModule { * did not succeed). * *

                            This method cleans up any state that was originally saved - * as part of the authentication attempt from the login - * and commit methods. - * - *

                            + * as part of the authentication attempt from the {@code login} + * and {@code commit} methods. * * @exception LoginException if the abort fails * @@ -267,13 +259,11 @@ public class UnixLoginModule implements LoginModule { * Logout the user * *

                            This method removes the Principals associated - * with the Subject. - * - *

                            + * with the {@code Subject}. * * @exception LoginException if the logout fails * - * @return true in all cases (this LoginModule + * @return true in all cases (this {@code LoginModule} * should not be ignored). */ public boolean logout() throws LoginException { diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/UnixSystem.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/UnixSystem.java index f969ae1dd10..43f93f78e82 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/UnixSystem.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/UnixSystem.java @@ -26,9 +26,8 @@ package com.sun.security.auth.module; /** - *

                            This class implementation retrieves and makes available Unix + * This class implementation retrieves and makes available Unix * UID/GID/groups information for the current user. - * */ @jdk.Exported public class UnixSystem { @@ -41,7 +40,7 @@ public class UnixSystem { protected long[] groups; /** - * Instantiate a UnixSystem and load + * Instantiate a {@code UnixSystem} and load * the native library to access the underlying system information. */ public UnixSystem() { @@ -52,8 +51,6 @@ public class UnixSystem { /** * Get the username for the current Unix user. * - *

                            - * * @return the username for the current Unix user. */ public String getUsername() { @@ -63,8 +60,6 @@ public class UnixSystem { /** * Get the UID for the current Unix user. * - *

                            - * * @return the UID for the current Unix user. */ public long getUid() { @@ -74,8 +69,6 @@ public class UnixSystem { /** * Get the GID for the current Unix user. * - *

                            - * * @return the GID for the current Unix user. */ public long getGid() { @@ -85,8 +78,6 @@ public class UnixSystem { /** * Get the supplementary groups for the current Unix user. * - *

                            - * * @return the supplementary groups for the current Unix user. */ public long[] getGroups() { diff --git a/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipConstants.java b/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipConstants.java index 0a080a261ed..211e5a393f8 100644 --- a/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipConstants.java +++ b/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipConstants.java @@ -184,10 +184,19 @@ class ZipConstants { return (LG(b, n)) | (LG(b, n + 4) << 32); } - static final long GETSIG(byte[] b) { - return LG(b, 0); + static long getSig(byte[] b, int n) { return LG(b, n); } + + private static boolean pkSigAt(byte[] b, int n, int b1, int b2) { + return b[n] == 'P' & b[n + 1] == 'K' & b[n + 2] == b1 & b[n + 3] == b2; } + static boolean cenSigAt(byte[] b, int n) { return pkSigAt(b, n, 1, 2); } + static boolean locSigAt(byte[] b, int n) { return pkSigAt(b, n, 3, 4); } + static boolean endSigAt(byte[] b, int n) { return pkSigAt(b, n, 5, 6); } + static boolean extSigAt(byte[] b, int n) { return pkSigAt(b, n, 7, 8); } + static boolean end64SigAt(byte[] b, int n) { return pkSigAt(b, n, 6, 6); } + static boolean locator64SigAt(byte[] b, int n) { return pkSigAt(b, n, 6, 7); } + // local file (LOC) header fields static final long LOCSIG(byte[] b) { return LG(b, 0); } // signature static final int LOCVER(byte[] b) { return SH(b, 4); } // version needed to extract diff --git a/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java b/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java index aa584943d3f..17acf262266 100644 --- a/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java +++ b/jdk/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java @@ -1060,7 +1060,7 @@ class ZipFileSystem extends FileSystem { int pos = 0; int limit = cen.length - ENDHDR; while (pos < limit) { - if (CENSIG(cen, pos) != CENSIG) + if (!cenSigAt(cen, pos)) zerror("invalid CEN header (bad signature)"); int method = CENHOW(cen, pos); int nlen = CENNAM(cen, pos); @@ -1894,7 +1894,7 @@ class ZipFileSystem extends FileSystem { throws IOException { byte[] cen = zipfs.cen; - if (CENSIG(cen, pos) != CENSIG) + if (!cenSigAt(cen, pos)) zerror("invalid CEN header (bad signature)"); versionMade = CENVEM(cen, pos); version = CENVER(cen, pos); @@ -2057,9 +2057,9 @@ class ZipFileSystem extends FileSystem { assert (buf.length >= LOCHDR); if (zipfs.readFullyAt(buf, 0, LOCHDR , pos) != LOCHDR) throw new ZipException("loc: reading failed"); - if (LOCSIG(buf) != LOCSIG) + if (!locSigAt(buf, 0)) throw new ZipException("loc: wrong sig ->" - + Long.toString(LOCSIG(buf), 16)); + + Long.toString(getSig(buf, 0), 16)); //startPos = pos; version = LOCVER(buf); flag = LOCFLG(buf); @@ -2271,6 +2271,8 @@ class ZipFileSystem extends FileSystem { } break; case EXTID_NTFS: + if (sz < 32) + break; pos += 4; // reserved 4 bytes if (SH(extra, pos) != 0x0001) break; @@ -2289,9 +2291,9 @@ class ZipFileSystem extends FileSystem { if (zipfs.readFullyAt(buf, 0, buf.length , locoff) != buf.length) throw new ZipException("loc: reading failed"); - if (LOCSIG(buf) != LOCSIG) + if (!locSigAt(buf, 0)) throw new ZipException("loc: wrong sig ->" - + Long.toString(LOCSIG(buf), 16)); + + Long.toString(getSig(buf, 0), 16)); int locElen = LOCEXT(buf); if (locElen < 9) // EXTT is at lease 9 bytes diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index b8bcd0e1dc9..fb8d79c7b5e 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -164,9 +164,6 @@ javax/management/remote/mandatory/notif/NotifReconnectDeadlockTest.java generi # 6988950 demo/jvmti/compiledMethodLoad/CompiledMethodLoadTest.java generic-all -# 8071968 -javax/xml/ws/8046817/GenerateEnumSchema.java windows-all - ############################################################################ # jdk_net @@ -251,6 +248,64 @@ java/security/Security/ClassLoaderDeadlock/Deadlock2.sh generic-all # 8026393 sun/security/tools/jarsigner/warnings/BadKeyUsageTest.java generic-all +# 8077138: Some PKCS11 tests fail because NSS library is not initialized +sun/security/pkcs11/Cipher/ReinitCipher.java windows-all +sun/security/pkcs11/Cipher/TestPKCS5PaddingError.java windows-all +sun/security/pkcs11/Cipher/TestRSACipher.java windows-all +sun/security/pkcs11/Cipher/TestRSACipherWrap.java windows-all +sun/security/pkcs11/Cipher/TestRawRSACipher.java windows-all +sun/security/pkcs11/Cipher/TestSymmCiphers.java windows-all +sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java windows-all +sun/security/pkcs11/KeyAgreement/TestDH.java windows-all +sun/security/pkcs11/KeyAgreement/TestInterop.java windows-all +sun/security/pkcs11/KeyAgreement/TestShort.java windows-all +sun/security/pkcs11/KeyGenerator/DESParity.java windows-all +sun/security/pkcs11/KeyGenerator/TestKeyGenerator.java windows-all +sun/security/pkcs11/KeyPairGenerator/TestDH2048.java windows-all +sun/security/pkcs11/KeyStore/SecretKeysBasic.sh windows-all +sun/security/pkcs11/Mac/MacKAT.java windows-all +sun/security/pkcs11/Mac/MacSameTest.java windows-all +sun/security/pkcs11/Mac/ReinitMac.java windows-all +sun/security/pkcs11/MessageDigest/ByteBuffers.java windows-all +sun/security/pkcs11/MessageDigest/DigestKAT.java windows-all +sun/security/pkcs11/MessageDigest/ReinitDigest.java windows-all +sun/security/pkcs11/MessageDigest/TestCloning.java windows-all +sun/security/pkcs11/Provider/ConfigQuotedString.sh windows-all +sun/security/pkcs11/Provider/Login.sh windows-all +sun/security/pkcs11/SampleTest.java windows-all +sun/security/pkcs11/Secmod/AddPrivateKey.java windows-all +sun/security/pkcs11/Secmod/AddTrustedCert.java windows-all +sun/security/pkcs11/Secmod/Crypto.java windows-all +sun/security/pkcs11/Secmod/GetPrivateKey.java windows-all +sun/security/pkcs11/Secmod/JksSetPrivateKey.java windows-all +sun/security/pkcs11/SecureRandom/Basic.java windows-all +sun/security/pkcs11/SecureRandom/TestDeserialization.java windows-all +sun/security/pkcs11/Serialize/SerializeProvider.java windows-all +sun/security/pkcs11/Signature/ByteBuffers.java windows-all +sun/security/pkcs11/Signature/ReinitSignature.java windows-all +sun/security/pkcs11/Signature/TestDSA.java windows-all +sun/security/pkcs11/Signature/TestDSAKeyLength.java windows-all +sun/security/pkcs11/Signature/TestRSAKeyLength.java windows-all +sun/security/pkcs11/ec/ReadCertificates.java windows-all +sun/security/pkcs11/ec/ReadPKCS12.java windows-all +sun/security/pkcs11/ec/TestCurves.java windows-all +sun/security/pkcs11/ec/TestECDH.java windows-all +sun/security/pkcs11/ec/TestECDH2.java windows-all +sun/security/pkcs11/ec/TestECDSA.java windows-all +sun/security/pkcs11/ec/TestECDSA2.java windows-all +sun/security/pkcs11/ec/TestECGenSpec.java windows-all +sun/security/pkcs11/rsa/KeyWrap.java windows-all +sun/security/pkcs11/rsa/TestCACerts.java windows-all +sun/security/pkcs11/rsa/TestKeyFactory.java windows-all +sun/security/pkcs11/rsa/TestKeyPairGenerator.java windows-all +sun/security/pkcs11/rsa/TestSignatures.java windows-all +sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java windows-all +sun/security/pkcs11/tls/TestKeyMaterial.java windows-all +sun/security/pkcs11/tls/TestLeadingZeroesP11.java windows-all +sun/security/pkcs11/tls/TestMasterSecret.java windows-all +sun/security/pkcs11/tls/TestPRF.java windows-all +sun/security/pkcs11/tls/TestPremaster.java windows-all + ############################################################################ # jdk_sound @@ -283,9 +338,6 @@ tools/launcher/FXLauncherTest.java linux-all # jdk_jdi -# 6983531 -com/sun/jdi/BadHandshakeTest.java linux-all,windows-all - # 8004127 com/sun/jdi/RedefineImplementor.sh generic-all diff --git a/jdk/test/TEST.ROOT b/jdk/test/TEST.ROOT index 0e6fa003234..76e0c407cba 100644 --- a/jdk/test/TEST.ROOT +++ b/jdk/test/TEST.ROOT @@ -1,14 +1,21 @@ # This file identifies the root of the test-suite hierarchy. # It also contains test-suite configuration information. -# The list of keywords supported in the entire test suite -keys=2d dnd i18n intermittent +# The list of keywords supported in the entire test suite. The +# "intermittent" keyword marks tests known to fail intermittently. +# The "randomness" keyword marks tests using randomness with test +# cases differing from run to run. (A test using a fixed random seed +# would not count as "randomness" by this definition.) Extra care +# should be taken to handle test failures of intermittent or +# randomness tests. + +keys=2d dnd i18n intermittent randomness # Tests that must run in othervm mode othervm.dirs=java/awt java/beans javax/accessibility javax/imageio javax/sound javax/print javax/management com/sun/awt sun/awt sun/java2d sun/pisces javax/xml/jaxp/testng/validation # Tests that cannot run concurrently -exclusiveAccess.dirs=java/rmi/Naming java/util/prefs sun/management/jmxremote sun/tools/jstatd sun/security/mscapi java/util/stream +exclusiveAccess.dirs=java/rmi/Naming java/util/prefs sun/management/jmxremote sun/tools/jstatd sun/security/mscapi java/util/stream javax/rmi # Group definitions groups=TEST.groups [closed/TEST.groups] diff --git a/jdk/test/TEST.groups b/jdk/test/TEST.groups index 2ee1007a5e7..73ac408f90e 100644 --- a/jdk/test/TEST.groups +++ b/jdk/test/TEST.groups @@ -38,7 +38,9 @@ tier2 = \ :jdk_time \ :jdk_security \ :jdk_text \ - :core_tools + :core_tools \ + :jdk_other \ + :jdk_svc ############################################################################### # @@ -136,7 +138,6 @@ jdk_time = \ jdk_rmi = \ java/rmi \ - javax/rmi/ssl \ sun/rmi jdk_security1 = \ @@ -235,6 +236,7 @@ jdk_tools = \ jdk_other = \ java/sql \ javax/sql \ + javax/rmi \ javax/naming \ javax/script \ javax/smartcardio \ @@ -451,7 +453,6 @@ needs_jdk = \ java/util/jar/JarInputStream/ExtraFileInMetaInf.java \ java/util/logging/TestLoggerWeakRefLeak.java \ java/util/zip/3GBZipFiles.sh \ - jdk/lambda/FDTest.java \ jdk/lambda/separate/Compiler.java \ sun/management/jmxremote/bootstrap/JvmstatCountersTest.java \ sun/management/jmxremote/bootstrap/LocalManagementTest.java \ diff --git a/jdk/test/com/oracle/security/ucrypto/CipherSignNotSupported.java b/jdk/test/com/oracle/security/ucrypto/CipherSignNotSupported.java index bf463227ed3..7e141b615b5 100644 --- a/jdk/test/com/oracle/security/ucrypto/CipherSignNotSupported.java +++ b/jdk/test/com/oracle/security/ucrypto/CipherSignNotSupported.java @@ -27,6 +27,7 @@ * @summary Make sure signing via encrypt and verifying via decrypt are not * supported by OracleUcrypto provider. * @author Anthony Scarpino + * @key randomness */ import java.util.Random; diff --git a/jdk/test/com/oracle/security/ucrypto/TestAES.java b/jdk/test/com/oracle/security/ucrypto/TestAES.java index 61594f381c0..4ed48659c86 100644 --- a/jdk/test/com/oracle/security/ucrypto/TestAES.java +++ b/jdk/test/com/oracle/security/ucrypto/TestAES.java @@ -25,6 +25,7 @@ * @test * @bug 7088989 8014374 * @summary Ensure the AES ciphers of OracleUcrypto provider works correctly + * @key randomness */ import java.io.*; diff --git a/jdk/test/com/oracle/security/ucrypto/TestCICOWithGCM.java b/jdk/test/com/oracle/security/ucrypto/TestCICOWithGCM.java index f12ee740a1a..3191fd8b321 100644 --- a/jdk/test/com/oracle/security/ucrypto/TestCICOWithGCM.java +++ b/jdk/test/com/oracle/security/ucrypto/TestCICOWithGCM.java @@ -26,6 +26,7 @@ * @bug 8014374 * @summary Test basic CipherInputStream/OutputStream func w/ GCM mode. * @author Valerie Peng + * @key randomness */ import java.security.*; diff --git a/jdk/test/com/oracle/security/ucrypto/TestCICOWithGCMAndAAD.java b/jdk/test/com/oracle/security/ucrypto/TestCICOWithGCMAndAAD.java index 782cea6145e..6075672dbcb 100644 --- a/jdk/test/com/oracle/security/ucrypto/TestCICOWithGCMAndAAD.java +++ b/jdk/test/com/oracle/security/ucrypto/TestCICOWithGCMAndAAD.java @@ -26,6 +26,7 @@ * @bug 8014374 * @summary Test CipherInputStream/OutputStream func w/ GCM mode and AAD. * @author Valerie Peng + * @key randomness */ import java.io.*; diff --git a/jdk/test/com/oracle/security/ucrypto/TestDigest.java b/jdk/test/com/oracle/security/ucrypto/TestDigest.java index a9057ba3c87..5bd6f412f29 100644 --- a/jdk/test/com/oracle/security/ucrypto/TestDigest.java +++ b/jdk/test/com/oracle/security/ucrypto/TestDigest.java @@ -25,6 +25,7 @@ * @test * @bug 7088989 * @summary Ensure the various message digests works correctly + * @key randomness */ import java.io.*; diff --git a/jdk/test/com/oracle/security/ucrypto/TestGCMKeyWrap.java b/jdk/test/com/oracle/security/ucrypto/TestGCMKeyWrap.java index 89d5e02efbd..c64367ab46e 100644 --- a/jdk/test/com/oracle/security/ucrypto/TestGCMKeyWrap.java +++ b/jdk/test/com/oracle/security/ucrypto/TestGCMKeyWrap.java @@ -25,6 +25,7 @@ * @test * @bug 8014374 * @summary Ensure key wrap/unwrap works using AES/GCM/NoPadding + * @key randomness */ import java.io.*; diff --git a/jdk/test/com/sun/crypto/provider/Cipher/AES/CICO.java b/jdk/test/com/sun/crypto/provider/Cipher/AES/CICO.java index 811724be8ce..1bb9f0d061f 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/AES/CICO.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/CICO.java @@ -44,6 +44,7 @@ import javax.crypto.spec.IvParameterSpec; * @summary Test AES ciphers with different modes and padding schemes (ECB mode * doesn't use IV). The test tries 3 different read methods of * CipherInputStream. + * @key randomness */ public class CICO { private static final String ALGORITHM = "aEs"; diff --git a/jdk/test/com/sun/crypto/provider/Cipher/AES/CTR.java b/jdk/test/com/sun/crypto/provider/Cipher/AES/CTR.java index 808f3e26916..d569965bca1 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/AES/CTR.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/CTR.java @@ -43,6 +43,7 @@ import javax.crypto.spec.IvParameterSpec; * @bug 8043836 * @summary Test AES ciphers with 4 different modes with NoPadding. Check if * data before encryption and after decryption is the same. + * @key randomness */ public class CTR { diff --git a/jdk/test/com/sun/crypto/provider/Cipher/AES/Padding.java b/jdk/test/com/sun/crypto/provider/Cipher/AES/Padding.java index 6023ec7cc67..9185efdf02c 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/AES/Padding.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/Padding.java @@ -42,6 +42,7 @@ import javax.crypto.spec.IvParameterSpec; * @summary Test AES ciphers with different modes and padding schemes (ECB mode * doesn't use IV). The test tries 3 different read methods of * CipherInputStream. + * @key randomness */ public class Padding { diff --git a/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4513830.java b/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4513830.java index d3ecc9e27bf..c421b169c4a 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4513830.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4513830.java @@ -27,6 +27,7 @@ * @summary Verify the output size returned by AES cipher.getOutputSize * method in DECRYPT mode does not add extra bytes for padding * @author Valerie Peng + * @key randomness */ import java.io.PrintStream; import java.security.*; diff --git a/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4517355.java b/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4517355.java index a4716482918..7ea6b8316f8 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4517355.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4517355.java @@ -27,6 +27,7 @@ * @summary Verify that AES cipher.doFinal method does NOT need more * than necessary bytes in decrypt mode * @author Valerie Peng + * @key randomness */ import java.io.PrintStream; import java.security.*; diff --git a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestAESCipher.java b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestAESCipher.java index 190b58630cc..0ea8d01bc92 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestAESCipher.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestAESCipher.java @@ -43,6 +43,7 @@ import javax.crypto.spec.IvParameterSpec; * doesn't use IV). * @author Liwen Wang * @author Parag Salvi + * @key randomness */ public class TestAESCipher { diff --git a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCICOWithGCM.java b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCICOWithGCM.java index 8fec041d0a9..1d5e5abbb62 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCICOWithGCM.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCICOWithGCM.java @@ -29,6 +29,7 @@ * @run main TestCICOWithGCM * @summary Test CipherInputStream/OutputStream with AES GCM mode. * @author Valerie Peng + * @key randomness */ import java.security.*; diff --git a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCICOWithGCMAndAAD.java b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCICOWithGCMAndAAD.java index 816f764f9ba..edc43d61ae3 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCICOWithGCMAndAAD.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCICOWithGCMAndAAD.java @@ -29,6 +29,7 @@ * @run main TestCICOWithGCMAndAAD * @summary Test CipherInputStream/OutputStream with AES GCM mode with AAD. * @author Valerie Peng + * @key randomness */ import java.io.*; import java.security.*; diff --git a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestISO10126Padding.java b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestISO10126Padding.java index edb62cb2b1f..926320393dd 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestISO10126Padding.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestISO10126Padding.java @@ -26,6 +26,7 @@ * @bug 4921443 * @summary Ensure ISO10126Padding works correctly. * @author Valerie Peng + * @key randomness */ import java.util.Arrays; import java.security.*; diff --git a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestNonexpanding.java b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestNonexpanding.java index 200d38b547b..3ed865f5a98 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestNonexpanding.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestNonexpanding.java @@ -40,6 +40,7 @@ import javax.crypto.spec.GCMParameterSpec; * @bug 8043836 * @summary Test AES encryption with no padding. Expect the original data length * is the same as the encrypted data. + * @key randomness */ public class TestNonexpanding { diff --git a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestSameBuffer.java b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestSameBuffer.java index bbba223a7c4..f4cc9276bbc 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestSameBuffer.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestSameBuffer.java @@ -42,6 +42,7 @@ import javax.crypto.spec.IvParameterSpec; * @summary Test AES ciphers with different modes and padding schemes (ECB mode * doesn't use IV). The test tries 3 different read methods of * CipherInputStream. + * @key randomness */ public class TestSameBuffer { diff --git a/jdk/test/com/sun/crypto/provider/Cipher/DES/FlushBug.java b/jdk/test/com/sun/crypto/provider/Cipher/DES/FlushBug.java index ab2dde8b434..bb03a885825 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/DES/FlushBug.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/DES/FlushBug.java @@ -26,6 +26,7 @@ * @bug 0000000 * @summary FlushBug * @author Jan Luehe + * @key randomness */ import java.io.*; import java.security.*; diff --git a/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBESealedObject.java b/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBESealedObject.java index 2420b9bc4a3..f97acd547a8 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBESealedObject.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBESealedObject.java @@ -45,6 +45,7 @@ import javax.crypto.spec.PBEParameterSpec; * @author Bill Situ * @author Alexander Fomin * @run main PBESealedObject + * @key randomness */ public class PBESealedObject { diff --git a/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBKDF2Translate.java b/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBKDF2Translate.java index 36681591e46..d9ccf5cf7c1 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBKDF2Translate.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/PBE/PBKDF2Translate.java @@ -37,6 +37,7 @@ import javax.crypto.spec.PBEKeySpec; * @summary Verify if the SecretKeyFactory.translateKey() method works * @author Alexander Fomin * @run main PBKDF2Translate + * @key randomness */ public class PBKDF2Translate { diff --git a/jdk/test/com/sun/crypto/provider/Cipher/PBE/PKCS12Cipher.java b/jdk/test/com/sun/crypto/provider/Cipher/PBE/PKCS12Cipher.java index 4995a9a8b8e..00ff89ade69 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/PBE/PKCS12Cipher.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/PBE/PKCS12Cipher.java @@ -27,6 +27,7 @@ * @summary basic test for PBEWithSHA1AndDESede, PBEWithSHA1AndRC2_40/128 * and PBEWithSHA1AndRC4_40/128 * @author Valerie Peng + * @key randomness */ import java.io.*; diff --git a/jdk/test/com/sun/crypto/provider/Cipher/PBE/TestCipherKeyWrapperPBEKey.java b/jdk/test/com/sun/crypto/provider/Cipher/PBE/TestCipherKeyWrapperPBEKey.java index cc237d0549d..dd767ba1fed 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/PBE/TestCipherKeyWrapperPBEKey.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/PBE/TestCipherKeyWrapperPBEKey.java @@ -45,6 +45,7 @@ import javax.crypto.spec.PBEParameterSpec; * @author Bill Situ * @author Yun Ke * @run main TestCipherKeyWrapperPBEKey + * @key randomness */ public class TestCipherKeyWrapperPBEKey { diff --git a/jdk/test/com/sun/crypto/provider/Cipher/RSA/TestOAEP.java b/jdk/test/com/sun/crypto/provider/Cipher/RSA/TestOAEP.java index 55b501ebf36..b35b8a2ef32 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/RSA/TestOAEP.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/RSA/TestOAEP.java @@ -26,6 +26,7 @@ * @bug 4894151 * @summary encryption/decryption test for OAEP * @author Andreas Sterbenz + * @key randomness */ import java.util.*; diff --git a/jdk/test/com/sun/crypto/provider/Cipher/RSA/TestRSA.java b/jdk/test/com/sun/crypto/provider/Cipher/RSA/TestRSA.java index b88a5dc524b..1e4c6ed10b1 100644 --- a/jdk/test/com/sun/crypto/provider/Cipher/RSA/TestRSA.java +++ b/jdk/test/com/sun/crypto/provider/Cipher/RSA/TestRSA.java @@ -26,6 +26,7 @@ * @bug 4853306 * @summary Test RSA Cipher implementation * @author Andreas Sterbenz + * @key randomness */ import java.io.*; diff --git a/jdk/test/com/sun/crypto/provider/Mac/HmacSaltLengths.java b/jdk/test/com/sun/crypto/provider/Mac/HmacSaltLengths.java index 17447398403..38d4da44a4a 100644 --- a/jdk/test/com/sun/crypto/provider/Mac/HmacSaltLengths.java +++ b/jdk/test/com/sun/crypto/provider/Mac/HmacSaltLengths.java @@ -27,6 +27,7 @@ * @summary ensures various salt lengths can be used for * HmacPBESHA1. * @author Valerie Peng + * @key randomness */ import java.io.*; diff --git a/jdk/test/com/sun/crypto/provider/Mac/MacSameTest.java b/jdk/test/com/sun/crypto/provider/Mac/MacSameTest.java index 8d97f1a6a88..598ea6a910c 100644 --- a/jdk/test/com/sun/crypto/provider/Mac/MacSameTest.java +++ b/jdk/test/com/sun/crypto/provider/Mac/MacSameTest.java @@ -35,6 +35,7 @@ import javax.crypto.spec.SecretKeySpec; * @author Yu-Ching Valerie Peng, Bill Situ, Alexander Fomin * @build Utils * @run main MacSameTest + * @key randomness */ public class MacSameTest implements MacTest { diff --git a/jdk/test/com/sun/jdi/BadHandshakeTest.java b/jdk/test/com/sun/jdi/BadHandshakeTest.java index 87db9002ae9..2a1108f5910 100644 --- a/jdk/test/com/sun/jdi/BadHandshakeTest.java +++ b/jdk/test/com/sun/jdi/BadHandshakeTest.java @@ -21,22 +21,15 @@ * questions. */ -/* @test - * @bug 6306165 6432567 - * @summary Check that a bad handshake doesn't cause a debuggee to abort - * @library /lib/testlibrary - * - * @build jdk.testlibrary.* VMConnection BadHandshakeTest Exit0 - * @run driver BadHandshakeTest - * - */ import java.net.Socket; -import java.net.InetAddress; + import com.sun.jdi.Bootstrap; import com.sun.jdi.VirtualMachine; import com.sun.jdi.event.*; import com.sun.jdi.connect.Connector; import com.sun.jdi.connect.AttachingConnector; +import com.sun.jdi.connect.Connector.Argument; + import java.util.Map; import java.util.List; import java.util.Iterator; @@ -46,13 +39,22 @@ import java.util.concurrent.atomic.AtomicBoolean; import jdk.testlibrary.Utils; import jdk.testlibrary.ProcessTools; +/* @test + * @bug 6306165 6432567 + * @summary Check that a bad handshake doesn't cause a debuggee to abort + * @library /lib/testlibrary + * + * @build jdk.testlibrary.* VMConnection BadHandshakeTest Exit0 + * @run driver BadHandshakeTest + */ public class BadHandshakeTest { + /* * Find a connector by name */ private static Connector findConnector(String name) { - List connectors = Bootstrap.virtualMachineManager().allConnectors(); - Iterator iter = connectors.iterator(); + List connectors = Bootstrap.virtualMachineManager().allConnectors(); + Iterator iter = connectors.iterator(); while (iter.hasNext()) { Connector connector = (Connector)iter.next(); if (connector.name().equals(name)) { @@ -65,7 +67,7 @@ public class BadHandshakeTest { /* * Launch a server debuggee with the given address */ - private static Process launch(String address, String class_name) throws Exception { + private static LaunchResult launch(String address, String class_name) throws Exception { String[] args = VMConnection.insertDebuggeeVMOptions(new String[] { "-agentlib:jdwp=transport=dt_socket" + ",server=y" + ",suspend=y" + ",address=" + address, @@ -75,6 +77,7 @@ public class BadHandshakeTest { ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); final AtomicBoolean success = new AtomicBoolean(); + final AtomicBoolean bindFailed = new AtomicBoolean(); Process p = ProcessTools.startProcess( class_name, pb, @@ -83,13 +86,17 @@ public class BadHandshakeTest { // Listening for transport dt_socket at address: xxxxx // which shows the debuggee is ready to accept connections. success.set(line.contains("Listening for transport dt_socket at address:")); + // If the first line contains 'Address already in use' + // that means the debuggee has failed to start due to busy port + bindFailed.set(line.contains("Address already in use")); return true; }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS ); - return success.get() ? p : null; + return new LaunchResult(success.get() ? p : null, + bindFailed.get()); } /* @@ -99,14 +106,20 @@ public class BadHandshakeTest { * - verify we saw no error */ public static void main(String args[]) throws Exception { - int port = Utils.getFreePort(); - - String address = String.valueOf(port); - - // launch the server debuggee - Process process = launch(address, "Exit0"); - if (process == null) { - throw new RuntimeException("Unable to start debugee"); + // Launch the server debuggee + int port = 0; + Process process = null; + while (process == null) { + port = Utils.getFreePort(); + String address = String.valueOf(port); + LaunchResult launchResult = launch(address, "Exit0"); + process = launchResult.getProcess(); + if (launchResult.isBindFailed()) { + System.out.println("Port " + port + " already in use. Trying to restart debuggee with a new one..."); + Thread.sleep(100); + } else if (process == null ) { + throw new RuntimeException("Unable to start debugee"); + } } // Connect to the debuggee and handshake with garbage @@ -119,9 +132,9 @@ public class BadHandshakeTest { s.getOutputStream().write("JDWP-".getBytes("UTF-8")); - // attach to server debuggee and resume it so it can exit + // Attach to server debuggee and resume it so it can exit AttachingConnector conn = (AttachingConnector)findConnector("com.sun.jdi.SocketAttach"); - Map conn_args = conn.defaultArguments(); + Map conn_args = conn.defaultArguments(); Connector.IntegerArgument port_arg = (Connector.IntegerArgument)conn_args.get("port"); port_arg.setValue(port); @@ -143,4 +156,24 @@ public class BadHandshakeTest { process.waitFor(); } + private static class LaunchResult { + + private final Process p; + private final boolean bindFailed; + + public LaunchResult(Process p, boolean bindFailed) { + this.p = p; + this.bindFailed = bindFailed; + } + + public Process getProcess() { + return p; + } + + public boolean isBindFailed() { + return bindFailed; + } + + } + } diff --git a/jdk/test/com/sun/jdi/JdbReadTwiceTest.sh b/jdk/test/com/sun/jdi/JdbReadTwiceTest.sh index 0c78fe5ec81..a166f2c54f1 100644 --- a/jdk/test/com/sun/jdi/JdbReadTwiceTest.sh +++ b/jdk/test/com/sun/jdi/JdbReadTwiceTest.sh @@ -204,39 +204,6 @@ if [ ! -r c:/ ] ; then clean fi -echo -echo "+++++++++++++++++++++++++++++++++++" -echo "Read an unreadable file - verify the read fails." - -canMakeUnreadable=No -id > $HOME/jdb.ini -if chmod a-r $HOME/jdb.ini -then - grep -q 'uid=0(' $HOME/jdb.ini 2> /dev/null - case $? in - 0) - echo "Error! Can't make file unreadable running as root" - ;; - 1) - echo "Error! Can't make file unreadable for some other reason (windows?)" - ;; - *) - echo "OK. the file is unreadable" - canMakeUnreadable=Yes - ;; - esac -else - echo "Error! Can't create or chmod file" -fi - -if [ "$canMakeUnreadable" = "Yes" ] -then - doit - failIfNot 1 "open: $HOME/jdb.ini" -fi -clean - - echo echo "+++++++++++++++++++++++++++++++++++" echo "Read a directory - verify the read fails" diff --git a/jdk/test/com/sun/jndi/dns/IPv6NameserverPlatformParsingTest.java b/jdk/test/com/sun/jndi/dns/IPv6NameserverPlatformParsingTest.java new file mode 100644 index 00000000000..fac68ba0756 --- /dev/null +++ b/jdk/test/com/sun/jndi/dns/IPv6NameserverPlatformParsingTest.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.lang.reflect.Field; +import java.util.Hashtable; + +import javax.naming.Context; +import javax.naming.NamingException; +import javax.naming.spi.NamingManager; + +import com.sun.jndi.dns.DnsContext; + +/** + * @test + * @bug 6991580 + * @summary IPv6 Nameservers in resolv.conf throws NumberFormatException + * @run main/manual IPv6NameserverPlatformParsingTest + * + * In order to run this test be sure to place, for example, the following + * snippet into your platform's {@code /etc/resolv.conf}: + *

                            + * nameserver 127.0.0.1
                            + * nameserver 2001:4860:4860::8888
                            + * nameserver [::1]:5353
                            + * nameserver 127.0.0.1:5353
                            + * 
                            + * + * Then, run this test as manual jtreg test. + * + * @author Severin Gehwolf + * + */ +public class IPv6NameserverPlatformParsingTest { + + private static boolean foundIPv6 = false; + + public static void main(String[] args) { + Hashtable env = new Hashtable<>(); + env.put(Context.INITIAL_CONTEXT_FACTORY, com.sun.jndi.dns.DnsContextFactory.class.getName()); + + String[] servers; + try { + Context ctx = NamingManager.getInitialContext(env); + if (!com.sun.jndi.dns.DnsContextFactory.platformServersAvailable()) { + throw new RuntimeException("FAIL: no platform servers available, test does not make sense"); + } + DnsContext context = (DnsContext)ctx; + servers = getServersFromContext(context); + } catch (NamingException e) { + throw new RuntimeException(e); + } + for (String server: servers) { + System.out.println("DEBUG: 'nameserver = " + server + "'"); + if (server.indexOf(':') >= 0 && server.indexOf('.') < 0) { + System.out.println("DEBUG: ==> Found IPv6 address in servers list: " + server); + foundIPv6 = true; + } + } + try { + new com.sun.jndi.dns.DnsClient(servers, 100, 1); + } catch (NumberFormatException e) { + throw new RuntimeException("FAIL: Tried to parse non-[]-encapsulated IPv6 address.", e); + } catch (Exception e) { + throw new RuntimeException("ERROR: Something unexpected happened."); + } + if (!foundIPv6) { + // This is a manual test, since it requires changing /etc/resolv.conf on Linux/Unix + // platforms. See comment as to how to run this test. + throw new RuntimeException("ERROR: No IPv6 address returned from platform."); + } + System.out.println("PASS: Found IPv6 address and DnsClient parsed it correctly."); + } + + private static String[] getServersFromContext(DnsContext context) { + try { + Field serversField = DnsContext.class.getDeclaredField("servers"); + serversField.setAccessible(true); + return (String[])serversField.get(context); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/jdk/test/com/sun/jndi/ldap/LdapURLOptionalFields.java b/jdk/test/com/sun/jndi/ldap/LdapURLOptionalFields.java new file mode 100644 index 00000000000..86b5c1a442b --- /dev/null +++ b/jdk/test/com/sun/jndi/ldap/LdapURLOptionalFields.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2015, Red Hat, Inc. + * 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 8074761 + * @summary RFC-2255 allows attribute, scope and filter to be empty. + */ + +import com.sun.jndi.ldap.LdapURL; + +public class LdapURLOptionalFields { + + private static final String[] TEST_URLS = { + "ldap://localhost:10389/ou=RefPeople,dc=example,dc=com", + "ldap://localhost:10389/ou=RefPeople,dc=example,dc=com?", + "ldap://localhost:10389/ou=RefPeople,dc=example,dc=com??", + "ldap://localhost:10389/ou=RefPeople,dc=example,dc=com???", + "ldap://localhost:10389/ou=RefPeople,dc=example,dc=com????" + }; + + public static void main(String[] args) throws Exception { + for (int i = 0; i < TEST_URLS.length; i++) { + String url = TEST_URLS[i]; + checkEmptyAttributes(url); + } + } + + private static void checkEmptyAttributes(String urlString) throws Exception { + LdapURL url = new LdapURL(urlString); + if (url.getAttributes() != null) { + throw new Exception("Expected null attributes for url: '" + urlString + "'"); + } + if (url.getScope() != null) { + throw new Exception("Expected null scope for url: '" + urlString + "'"); + } + if (url.getFilter() != null) { + throw new Exception("Expected null filter for url: '" + urlString + "'"); + } + } + +} diff --git a/jdk/test/com/sun/management/ThreadMXBean/ThreadCpuTimeArray.java b/jdk/test/com/sun/management/ThreadMXBean/ThreadCpuTimeArray.java index 67dea226bd1..b364312f0bd 100644 --- a/jdk/test/com/sun/management/ThreadMXBean/ThreadCpuTimeArray.java +++ b/jdk/test/com/sun/management/ThreadMXBean/ThreadCpuTimeArray.java @@ -27,6 +27,7 @@ * @summary Basic test of ThreadMXBean.getThreadCpuTime(long[]) and * getThreadUserTime(long[]). * @author Paul Hohensee + * @key randomness */ import java.lang.management.*; diff --git a/jdk/test/com/sun/nio/sctp/SctpMultiChannel/SendFailed.java b/jdk/test/com/sun/nio/sctp/SctpMultiChannel/SendFailed.java index 18f7a4c7815..be50b4efb2f 100644 --- a/jdk/test/com/sun/nio/sctp/SctpMultiChannel/SendFailed.java +++ b/jdk/test/com/sun/nio/sctp/SctpMultiChannel/SendFailed.java @@ -43,11 +43,16 @@ public class SendFailed { void test(String[] args) throws IOException { SocketAddress address = null; + String os = System.getProperty("os.name").toLowerCase(); if (!Util.isSCTPSupported()) { out.println("SCTP protocol is not supported"); out.println("Test cannot be run"); return; + } else if (os.startsWith("sunos")) { + out.println("Test not supported on Solaris"); + out.println("Test cannot be run"); + return; } System.out.println("remote address: " + remoteAddress); diff --git a/jdk/test/com/sun/security/auth/login/ConfigFile/InconsistentError.java b/jdk/test/com/sun/security/auth/login/ConfigFile/InconsistentError.java index 8bece1cb668..6dd48251ed9 100644 --- a/jdk/test/com/sun/security/auth/login/ConfigFile/InconsistentError.java +++ b/jdk/test/com/sun/security/auth/login/ConfigFile/InconsistentError.java @@ -26,6 +26,7 @@ * @bug 4406033 * @summary ConfigFile throws an inconsistent error message * when the configuration file is not found + * @run main/othervm -Duser.language=en InconsistentError */ import com.sun.security.auth.login.*; diff --git a/jdk/test/com/sun/security/auth/module/KeyStoreLoginModule/OptionTest.java b/jdk/test/com/sun/security/auth/module/KeyStoreLoginModule/OptionTest.java index 585b3b63994..3b918760200 100644 --- a/jdk/test/com/sun/security/auth/module/KeyStoreLoginModule/OptionTest.java +++ b/jdk/test/com/sun/security/auth/module/KeyStoreLoginModule/OptionTest.java @@ -25,6 +25,7 @@ * @test * @bug 4919147 * @summary Support for token-based KeyStores + * @run main/othervm -Duser.language=en OptionTest */ import java.io.File; diff --git a/jdk/test/java/awt/Checkbox/SetStateExcessEvent/SetStateExcessEvent.java b/jdk/test/java/awt/Checkbox/SetStateExcessEvent/SetStateExcessEvent.java new file mode 100644 index 00000000000..f7235beeb35 --- /dev/null +++ b/jdk/test/java/awt/Checkbox/SetStateExcessEvent/SetStateExcessEvent.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Checkbox; +import java.awt.CheckboxGroup; +import java.awt.Frame; +import java.awt.GridBagLayout; +import java.awt.Robot; + +/** + * @test + * @bug 8074500 + * @summary Checkbox.setState() call should not post ItemEvent + * @author Sergey Bylokhov + */ +public final class SetStateExcessEvent { + + private static boolean failed; + + public static void main(final String[] args) throws Exception { + final Robot robot = new Robot(); + final CheckboxGroup group = new CheckboxGroup(); + final Checkbox[] cbs = {new Checkbox("checkbox1", true, group), + new Checkbox("checkbox2", false, group), + new Checkbox("checkbox3", true, group), + + new Checkbox("checkbox4", true), + new Checkbox("checkbox5", false), + new Checkbox("checkbox6", true)}; + final Frame frame = new Frame(); + frame.setLayout(new GridBagLayout()); + try { + for (final Checkbox cb : cbs) { + cb.addItemListener(e -> { + failed = true; + }); + } + for (final Checkbox cb : cbs) { + frame.add(cb); + } + frame.pack(); + + for (final Checkbox cb : cbs) { + cb.setState(!cb.getState()); + } + + for (final Checkbox cb : cbs) { + group.setSelectedCheckbox(cb); + } + robot.waitForIdle(); + } finally { + frame.dispose(); + } + if (failed) { + throw new RuntimeException("Listener should not be called"); + } + System.out.println("Test passed"); + } +} diff --git a/jdk/test/java/awt/Focus/ModalExcludedWindowClickTest/ModalExcludedWindowClickTest.html b/jdk/test/java/awt/Focus/ModalExcludedWindowClickTest/ModalExcludedWindowClickTest.html new file mode 100644 index 00000000000..77502895ba6 --- /dev/null +++ b/jdk/test/java/awt/Focus/ModalExcludedWindowClickTest/ModalExcludedWindowClickTest.html @@ -0,0 +1,43 @@ + + + + + +ModalExcludedWindowClickTest + + + +

                            ModalExcludedWindowClickTest
                            Bug ID: 6272324

                            + +

                            See the dialog box (usually in upper left corner) for instructions

                            + + + + diff --git a/jdk/test/java/awt/Focus/ModalExcludedWindowClickTest/ModalExcludedWindowClickTest.java b/jdk/test/java/awt/Focus/ModalExcludedWindowClickTest/ModalExcludedWindowClickTest.java new file mode 100644 index 00000000000..70f6d1effd2 --- /dev/null +++ b/jdk/test/java/awt/Focus/ModalExcludedWindowClickTest/ModalExcludedWindowClickTest.java @@ -0,0 +1,291 @@ +/* + * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 6271849 + @summary Tests that component in modal excluded Window which parent is blocked responses to mouse clicks. + @author anton.tarasov@sun.com: area=awt.focus + @run applet ModalExcludedWindowClickTest.html +*/ + +import java.applet.Applet; +import java.awt.*; +import java.awt.event.*; +import java.lang.reflect.*; + +public class ModalExcludedWindowClickTest extends Applet { + Robot robot; + Frame frame = new Frame("Frame"); + Window w = new Window(frame); + Dialog d = new Dialog ((Dialog)null, "NullParentDialog", true); + Button button = new Button("Button"); + boolean actionPerformed = false; + + public static void main (String args[]) { + ModalExcludedWindowClickTest app = new ModalExcludedWindowClickTest(); + app.init(); + app.start(); + } + + public void init() { + try { + robot = new Robot(); + } catch (AWTException e) { + throw new RuntimeException("Error: unable to create robot", e); + } + // Create instructions for the user here, as well as set up + // the environment -- set the layout manager, add buttons, + // etc. + this.setLayout (new BorderLayout ()); + Sysout.createDialogWithInstructions(new String[] + {"This is an AUTOMATIC test", "simply wait until it is done"}); + } + + public void start() { + + if ("sun.awt.motif.MToolkit".equals(Toolkit.getDefaultToolkit().getClass().getName())) { + Sysout.println("No testing on MToolkit."); + return; + } + + button.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + actionPerformed = true; + Sysout.println(e.paramString()); + } + }); + + EventQueue.invokeLater(new Runnable() { + public void run() { + frame.setSize(200, 200); + frame.setVisible(true); + + w.setModalExclusionType(Dialog.ModalExclusionType.APPLICATION_EXCLUDE); + w.add(button); + w.setSize(200, 200); + w.setLocation(230, 230); + w.setVisible(true); + + d.setSize(200, 200); + d.setLocation(0, 230); + d.setVisible(true); + + } + }); + + waitTillShown(d); + + test(); + } + + void test() { + clickOn(button); + waitForIdle(); + if (!actionPerformed) { + throw new RuntimeException("Test failed!"); + } + Sysout.println("Test passed."); + } + + void clickOn(Component c) { + Point p = c.getLocationOnScreen(); + Dimension d = c.getSize(); + + Sysout.println("Clicking " + c); + + if (c instanceof Frame) { + robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + ((Frame)c).getInsets().top/2); + } else { + robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2)); + } + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + waitForIdle(); + } + void waitTillShown(Component c) { + while (true) { + try { + Thread.sleep(100); + c.getLocationOnScreen(); + break; + } catch (InterruptedException e) { + throw new RuntimeException(e); + } catch (IllegalComponentStateException e) {} + } + } + void waitForIdle() { + try { + robot.waitForIdle(); + EventQueue.invokeAndWait( new Runnable() { + public void run() {} // Dummy implementation + }); + } catch(InterruptedException ie) { + Sysout.println("waitForIdle, non-fatal exception caught:"); + ie.printStackTrace(); + } catch(InvocationTargetException ite) { + Sysout.println("waitForIdle, non-fatal exception caught:"); + ite.printStackTrace(); + } + + // wait longer... + robot.delay(200); + } +} + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout +{ + static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + dialog.displayMessage( messageIn ); + } + +}// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog +{ + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("Center", messageText); + + pack(); + + setVisible(true); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + System.out.println(messageIn); + } + +}// TestDialog class diff --git a/jdk/test/java/awt/Focus/NonFocusableBlockedOwnerTest/NonFocusableBlockedOwnerTest.html b/jdk/test/java/awt/Focus/NonFocusableBlockedOwnerTest/NonFocusableBlockedOwnerTest.html new file mode 100644 index 00000000000..a844c798cb3 --- /dev/null +++ b/jdk/test/java/awt/Focus/NonFocusableBlockedOwnerTest/NonFocusableBlockedOwnerTest.html @@ -0,0 +1,43 @@ + + + + + +NonFocusableBlockedOwnerTest + + + +

                            NonFocusableBlockedOwnerTest
                            Bug ID: 6272324

                            + +

                            See the dialog box (usually in upper left corner) for instructions

                            + + + + diff --git a/jdk/test/java/awt/Focus/NonFocusableBlockedOwnerTest/NonFocusableBlockedOwnerTest.java b/jdk/test/java/awt/Focus/NonFocusableBlockedOwnerTest/NonFocusableBlockedOwnerTest.java new file mode 100644 index 00000000000..b98fe3b522d --- /dev/null +++ b/jdk/test/java/awt/Focus/NonFocusableBlockedOwnerTest/NonFocusableBlockedOwnerTest.java @@ -0,0 +1,288 @@ +/* + * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 6272324 + @summary Modal excluded Window which decorated parent is blocked should be non-focusable. + @author anton.tarasov@sun.com: area=awt.focus + @run applet NonFocusableBlockedOwnerTest.html +*/ + +import java.applet.Applet; +import java.awt.*; +import java.awt.event.*; +import java.lang.reflect.*; + +public class NonFocusableBlockedOwnerTest extends Applet { + Robot robot; + Frame frame = new Frame("Modal Blocked Frame"); + Dialog dialog = new Dialog(frame, "Modal Dialog", true); + Window excluded = new Window(frame); + Button button = new Button("button"); + + public static void main(String[] args) { + NonFocusableBlockedOwnerTest app = new NonFocusableBlockedOwnerTest(); + app.init(); + app.start(); + } + + public void init() { + try { + robot = new Robot(); + } catch (AWTException e) { + throw new RuntimeException("Error: unable to create robot", e); + } + // Create instructions for the user here, as well as set up + // the environment -- set the layout manager, add buttons, + // etc. + this.setLayout (new BorderLayout ()); + Sysout.createDialogWithInstructions(new String[] + {"This is an AUTOMATIC test", "simply wait until it is done"}); + } + + public void start() { + + if ("sun.awt.motif.MToolkit".equals(Toolkit.getDefaultToolkit().getClass().getName())) { + Sysout.println("No testing on MToolkit."); + return; + } + + try { + EventQueue.invokeLater(new Runnable() { + public void run() { + frame.setSize(300, 200); + frame.setVisible(true); + + excluded.setSize(300, 200); + excluded.setLocation(0, 400); + excluded.setModalExclusionType(Dialog.ModalExclusionType.TOOLKIT_EXCLUDE); + excluded.setLayout(new FlowLayout()); + excluded.add(button); + excluded.setVisible(true); + + dialog.setSize(200, 100); + dialog.setLocation(0, 250); + dialog.setVisible(true); + } + }); + } catch (Exception e) { + e.printStackTrace(); + } + + waitTillShown(dialog); + clickOn(button); + if (frame == KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow()) { + throw new RuntimeException("Test failed!"); + } + if (excluded == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow()) { + throw new RuntimeException("Test failed!"); + } + if (button == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) { + throw new RuntimeException("Test failed!"); + } + Sysout.println("Test passed."); + } + + void clickOn(Component c) { + Point p = c.getLocationOnScreen(); + Dimension d = c.getSize(); + + Sysout.println("Clicking " + c); + + if (c instanceof Frame) { + robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + ((Frame)c).getInsets().top/2); + } else { + robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2)); + } + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + waitForIdle(); + } + + void waitTillShown(Component c) { + while (true) { + try { + Thread.sleep(100); + c.getLocationOnScreen(); + break; + } catch (InterruptedException e) { + throw new RuntimeException(e); + } catch (IllegalComponentStateException e) {} + } + } + void waitForIdle() { + try { + robot.waitForIdle(); + EventQueue.invokeAndWait( new Runnable() { + public void run() {} // Dummy implementation + }); + } catch(InterruptedException ie) { + Sysout.println("waitForIdle, non-fatal exception caught:"); + ie.printStackTrace(); + } catch(InvocationTargetException ite) { + Sysout.println("waitForIdle, non-fatal exception caught:"); + ite.printStackTrace(); + } + + // wait longer... + robot.delay(200); + } +} + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout +{ + static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + dialog.displayMessage( messageIn ); + } + +}// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog +{ + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("Center", messageText); + + pack(); + + setVisible(true); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + System.out.println(messageIn); + } + +}// TestDialog class diff --git a/jdk/test/java/awt/Focus/WindowUpdateFocusabilityTest/WindowUpdateFocusabilityTest.html b/jdk/test/java/awt/Focus/WindowUpdateFocusabilityTest/WindowUpdateFocusabilityTest.html new file mode 100644 index 00000000000..56b72d53944 --- /dev/null +++ b/jdk/test/java/awt/Focus/WindowUpdateFocusabilityTest/WindowUpdateFocusabilityTest.html @@ -0,0 +1,43 @@ + + + + + +WindowUpdateFocusabilityTest + + + +

                            WindowUpdateFocusabilityTest
                            Bug ID: 6253913

                            + +

                            See the dialog box (usually in upper left corner) for instructions

                            + + + + diff --git a/jdk/test/java/awt/Focus/WindowUpdateFocusabilityTest/WindowUpdateFocusabilityTest.java b/jdk/test/java/awt/Focus/WindowUpdateFocusabilityTest/WindowUpdateFocusabilityTest.java new file mode 100644 index 00000000000..8070e57a382 --- /dev/null +++ b/jdk/test/java/awt/Focus/WindowUpdateFocusabilityTest/WindowUpdateFocusabilityTest.java @@ -0,0 +1,325 @@ +/* + * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 6253913 + @summary Tests that a Window shown before its owner is focusable. + @author anton.tarasov@sun.com: area=awt-focus + @run applet WindowUpdateFocusabilityTest.html +*/ + +import java.awt.*; +import java.awt.event.*; +import java.applet.Applet; +import java.lang.reflect.*; + +public class WindowUpdateFocusabilityTest extends Applet { + Robot robot; + boolean focusGained = false; + final Object monitor = new Object(); + FocusListener listener = new FocusAdapter () { + public void focusGained(FocusEvent e) { + Sysout.println(e.toString()); + synchronized (monitor) { + focusGained = true; + monitor.notifyAll(); + } + } + }; + + public static void main(String[] args) { + WindowUpdateFocusabilityTest app = new WindowUpdateFocusabilityTest(); + app.init(); + app.start(); + } + + public void init() { + try { + robot = new Robot(); + } catch (AWTException e) { + throw new RuntimeException("Error: couldn't create robot"); + } + // Create instructions for the user here, as well as set up + // the environment -- set the layout manager, add buttons, + // etc. + this.setLayout (new BorderLayout ()); + Sysout.createDialogWithInstructions(new String[] + {"This is an automatic test. Simply wait until it's done."}); + } + + public void start() { + if ("sun.awt.motif.MToolkit".equals(Toolkit.getDefaultToolkit().getClass().getName())) { + Sysout.println("No testing on Motif."); + return; + } + + test(new Frame("Frame owner")); + Frame dialog_owner = new Frame("dialog's owner"); + test(new Dialog(dialog_owner)); + test(new Dialog(dialog_owner, Dialog.ModalityType.DOCUMENT_MODAL)); + test(new Dialog(dialog_owner, Dialog.ModalityType.APPLICATION_MODAL)); + test(new Dialog(dialog_owner, Dialog.ModalityType.TOOLKIT_MODAL)); + test(new Dialog((Window) null, Dialog.ModalityType.MODELESS)); + test(new Dialog((Window) null, Dialog.ModalityType.DOCUMENT_MODAL)); + test(new Dialog((Window) null, Dialog.ModalityType.APPLICATION_MODAL)); + test(new Dialog((Window) null, Dialog.ModalityType.TOOLKIT_MODAL)); + dialog_owner.dispose(); + } + + private void test(final Window owner) + { + Window window0 = new Window(owner); // will not be shown + Window window1 = new Window(window0); + Window window2 = new Window(window1); + Button button1 = new Button("button1"); + Button button2 = new Button("button2"); + button1.addFocusListener(listener); + button2.addFocusListener(listener); + + owner.setBounds(800, 0, 100, 100); + window1.setBounds(800, 300, 100, 100); + window2.setBounds(800, 150, 100, 100); + + window1.add(button1); + window2.add(button2); + + window2.setVisible(true); + window1.setVisible(true); + EventQueue.invokeLater(new Runnable() { + public void run() { + owner.setVisible(true); + } + }); + + try { + EventQueue.invokeAndWait(new Runnable() { + public void run() { + // do nothing just wait until previous invokeLater will be executed + } + }); + } catch (InterruptedException ie) { + throw new RuntimeException(ie); + } catch (InvocationTargetException ite) { + throw new RuntimeException(ite); + } + + robot.delay(1000); + + clickOn(button1); + + if (!isFocusGained()) { + throw new RuntimeException("Test failed: window1 is not focusable!"); + } + + focusGained = false; + clickOn(button2); + + if (!isFocusGained()) { + throw new RuntimeException("Test failed: window2 is not focusable!"); + } + + Sysout.println("Test for " + owner.getName() + " passed."); + owner.dispose(); + } + + void clickOn(Component c) { + Point p = c.getLocationOnScreen(); + Dimension d = c.getSize(); + + Sysout.println("Clicking " + c); + + robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2)); + + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + waitForIdle(); + } + + void waitForIdle() { + try { + robot.waitForIdle(); + robot.delay(50); + EventQueue.invokeAndWait( new Runnable() { + public void run() {} // Dummy implementation + }); + } catch(InterruptedException ie) { + Sysout.println("waitForIdle, non-fatal exception caught:"); + ie.printStackTrace(); + } catch(InvocationTargetException ite) { + Sysout.println("waitForIdle, non-fatal exception caught:"); + ite.printStackTrace(); + } + } + + boolean isFocusGained() { + synchronized (monitor) { + if (!focusGained) { + try { + monitor.wait(3000); + } catch (InterruptedException e) { + Sysout.println("Interrupted unexpectedly!"); + throw new RuntimeException(e); + } + } + } + return focusGained; + } +} + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout +{ + static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + dialog.displayMessage( messageIn ); + } + +}// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog +{ + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("Center", messageText); + + pack(); + + setVisible(true); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + System.out.println(messageIn); + } + +}// TestDialog class diff --git a/jdk/test/java/awt/KeyboardFocusmanager/TypeAhead/TestDialogTypeAhead.java b/jdk/test/java/awt/KeyboardFocusmanager/TypeAhead/TestDialogTypeAhead.java index 7ef62198768..8b6d2fea517 100644 --- a/jdk/test/java/awt/KeyboardFocusmanager/TypeAhead/TestDialogTypeAhead.java +++ b/jdk/test/java/awt/KeyboardFocusmanager/TypeAhead/TestDialogTypeAhead.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -192,8 +192,7 @@ public class TestDialogTypeAhead extends Applet } private void waitForIdle() { try { - Toolkit.getDefaultToolkit().sync(); - sun.awt.SunToolkit.flushPendingEvents(); + robot.waitForIdle(); EventQueue.invokeAndWait( new Runnable() { public void run() { // dummy implementation diff --git a/jdk/test/java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java b/jdk/test/java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java index a13cd81520e..4173e9b91bb 100644 --- a/jdk/test/java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java +++ b/jdk/test/java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java @@ -23,13 +23,16 @@ import java.awt.Color; import java.awt.Dialog; +import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Panel; import java.awt.Rectangle; import java.awt.Robot; import java.awt.SplashScreen; +import java.awt.TextField; import java.awt.Window; +import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; @@ -37,7 +40,7 @@ import sun.java2d.SunGraphics2D; /** * @test - * @bug 8043869 + * @bug 8043869 8075244 * @author Alexander Scherbatiy * @summary [macosx] java -splash does not honor 2x hi dpi notation for retina * support @@ -45,6 +48,7 @@ import sun.java2d.SunGraphics2D; * @run main/othervm -splash:splash1.png MultiResolutionSplashTest TEST_SPLASH 0 * @run main/othervm -splash:splash2 MultiResolutionSplashTest TEST_SPLASH 1 * @run main/othervm -splash:splash3. MultiResolutionSplashTest TEST_SPLASH 2 + * @run main/othervm -splash:splash1.png MultiResolutionSplashTest TEST_FOCUS */ public class MultiResolutionSplashTest { @@ -69,6 +73,9 @@ public class MultiResolutionSplashTest { int index = Integer.parseInt(args[1]); testSplash(tests[index]); break; + case "TEST_FOCUS": + testFocus(); + break; default: throw new RuntimeException("Unknown test: " + test); } @@ -92,12 +99,49 @@ public class MultiResolutionSplashTest { float scaleFactor = getScaleFactor(); Color testColor = (1 < scaleFactor) ? test.color2x : test.color1x; - if (!testColor.equals(splashScreenColor)) { + if (!compare(testColor, splashScreenColor)) { throw new RuntimeException( "Image with wrong resolution is used for splash screen!"); } } + static void testFocus() throws Exception { + + System.out.println("Focus Test!"); + Robot robot = new Robot(); + robot.setAutoDelay(50); + + Frame frame = new Frame(); + frame.setSize(100, 100); + String test = "123"; + TextField textField = new TextField(test); + frame.add(textField); + frame.setVisible(true); + robot.waitForIdle(); + + robot.keyPress(KeyEvent.VK_A); + robot.keyRelease(KeyEvent.VK_A); + robot.keyPress(KeyEvent.VK_B); + robot.keyRelease(KeyEvent.VK_B); + robot.waitForIdle(); + + frame.dispose(); + + if(!textField.getText().equals("ab")){ + throw new RuntimeException("Focus is lost!"); + } + } + + static boolean compare(Color c1, Color c2){ + return compare(c1.getRed(), c2.getRed()) + && compare(c1.getGreen(), c2.getGreen()) + && compare(c1.getBlue(), c2.getBlue()); + } + + static boolean compare(int n, int m){ + return Math.abs(n - m) <= 50; + } + static float getScaleFactor() { final Dialog dialog = new Dialog((Window) null); diff --git a/jdk/test/java/awt/TrayIcon/8072769/bug8072769.java b/jdk/test/java/awt/TrayIcon/8072769/bug8072769.java new file mode 100644 index 00000000000..26b64a087bd --- /dev/null +++ b/jdk/test/java/awt/TrayIcon/8072769/bug8072769.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 8072769 + @summary System tray icon title freezes java + @author Semyon Sadetsky + @library ../../../../lib/testlibrary + @build jdk.testlibrary.OSInfo + */ + +import jdk.testlibrary.OSInfo; + +import javax.swing.*; +import java.awt.*; +import java.util.Arrays; + +public class bug8072769 { + + public static void main(String[] args) throws Exception { + if (OSInfo.getOSType() == OSInfo.OSType.WINDOWS) { + if (SystemTray.isSupported()) { + test(); + } else { + System.out.println("SystemTray not supported. " + + "Test is skipped."); + } + } else { + System.out.println("Test will only run on Windows platform. " + + "Test is skipped."); + } + System.out.println("ok"); + } + + private static void test() throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + final SystemTray tray = SystemTray.getSystemTray(); + final TrayIcon trayIcon = new TrayIcon(icon.getImage()); + try { + tray.add(trayIcon); + } catch (AWTException e) { + throw new RuntimeException( + "TrayIcon could not be added."); + } + + + try { + trayIcon.displayMessage(createString(63, 'A'), + createString(255, 'C'), TrayIcon.MessageType.ERROR); + + trayIcon.setToolTip(createString(127, 'B')); + + trayIcon.displayMessage(createString(64, 'A'), + createString(256, 'C'), TrayIcon.MessageType.ERROR); + + trayIcon.setToolTip(createString(128, 'B')); + + trayIcon.displayMessage(createString(65, 'A'), + createString(257, 'C'), TrayIcon.MessageType.ERROR); + + trayIcon.setToolTip(createString(129, 'B')); + } + finally { + tray.remove(trayIcon); + } + } + }); + } + + private static String createString(int len, char letter) { + char[] chars = new char[len]; + Arrays.fill(chars, letter); + chars[len - 2] = '='; + chars[len - 1] = '>'; + return new String(chars); + } + + private static ImageIcon icon = new ImageIcon( + new byte[]{71, 73, 70, 56, 57, 97, 32, 0, 35, 0, -43, 0, 0, -1, -1, + -1, -19, -101, 9, -18, -95, 24, -14, -76, 71, -4, -19, -46, + -3, -13, -31, -17, -88, 40, -12, -63, 102, -10, -51, -124, + -16, -82, 55, -11, -57, 117, -2, -7, -15, -7, -32, -77, -9, + -45, -108, -5, -26, -62, -13, -70, 86, -8, -39, -94, 83, + -126, -95, -8, -38, -93, -6, -26, -63, -9, -45, -109, -4, + -14, -32, -15, -76, 70, -12, -58, 116, -17, -89, 39, 77, + 121, -106, -3, -8, -17, 104, -111, -84, 126, -95, -72, 93, + -119, -90, -14, -70, 85, -13, -64, 101, -16, -83, 55, -109, + -80, -60, -7, -33, -78, -100, -84, -85, 94, -127, -104, -32, + -99, 39, 127, -120, -114, 83, 113, -124, -12, -9, -7, -16, + -16, -16, -115, 108, 45, 57, 89, 110, -50, -41, -35, 104, + -111, -83, 41, 65, 80, 72, 113, -116, 115, -103, -78, 88, + 106, 112, -82, -78, -82, -45, -38, -40, -5, -20, -48, -65, + -48, -36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, -7, 4, 0, 0, 0, + 0, 0, 44, 0, 0, 0, 0, 32, 0, 35, 0, 0, 6, -1, 64, -128, 112, + 72, 4, 16, 0, 14, -57, 2, 1, 96, 30, -117, -48, 40, -78, + -55, 96, 28, 28, -125, -62, 0, 96, 48, 74, -91, -116, 102, + 3, 97, 64, 4, 20, -25, -128, 68, -80, 16, 24, 11, 95, 98, + -29, -64, 72, 11, 2, 120, -68, 96, -64, 39, 116, -29, 0, 12, + 13, 5, 1, 3, 121, -121, -120, 9, 2, 7, 5, 15, 82, 11, 11, + 92, 15, 6, -120, -107, -121, 7, 2, 18, 0, 112, 80, 3, 8, + 104, -106, -95, 122, 88, 97, 68, 5, 11, 4, -95, 32, 8, 16, + 19, 16, 8, 22, -106, -114, 79, 66, 5, 2, 15, 9, -120, 22, + 19, 81, 21, 31, -120, 7, 6, 10, 67, 71, 4, 119, -121, 20, + -128, 16, -57, 120, 7, -101, -111, -58, 9, -108, 121, -55, + -128, 0, 16, 121, 123, -117, 67, 5, -71, 121, 30, -42, 67, + 23, -121, 13, 66, 14, 6, 3, -34, 120, 21, -31, 66, 26, -39, + 3, 6, -50, 11, -96, 120, 31, -19, 67, 30, 121, 9, 14, 0, 13, + 124, -121, 68, -32, 19, 98, 6, 15, 58, 71, 18, 12, -27, 97, + 55, 80, 68, 54, 5, 5, 24, 40, 80, 23, 96, -96, -112, 9, -39, + 30, 52, -112, 72, -47, 34, 0, 10, 25, -53, 37, 60, -60, 16, + -33, 56, 61, 16, -1, 41, -60, 83, 13, 31, -122, 60, 7, 1, + -48, 59, -124, 65, 3, 62, -116, 48, -5, 57, 72, -112, -18, + -48, 5, -103, 124, 32, -32, 37, 112, -74, -119, 98, 0, 8, + -31, 64, -110, 35, 38, 64, 26, 34, -92, 113, 42, 48, -45, + 70, -76, 24, -77, 60, 80, -91, -60, -70, -12, 76, -120, 49, + 92, -120, 4, -40, -116, -126, 51, 79, -80, 97, -36, 80, 89, + -6, 25, -91, 96, -98, 89, -99, 62, 33, -62, 32, -59, -83, 0, + 82, 80, 32, 1, -72, 53, 13, -113, -42, 102, -103, 54, -127, + 25, 84, 40, 15, -115, 40, 37, 20, 49, 34, 26, 103, 78, 29, + 52, 42, 88, 16, 65, 17, -94, -49, 31, 107, 97, 16, -116, 49, + 32, 35, -61, 6, 14, 33, 56, 68, -120, -80, -96, 11, 1, 78, + -31, -6, 33, 96, 48, -93, -61, -122, 21, 46, 50, -116, -10, + -30, -47, -117, -125, 24, 29, 94, -100, -112, 61, -94, 54, + -108, 20, 38, 90, -112, -128, 81, -61, 90, 16, 0, 59}, + "try icon"); + +} diff --git a/jdk/test/java/awt/Window/AlwaysOnTop/AutoTestOnTop.java b/jdk/test/java/awt/Window/AlwaysOnTop/AutoTestOnTop.java new file mode 100644 index 00000000000..07843be5ea6 --- /dev/null +++ b/jdk/test/java/awt/Window/AlwaysOnTop/AutoTestOnTop.java @@ -0,0 +1,795 @@ +/* + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 4632143 + @summary Unit test for the RFE window/frame/dialog always on top + @author dom@sparc.spb.su: area=awt.toplevel + @run main AutoTestOnTop +*/ + +import java.awt.*; +import java.awt.event.*; +import java.lang.reflect.*; +import javax.swing.*; +import java.util.Vector; + +/** + * @author tav@sparc.spb.su + * @author dom@sparc.spb.su + * Tests that always-on-top windows combine correctly with different kinds of window in different styles and conditions. + * + * !!! WARNING !!! + * The test fails sometimes because the toFront() method doesn't guarantee + * that after its invocation the frame will be placed above all other windows. + */ +public class AutoTestOnTop { + static Window topw; + static Frame parentw = new Frame(); + static Window f; + static Frame parentf = new Frame(); + + static Object uncheckedSrc = new Object(); // used when no need to check event source + static Object eventSrc = uncheckedSrc; + static boolean dispatchedCond; + + static Semaphore STATE_SEMA = new Semaphore(); + static Semaphore VIS_SEMA = new Semaphore(); + static Vector errors = new Vector(); + + static boolean isUnix = false; + + static StringBuffer msgError = new StringBuffer(); + static StringBuffer msgCase = new StringBuffer(); + static StringBuffer msgAction = new StringBuffer(); + static StringBuffer msgFunc = new StringBuffer(); + static StringBuffer msgVisibility = new StringBuffer(); + + static volatile int stageNum; + static volatile int actNum; + static volatile int testResult = 0; + + static volatile boolean doCheckEvents; + static volatile boolean eventsCheckPassed; + static boolean[] eventsCheckInitVals = new boolean[] { // Whether events are checked for abcence or precence + true, true, true, true, true, false, false, false, false + }; + static String[] msgEventsChecks = new String[] { + null, null, null, null, null, + "expected WindowEvent.WINDOW_STATE_CHANGED hasn't been generated", + "expected WindowEvent.WINDOW_STATE_CHANGED hasn't been generated", + "expected WindowEvent.WINDOW_STATE_CHANGED hasn't been generated", + "expected WindowEvent.WINDOW_STATE_CHANGED hasn't been generated", + }; + + static final int stagesCount = 7; + static final int actionsCount = 9; + + static Method[] preActions = new Method[actionsCount]; + static Method[] postActions = new Method[actionsCount]; + static Method[] isActionsAllowed = new Method[actionsCount]; + static Method[] checksActionEvents = new Method[actionsCount]; + + static Robot robot; + + static boolean doStartTest; + static String osName = System.getProperty("os.name"); + + + public static void main(String[] args) { + checkTesting(); + + } + + public static void performTesting() { + isUnix = osName.equals("Linux") || osName.equals("SunOS"); + + Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { + public void eventDispatched(AWTEvent e) { + if (e.getID() == MouseEvent.MOUSE_CLICKED) { + if (eventSrc != null & eventSrc != uncheckedSrc && e.getSource() != eventSrc) { + error("Test failed: stage #" + stageNum + ", action # " + actNum + ": " + msgCase + ": " + msgAction + ": " + msgError); + testResult = -1; + } + synchronized (eventSrc) { + dispatchedCond = true; + eventSrc.notify(); + } + } + + if (doCheckEvents && (e.getSource() == topw || e.getSource() == f)) { + + //System.err.println("AWTEventListener: catched the event " + e); + + try { + checksActionEvents[actNum].invoke(null, new Object[] {e}); + } catch (InvocationTargetException ite) { + ite.printStackTrace(); + } catch (IllegalAccessException iae) { + iae.printStackTrace(); + } + return; + } + } + }, 0xffffffffffffffffL); + + Method[] allMethods; + + try { + allMethods = AutoTestOnTop.class.getDeclaredMethods(); + } catch (SecurityException se) { + throw new RuntimeException(se); + } + + for (int i = 0; i < allMethods.length; i++) { + String name = allMethods[i].getName(); + if (name.startsWith("preAction")) { + preActions[name.charAt(name.length() - 1) - '0'] = allMethods[i]; + } else if (name.startsWith("postAction")) { + postActions[name.charAt(name.length() - 1) - '0'] = allMethods[i]; + } else if (name.startsWith("isActionAllowed")) { + isActionsAllowed[name.charAt(name.length() - 1) - '0'] = allMethods[i]; + } else if (name.startsWith("checkActionEvents")) { + checksActionEvents[name.charAt(name.length() - 1) - '0'] = allMethods[i]; + } + } + + f = new Frame("Auxiliary Frame"); + f.setBounds(50, 0, 400, 50); + f.setVisible(true); + waitTillShown(f); + + try { + robot = new Robot(); + } catch (AWTException e) { + throw new RuntimeException("Error: unable to create robot", e); + } + + mainTest(); + + if (testResult != 0) { + System.err.println("The following errors were encountered: "); + for (int i = 0; i < errors.size(); i++) { + System.err.println(errors.get(i).toString()); + } + throw new RuntimeException("Test failed."); + } else { + System.err.println("Test PASSED."); + } + } + + public static void mainTest() { +// stageNum = 0; +// for (int i = 0; i < 5; i++) { +// actNum = 2; +// System.err.println("************************* A C T I O N " + actNum + " *************************"); +// doStage(stageNum, actNum); +// // pause(500); +// actNum = 3; +// System.err.println("************************* A C T I O N " + actNum + " *************************"); +// doStage(stageNum, actNum); +// // pause(500); +// } + for (stageNum = 0; stageNum < stagesCount; stageNum++) { + System.err.println("************************* S T A G E " + stageNum + " *************************"); + for (actNum = 0; actNum < actionsCount; actNum++) { + System.err.println("************************* A C T I O N " + actNum + " *************************"); + doStage(stageNum, actNum); + } // for thru actNum + } // fow thru stageNum + + eventSrc = null; + } + + private static void doStage(int stageNum, int actNum) { + try { + + if (!((Boolean)isActionsAllowed[actNum].invoke(null, new Object[0])).booleanValue()) { + System.err.println("Action skipped due to a platform limitations"); + return; + } + + STATE_SEMA.reset(); + createWindow(stageNum); + + //************************* + // Set window always-on-top + //************************* + + preActions[actNum].invoke(null, new Object[0]); + setAlwaysOnTop(topw, true); + waitForIdle(true); + + if (!topw.isAlwaysOnTopSupported()) return; + + postActions[actNum].invoke(null, new Object[0]); + waitForIdle(false); + + STATE_SEMA.reset(); + + testForAlwaysOnTop(); + + //***************************** + // Set window not always-on-top + //***************************** + + preActions[actNum].invoke(null, new Object[0]); + setAlwaysOnTop(topw, false); + waitForIdle(true); + postActions[actNum].invoke(null, new Object[0]); + waitForIdle(false); + STATE_SEMA.reset(); + + testForNotAlwaysOnTop(); + + } catch (InvocationTargetException ite) { + ite.printStackTrace(); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } + + private static void checkTesting() { + if (Toolkit.getDefaultToolkit().isAlwaysOnTopSupported()) { + performTesting(); + } + } + + public static void testForAlwaysOnTop() { + System.err.println("Checking for always-on-top " + topw); + + ensureInitialWinPosition(topw); + + // Check that always-on-top window is topmost. + // - Click on always-on-top window on the windows cross area. + clickOn(topw, f, 10, 30, "setting " + msgVisibility + + " window (1) always-on-top didn't make it topmost"); + + // Check that we can't change z-order of always-on-top window. + // - a) Try to put the other window on the top. + f.toFront(); + clickOn(uncheckedSrc, f, 190, 30, ""); // coz toFront() works not always + pause(300); + + // - b) Click on always-on-top window on the windows cross area. + clickOn(topw, f, 10, 30, "setting " + msgVisibility + + " window (1) always-on-top didn't make it such"); + + // Ask for always-on-top property + if (isAlwaysOnTop(topw) != true) + error("Test failed: stage #" + stageNum + ", action #" + actNum + ": " + msgCase + ": " + msgAction + + ": isAlwaysOnTop() returned 'false' for window (1) set always-on-top at state " + + msgVisibility); + } + + public static void testForNotAlwaysOnTop() { + System.err.println("Checking for non always-on-top of " + topw); + ensureInitialWinPosition(topw); + + if (msgVisibility.equals("visible") && actNum != 2) { + // Check that the window remains topmost. + // - click on the window on the windows cross area. + clickOn(topw, f, 10, 30, "setting " + msgVisibility + + " window (1) not always-on-top didn't keep it topmost"); + } + + // Check that we can change z-order of not always-on-top window. + // - a) try to put the other window on the top. + f.toFront(); + clickOn(uncheckedSrc, f, 190, 30, ""); // coz toFront() works not always + pause(300); + + // - b) click on not always-on-top window on the windows cross area. + clickOn(f, f, 10, 30, "setting " + msgVisibility + + " window (1) not always-on-top didn't make it such"); + + // Ask for always-on-top property + if (isAlwaysOnTop(topw) != false) + error("Test failed: stage #" + stageNum + ", action #" + actNum + ": " + msgCase + ": " + msgAction + + ": isAlwaysOnTop() returned 'true' for window (1) set not always-on-top at state " + + msgVisibility); + } + + + private static void createWindow(int stageNum) { + // Free native resourses + if (topw != null && topw.isVisible()) { + topw.dispose(); + } + + switch (stageNum) { + case 0: + topw = new Frame("Top Frame"); + msgCase.replace(0, msgCase.length(), "Frame (1) over Frame (2)"); + break; + case 1: + topw = new JFrame("Top JFrame"); + msgCase.replace(0, msgCase.length(), "JFrame (1) over Frame (2)"); + break; + case 2: + topw = new Dialog(parentw, "Top Dialog"); + msgCase.replace(0, msgCase.length(), "Dialog (1) over Frame (2)"); + break; + case 3: + topw = new JDialog(parentw, "Top JDialog"); + msgCase.replace(0, msgCase.length(), "JDialog (1) over Frame (2)"); + break; + case 4: + topw = new Frame("Top Frame"); + f.dispose(); + f = new Dialog(parentf, "Auxiliary Dialog"); + f.setBounds(50, 0, 250, 50); + f.setVisible(true); + waitTillShown(f); + msgCase.replace(0, msgCase.length(), "Frame (1) over Dialog (2)"); + break; + case 5: + topw = new Window(parentw); + msgCase.replace(0, msgCase.length(), "Window (1) over Frame (2)"); + break; + case 6: + topw = new JWindow(parentw); + msgCase.replace(0, msgCase.length(), "JWindow (1) over Frame (2)"); + break; + } + topw.addWindowStateListener(new WindowAdapter() { + public void windowStateChanged(WindowEvent e) { + System.err.println("* " + e); + STATE_SEMA.raise(); + } + }); + topw.setSize(200, 50); + } + + /** + * 0: setting always-on-top to invisible window + * 1: setting always-on-top to visible window + * 2: always-on-top on visible non-focusable window + * 3: always-on-top on visible, dragging topw after that + * 4: always-on-top on visible, dragging f after that + * 5: always-on-top on (visible, maximized), make normal after that + * 6: always-on-top on (visible, iconified), make normal after that + * 7: always-on-top on visible, iconify/deiconify after that + * 8: always-on-top on visible, maximize/restore after that + */ + public static void preAction_0() { + topw.setVisible(false); + } + public static void postAction_0() { + if (topw.isShowing()) { + error("Test failed: stage #" + stageNum + ", action #" + actNum + ": " + msgCase + + ": no actions with windows: changing always-on-top property at window (1) state 'invisible' makes window (1) visible"); + } + setWindowVisible("no actions with windows", "invisible"); + } + public static boolean isActionAllowed_0() { + // Window on Linux is always always-on-top! + return !((stageNum == 5 || stageNum == 6) && isUnix) && (stageNum < stagesCount); + } + public static void checkActionEvents_0(AWTEvent e) { + System.err.println(e.toString()); + } + + public static void preAction_1() { + setWindowVisible("no actions with windows", "visible"); + } + public static void postAction_1() {} + public static boolean isActionAllowed_1() { + return !((stageNum == 5 || stageNum == 6) && isUnix) && (stageNum < stagesCount ); + } + public static void checkActionEvents_1(AWTEvent e) { + System.err.println(e.toString()); + if (e instanceof PaintEvent) { + return; + } + eventsCheckPassed = false; + error("Test failed: stage #" + stageNum + ", action # " + actNum + ": " + msgCase + ": " + msgAction + ": after call " + msgFunc + + ": unexpected event " + e + " was generated"); + } + + public static void preAction_2() { + setWindowVisible("when window (1) set not focusable", "visible"); + topw.setFocusableWindowState(false); + f.toFront(); + pause(300); + } + public static void postAction_2() {} + public static boolean isActionAllowed_2() { + return !((stageNum == 5 || stageNum == 6) && isUnix) && (stageNum < stagesCount); + } + public static void checkActionEvents_2(AWTEvent e) { + System.err.println(e.toString()); + if ( (e.getID() >= FocusEvent.FOCUS_FIRST && e.getID() <= FocusEvent.FOCUS_LAST) || + (e.getID() == WindowEvent.WINDOW_LOST_FOCUS && e.getID() == WindowEvent.WINDOW_GAINED_FOCUS)) { + eventsCheckPassed = false; + error("Test failed: stage #" + stageNum + ", action # " + actNum + ": " + msgCase + ": " + + msgAction + ": after call " + msgFunc + + ": unexpected event " + e + " was generated"); + } + } + + public static void preAction_3() { + setWindowVisible("after dragging", "visible"); + } + public static void postAction_3() { + Point p = topw.getLocationOnScreen(); + int x = p.x + 40, y = p.y + 5; + + try { // Take a pause to avoid double click + Thread.sleep(500); // when called one after another. + } catch (InterruptedException ie) { + ie.printStackTrace(); + } catch (IllegalComponentStateException e) { + e.printStackTrace(); + } + + // Drag the window. + robot.mouseMove(x, y); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseMove(200, 50); + robot.mouseMove(x, y); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + } + public static boolean isActionAllowed_3() { + return (stageNum < 5); + } + public static void checkActionEvents_3(AWTEvent e) { + System.err.println(e.toString()); + } + + public static void preAction_4() { + setWindowVisible("after dragging window (2)", "visible"); + } + public static void postAction_4() { + Point p = f.getLocationOnScreen(); + int x = p.x + 150, y = p.y + 5; + + try { // Take a pause to avoid double click + Thread.sleep(500); // when called one after another. + } catch (InterruptedException ie) { + ie.printStackTrace(); + } catch (IllegalComponentStateException e) { + e.printStackTrace(); + } + + // Drag the window. + robot.mouseMove(x, y); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseMove(200, 50); + robot.mouseMove(x, y); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + ensureInitialWinPosition(f); + } + public static boolean isActionAllowed_4() { + return !((stageNum == 5 || stageNum == 6) && isUnix); + } + public static void checkActionEvents_4(AWTEvent e) { + System.err.println(e.toString()); + } + + // Metacity has a bug not allowing to set a window to NORMAL state!!! + + public static void preAction_5() { + setWindowVisible("at state 'maximized'", "visible"); + ((Frame)topw).setExtendedState(Frame.MAXIMIZED_BOTH); + waitForStateChange(); + } + public static void postAction_5() { + ((Frame)topw).setExtendedState(Frame.NORMAL); + waitForStateChange(); + } + public static boolean isActionAllowed_5() { + return (stageNum < 2); + } + public static void checkActionEvents_5(AWTEvent e) { + System.err.println("=" + e.toString()); + if (e.getID() == WindowEvent.WINDOW_STATE_CHANGED) { + eventsCheckPassed = true; + } + } + + public static void preAction_6() { + setWindowVisible("at state 'iconified'", "visible"); + System.err.println("Iconifying " + topw); + ((Frame)topw).setExtendedState(Frame.ICONIFIED); + if (!waitForStateChange()) { + error("Test failed: stage #" + stageNum + ", action # " + actNum + ": " + msgCase + ": " + msgAction + ": after call " + msgFunc + + ": state change to ICONIFIED hasn't been generated"); + } + } + public static void postAction_6() { + System.err.println("Restoring " + topw); + ((Frame)topw).setExtendedState(Frame.NORMAL); + if (!waitForStateChange()) { + error("Test failed: stage #" + stageNum + ", action # " + actNum + ": " + msgCase + ": " + msgAction + ": after call " + msgFunc + + ": state change to NORMAL hasn't been generated"); + } + } + public static boolean isActionAllowed_6() { + return (stageNum < 2 ); + } + public static void checkActionEvents_6(AWTEvent e) { + System.err.println("+" + e.toString()); + if (e.getID() == WindowEvent.WINDOW_STATE_CHANGED) { + eventsCheckPassed = true; + } + } + + public static void preAction_7() { + setWindowVisible("before state 'iconified'", "visible"); + } + public static void postAction_7() { + System.err.println("Setting iconified"); + ((Frame)topw).setExtendedState(Frame.ICONIFIED); + if (!waitForStateChange()) { + error("Test failed: stage #" + stageNum + ", action # " + actNum + ": " + msgCase + ": " + msgAction + ": after call " + msgFunc + + ": state change to ICONIFIED hasn't been generated"); + } + System.err.println("Setting normal"); + ((Frame)topw).setExtendedState(Frame.NORMAL); + if (!waitForStateChange()) { + error("Test failed: stage #" + stageNum + ", action # " + actNum + ": " + msgCase + ": " + msgAction + ": after call " + msgFunc + + ": state change to NORMAL hasn't been generated"); + } + } + public static boolean isActionAllowed_7() { + return (stageNum < 2); + } + public static void checkActionEvents_7(AWTEvent e) { + System.err.println(e.toString()); + if (e.getID() == WindowEvent.WINDOW_STATE_CHANGED) { + eventsCheckPassed = true; + } + } + + public static void preAction_8() { + setWindowVisible("before state 'maximized'", "visible"); + } + public static void postAction_8() { + ((Frame)topw).setExtendedState(Frame.MAXIMIZED_BOTH); + if (!waitForStateChange()) { + error("Test failed: stage #" + stageNum + ", action # " + actNum + ": " + msgCase + ": " + msgAction + ": after call " + msgFunc + + ": state change to MAXIMIZED hasn't been generated"); + } + ((Frame)topw).setExtendedState(Frame.NORMAL); + if (!waitForStateChange()) { + error("Test failed: stage #" + stageNum + ", action # " + actNum + ": " + msgCase + ": " + msgAction + ": after call " + msgFunc + + ": state change to NORMAL hasn't been generated"); + } + } + public static boolean isActionAllowed_8() { + return (stageNum < 2); + } + public static void checkActionEvents_8(AWTEvent e) { + System.err.println(e.toString()); + if (e.getID() == WindowEvent.WINDOW_STATE_CHANGED) { + eventsCheckPassed = true; + } + } + + //*************************************************************************** + + private static void setWindowVisible(String mAction, String mVisibility) { + msgAction.replace(0, msgAction.length(), mAction); + msgVisibility.replace(0, msgVisibility.length(), mVisibility); + + topw.setVisible(true); + pause(100); // Needs for Sawfish + topw.setLocation(0, 0); + waitTillShown(topw); + f.toFront(); + pause(300); + } + + private static void clickOn(Object src, Window relwin, int x, int y, String errorStr) { + Point p = relwin.getLocationOnScreen(); + int counter = 10; + while (--counter > 0) { + eventSrc = src; + msgError.replace(0, msgError.length(), errorStr); + + robot.mouseMove(p.x + x, p.y + y); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + synchronized (eventSrc) { + if (!dispatchedCond) { + try { + eventSrc.wait(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + if (!dispatchedCond) { + //System.err.println("clickOn: MOUSE_CLICKED event losed, trying to generate it again..."); + continue; + } + dispatchedCond = false; + } + break; + } // end while + if (counter <= 0) { + eventSrc = uncheckedSrc; + error("Test: internal error: could't catch MOUSE_CLICKED event. Skip testing this stage"); + } + } + + private static void setAlwaysOnTop(Window w, boolean value) { + System.err.println("Setting always on top on " + w + " to " + value); + robot.mouseMove(0, 100); // Move out of the window + msgFunc.replace(0, msgCase.length(), "setAlwaysOnTop()"); + try { + w.setAlwaysOnTop(value); + } catch (Exception e) { + error("Test failed: stage#" + stageNum + "action #" + actNum + ": " + msgCase + ": " + msgAction + + ": setAlwaysOnTop(" + value + ") called at state " + msgVisibility + + " threw exeption " + e); + } + } + + private static boolean isAlwaysOnTop(Window w) { + robot.mouseMove(0, 100); // Move out of the window + msgFunc.replace(0, msgCase.length(), "isAlwaysOnTop()"); + boolean result = false; + try { + result = w.isAlwaysOnTop(); + } catch (Exception e) { + error("Test failed: stage #" + stageNum + ", action # " + actNum + ": " + msgCase + ": " + msgAction + + ": isAlwaysOnTop() called at state " + msgVisibility + + " threw exeption " + e); + } + return result; + } + + private static void waitTillShown(Component c) { + while (true) { + try { + Thread.sleep(100); + c.getLocationOnScreen(); + break; + } catch (InterruptedException e) { + e.printStackTrace(); + break; + } + } + } + + private static void waitForIdle(boolean doCheck) { + try { + robot.waitForIdle(); + EventQueue.invokeAndWait( new Runnable() { + public void run() {} // Dummy implementation + } ); + } catch(InterruptedException ite) { + System.err.println("waitForIdle, non-fatal exception caught:"); + ite.printStackTrace(); + } catch(InvocationTargetException ine) { + System.err.println("waitForIdle, non-fatal exception caught:"); + ine.printStackTrace(); + } + doCheckEvents = doCheck; + + if (doCheck) { + eventsCheckPassed = eventsCheckInitVals[actNum]; // Initialize + } else if (!eventsCheckPassed && + msgEventsChecks[actNum] != null) { + + + // Some expected event hasn't been catched, + // so give it one more chance... + doCheckEvents = true; + pause(500); + doCheckEvents = false; + + if (!eventsCheckPassed) { + testResult = -1; + error("Test failed: stage #" + stageNum + ", action # " + actNum + ": " + msgCase + ": " + msgAction + ": after call " + + msgFunc + ": " + msgEventsChecks[actNum]); + } + } + } + + private static boolean waitForStateChange() { + System.err.println("------- Waiting for state change"); + try { + STATE_SEMA.doWait(3000); + } catch (InterruptedException ie) { + System.err.println("Wait interrupted: " + ie); + } + boolean state = STATE_SEMA.getState(); + STATE_SEMA.reset(); + return state; + } + + private static void ensureInitialWinPosition(Window w) { + int counter = 30; + while (w.getLocationOnScreen().y != 0 && --counter > 0) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + break; + } + } + if (counter <= 0) { + w.setLocation(0, 0); + pause(100); + System.err.println("Test: window set to initial position forcedly"); + } + } + + private static void pause(int mls) { + try { + Thread.sleep(mls); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + private static void error(String msg) { + errors.add(msg); + System.err.println(msg); + } +} + +class Semaphore { + boolean state = false; + int waiting = 0; + public Semaphore() { + } + public synchronized void doWait() throws InterruptedException { + if (state) { + return; + } + waiting++; + wait(); + waiting--; + } + public synchronized void doWait(int timeout) throws InterruptedException { + if (state) { + return; + } + waiting++; + wait(timeout); + waiting--; + } + public synchronized void raise() { + state = true; + if (waiting > 0) { + notifyAll(); + } + } + + public synchronized void doNotify() { + notifyAll(); + } + public synchronized boolean getState() { + return state; + } + + public synchronized void reset() { + state = false; + } +} diff --git a/jdk/test/java/awt/datatransfer/ClipboardInterVMTest/ClipboardInterVMTest.java b/jdk/test/java/awt/datatransfer/ClipboardInterVMTest/ClipboardInterVMTest.java new file mode 100644 index 00000000000..fd1fa7cf302 --- /dev/null +++ b/jdk/test/java/awt/datatransfer/ClipboardInterVMTest/ClipboardInterVMTest.java @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 8071668 + @summary Check whether clipboard see changes from external process after taking ownership + @author Anton Nashatyrev: area=datatransfer + @library /lib/testlibrary + @build jdk.testlibrary.Utils + @run main ClipboardInterVMTest +*/ + +import jdk.testlibrary.Utils; + +import java.awt.*; +import java.awt.datatransfer.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +public class ClipboardInterVMTest { + + static CountDownLatch lostOwnershipMonitor = new CountDownLatch(1); + static CountDownLatch flavorChangedMonitor = new CountDownLatch(1); + static Process process; + + public static void main(String[] args) throws Throwable { + Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); + + if (args.length > 0) { + System.out.println("Changing clip..."); + clip.setContents(new StringSelection("pong"), null); + System.out.println("done"); + // keeping this process running for a while since on Mac the clipboard + // will be invalidated via NSApplicationDidBecomeActiveNotification + // callback in the main process after this child process finishes + Thread.sleep(60 * 1000); + return; + }; + + + clip.setContents(new CustomSelection(), new ClipboardOwner() { + @Override + public void lostOwnership(Clipboard clipboard, Transferable contents) { + System.out.println("ClipboardInterVMTest.lostOwnership"); + lostOwnershipMonitor.countDown(); + } + }); + + clip.addFlavorListener(new FlavorListener() { + @Override + public void flavorsChanged(FlavorEvent e) { + System.out.println("ClipboardInterVMTest.flavorsChanged"); + flavorChangedMonitor.countDown(); + } + }); + + System.out.println("Starting external clipborad modifier..."); + new Thread(() -> runTest(ClipboardInterVMTest.class.getCanonicalName(), "pong")).start(); + + String content = ""; + long startTime = System.currentTimeMillis(); + while (System.currentTimeMillis() - startTime < 30 * 1000) { + Transferable c = clip.getContents(null); + if (c.isDataFlavorSupported(DataFlavor.plainTextFlavor)) { + Reader reader = DataFlavor.plainTextFlavor.getReaderForText(c); + content = new BufferedReader(reader).readLine(); + System.out.println(content); + if (content.equals("pong")) { + break; + } + } + Thread.sleep(200); + } + + if (!lostOwnershipMonitor.await(10, TimeUnit.SECONDS)) { + throw new RuntimeException("No LostOwnership event received."); + }; + + if (!flavorChangedMonitor.await(10, TimeUnit.SECONDS)) { + throw new RuntimeException("No LostOwnership event received."); + }; + + if (!content.equals("pong")) { + throw new RuntimeException("Content was not passed."); + } + + process.destroy(); + + System.out.println("Passed."); + } + + private static void runTest(String main, String... args) { + + try { + List opts = new ArrayList<>(); + opts.add(getJavaExe()); + opts.addAll(Arrays.asList(Utils.getTestJavaOpts())); + opts.add("-cp"); + opts.add(System.getProperty("test.class.path", System.getProperty("java.class.path"))); + + opts.add(main); + opts.addAll(Arrays.asList(args)); + + ProcessBuilder pb = new ProcessBuilder(opts.toArray(new String[0])); + process = pb.start(); + } catch (Throwable throwable) { + throw new RuntimeException(throwable); + } + } + + private static String getJavaExe() throws IOException { + File p = new File(System.getProperty("java.home"), "bin"); + File j = new File(p, "java"); + if (!j.canRead()) { + j = new File(p, "java.exe"); + } + if (!j.canRead()) { + throw new RuntimeException("Can't find java executable in " + p); + } + return j.getCanonicalPath(); + } + + static class CustomSelection implements Transferable { + private static final DataFlavor[] flavors = { DataFlavor.allHtmlFlavor }; + + public DataFlavor[] getTransferDataFlavors() { + return flavors; + } + + public boolean isDataFlavorSupported(DataFlavor flavor) { + return flavors[0].equals(flavor); + } + + public Object getTransferData(DataFlavor flavor) + throws UnsupportedFlavorException, java.io.IOException { + if (isDataFlavorSupported(flavor)) { + return "ping"; + } else { + throw new UnsupportedFlavorException(flavor); + } + } + } +} \ No newline at end of file diff --git a/jdk/test/java/awt/event/ComponentEvent/MovedResizedTardyEventTest/MovedResizedTardyEventTest.html b/jdk/test/java/awt/event/ComponentEvent/MovedResizedTardyEventTest/MovedResizedTardyEventTest.html new file mode 100644 index 00000000000..39bbfcab4cd --- /dev/null +++ b/jdk/test/java/awt/event/ComponentEvent/MovedResizedTardyEventTest/MovedResizedTardyEventTest.html @@ -0,0 +1,43 @@ + + + + + +MovedResizedTardyEventTest + + + +

                            MovedResizedTardyEventTest
                            Bug ID: 4985250

                            + +

                            See the dialog box (usually in upper left corner) for instructions

                            + + + + diff --git a/jdk/test/java/awt/event/ComponentEvent/MovedResizedTardyEventTest/MovedResizedTardyEventTest.java b/jdk/test/java/awt/event/ComponentEvent/MovedResizedTardyEventTest/MovedResizedTardyEventTest.java new file mode 100644 index 00000000000..4c775119e9d --- /dev/null +++ b/jdk/test/java/awt/event/ComponentEvent/MovedResizedTardyEventTest/MovedResizedTardyEventTest.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 4985250 + @summary COMPONENT_MOVED/RESIZED tardy events shouldn't be generated. + @author tav@sparc.spb.su + @run applet MovedResizedTardyEventTest.html +*/ + +import java.awt.*; +import java.awt.event.*; +import java.applet.Applet; +import java.lang.reflect.InvocationTargetException; + +public class MovedResizedTardyEventTest extends Applet { + Frame f1 = new Frame("F-1"); + Frame f2 = new Frame("F-2"); + + boolean eventFlag = false; + + public static void main(String[] args) { + Applet a = new MovedResizedTardyEventTest(); + a.start(); + } + + public void start() { + f1.setVisible(true); + f2.setVisible(true); + + try { + Thread.sleep(500); + } catch (InterruptedException e) {} + + f1.addComponentListener(new ComponentAdapter() { + public void componentMoved(ComponentEvent e) { + MovedResizedTardyEventTest.this.eventFlag = true; + System.err.println(e); + } + public void componentResized(ComponentEvent e) { + MovedResizedTardyEventTest.this.eventFlag = true; + System.err.println(e); + } + }); + + f1.toFront(); + + waitForIdle(); + + try { // wait more... + Thread.sleep(500); + } catch (InterruptedException e) {} + + if (eventFlag) { + throw new RuntimeException("Test failed!"); + } + } + + void waitForIdle() { + try { + (new Robot()).waitForIdle(); + EventQueue.invokeAndWait( new Runnable() { + public void run() {} // Dummy implementation + }); + } catch(InterruptedException ie) { + System.err.println("waitForIdle, non-fatal exception caught:"); + ie.printStackTrace(); + } catch(InvocationTargetException ite) { + System.err.println("waitForIdle, non-fatal exception caught:"); + ite.printStackTrace(); + } catch(AWTException rex) { + rex.printStackTrace(); + throw new RuntimeException("unexpected exception"); + } + } +} diff --git a/jdk/test/java/awt/event/KeyEvent/AltCharAcceleratorTest/AltCharAcceleratorTest.java b/jdk/test/java/awt/event/KeyEvent/AltCharAcceleratorTest/AltCharAcceleratorTest.java index 6a5a26f84bf..741c4813903 100644 --- a/jdk/test/java/awt/event/KeyEvent/AltCharAcceleratorTest/AltCharAcceleratorTest.java +++ b/jdk/test/java/awt/event/KeyEvent/AltCharAcceleratorTest/AltCharAcceleratorTest.java @@ -29,8 +29,6 @@ @run main AltCharAcceleratorTest */ -import sun.awt.SunToolkit; - import javax.swing.*; import java.awt.*; import java.awt.event.*; @@ -103,12 +101,11 @@ public class AltCharAcceleratorTest { } void test() throws Exception { - ((SunToolkit) Toolkit.getDefaultToolkit()).realSync(); - - focusLatch.await(5, TimeUnit.SECONDS); - Robot robot = new Robot(); robot.setAutoDelay(100); + robot.waitForIdle(); + + focusLatch.await(5, TimeUnit.SECONDS); robot.keyPress(KeyEvent.VK_ALT); robot.keyPress(KeyEvent.VK_T); @@ -133,4 +130,4 @@ public class AltCharAcceleratorTest { AltCharAcceleratorTest t = new AltCharAcceleratorTest(); t.test(); } -} \ No newline at end of file +} diff --git a/jdk/test/java/awt/geom/Path2D/Path2DCopyConstructor.java b/jdk/test/java/awt/geom/Path2D/Path2DCopyConstructor.java new file mode 100644 index 00000000000..5413d5138c5 --- /dev/null +++ b/jdk/test/java/awt/geom/Path2D/Path2DCopyConstructor.java @@ -0,0 +1,537 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +import java.awt.Rectangle; +import java.awt.geom.AffineTransform; +import java.awt.geom.GeneralPath; +import java.awt.geom.IllegalPathStateException; +import java.awt.geom.Path2D; +import java.awt.geom.PathIterator; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.util.Arrays; + +/** + * @test + * @bug 8076419 + * @summary Check Path2D copy constructor (trims arrays) + * and constructor with zero capacity + * @run main Path2DTrimCopy + */ +public class Path2DCopyConstructor { + + private final static float EPSILON = 5e-6f; + private final static float FLATNESS = 1e-2f; + + private final static AffineTransform at + = AffineTransform.getScaleInstance(1.3, 2.4); + + private final static Rectangle2D.Double rect2d + = new Rectangle2D.Double(3.2, 4.1, 5.0, 10.0); + + private final static Point2D.Double pt2d + = new Point2D.Double(2.0, 2.5); + + public static boolean verbose; + + static void log(String msg) { + if (verbose) { + System.out.println(msg); + } + } + + public static void main(String argv[]) { + verbose = (argv.length != 0); + + testEmptyDoublePaths(); + testDoublePaths(); + + testEmptyFloatPaths(); + testFloatPaths(); + + testEmptyGeneralPath(); + testGeneralPath(); + } + + static void testEmptyDoublePaths() { + log("\n - Test(Path2D.Double[0]) ---"); + test(() -> new Path2D.Double(Path2D.WIND_NON_ZERO, 0)); + } + + static void testDoublePaths() { + log("\n - Test(Path2D.Double) ---"); + test(() -> new Path2D.Double()); + } + + static void testEmptyFloatPaths() { + log("\n - Test(Path2D.Float[0]) ---"); + test(() -> new Path2D.Float(Path2D.WIND_NON_ZERO, 0)); + } + + static void testFloatPaths() { + log("\n - Test(Path2D.Float) ---"); + test(() -> new Path2D.Float()); + } + + static void testEmptyGeneralPath() { + log("\n - Test(GeneralPath[0]) ---"); + test(() -> new GeneralPath(Path2D.WIND_NON_ZERO, 0)); + } + + static void testGeneralPath() { + log("\n - Test(GeneralPath) ---"); + test(() -> new GeneralPath()); + } + + interface PathFactory { + Path2D makePath(); + } + + static void test(PathFactory pf) { + log("\n --- test: path(empty) ---"); + test(pf.makePath(), true); + log("\n\n --- test: path(addMove) ---"); + test(addMove(pf.makePath()), false); + log("\n\n --- test: path(addMoveAndLines) ---"); + test(addMoveAndLines(pf.makePath()), false); + log("\n\n --- test: path(addMoveAndQuads) ---"); + test(addMoveAndQuads(pf.makePath()), false); + log("\n\n --- test: path(addMoveAndCubics) ---"); + test(addMoveAndCubics(pf.makePath()), false); + log("\n\n --- test: path(addMoveAndClose) ---"); + test(addMoveAndClose(pf.makePath()), false); + } + + static Path2D addMove(Path2D p2d) { + p2d.moveTo(1.0, 0.5); + return p2d; + } + + static Path2D addMoveAndLines(Path2D p2d) { + addMove(p2d); + addLines(p2d); + return p2d; + } + + static Path2D addLines(Path2D p2d) { + for (int i = 0; i < 10; i++) { + p2d.lineTo(1.1 * i, 2.3 * i); + } + return p2d; + } + + static Path2D addMoveAndCubics(Path2D p2d) { + addMove(p2d); + addCubics(p2d); + return p2d; + } + + static Path2D addCubics(Path2D p2d) { + for (int i = 0; i < 10; i++) { + p2d.curveTo(1.1 * i, 1.2 * i, 1.3 * i, 1.4 * i, 1.5 * i, 1.6 * i); + } + return p2d; + } + + static Path2D addMoveAndQuads(Path2D p2d) { + addMove(p2d); + addQuads(p2d); + return p2d; + } + + static Path2D addQuads(Path2D p2d) { + for (int i = 0; i < 10; i++) { + p2d.quadTo(1.1 * i, 1.2 * i, 1.3 * i, 1.4 * i); + } + return p2d; + } + + static Path2D addMoveAndClose(Path2D p2d) { + addMove(p2d); + addClose(p2d); + return p2d; + } + + static Path2D addClose(Path2D p2d) { + p2d.closePath(); + return p2d; + } + + static void test(Path2D p2d, boolean isEmpty) { + testEqual(new Path2D.Float(p2d), p2d); + testEqual(new Path2D.Double(p2d), p2d); + testEqual(new GeneralPath(p2d), p2d); + + testIterator(new Path2D.Float(p2d), p2d); + testIterator(new Path2D.Double(p2d), p2d); + testIterator((Path2D) p2d.clone(), p2d); + + testFlattening(new Path2D.Float(p2d), p2d); + testFlattening(new Path2D.Double(p2d), p2d); + testFlattening((Path2D) p2d.clone(), p2d); + + testAddMove(new Path2D.Float(p2d)); + testAddMove(new Path2D.Double(p2d)); + testAddMove((Path2D) p2d.clone()); + + // These should expect exception if empty + testAddLine(new Path2D.Float(p2d), isEmpty); + testAddLine(new Path2D.Double(p2d), isEmpty); + testAddLine((Path2D) p2d.clone(), isEmpty); + + testAddQuad(new Path2D.Float(p2d), isEmpty); + testAddQuad(new Path2D.Double(p2d), isEmpty); + testAddQuad((Path2D) p2d.clone(), isEmpty); + + testAddCubic(new Path2D.Float(p2d), isEmpty); + testAddCubic(new Path2D.Double(p2d), isEmpty); + testAddCubic((Path2D) p2d.clone(), isEmpty); + + testAddClose(new Path2D.Float(p2d), isEmpty); + testAddClose(new Path2D.Double(p2d), isEmpty); + testAddClose((Path2D) p2d.clone(), isEmpty); + + testGetBounds(new Path2D.Float(p2d), p2d); + testGetBounds(new Path2D.Double(p2d), p2d); + testGetBounds((Path2D) p2d.clone(), p2d); + + testTransform(new Path2D.Float(p2d)); + testTransform(new Path2D.Double(p2d)); + testTransform((Path2D) p2d.clone()); + + testIntersect(new Path2D.Float(p2d), p2d); + testIntersect(new Path2D.Double(p2d), p2d); + testIntersect((Path2D) p2d.clone(), p2d); + + testContains(new Path2D.Float(p2d), p2d); + testContains(new Path2D.Double(p2d), p2d); + testContains((Path2D) p2d.clone(), p2d); + + testGetCurrentPoint(new Path2D.Float(p2d), p2d); + testGetCurrentPoint(new Path2D.Double(p2d), p2d); + testGetCurrentPoint((Path2D) p2d.clone(), p2d); + } + + static void testEqual(Path2D pathA, Path2D pathB) { + final PathIterator itA = pathA.getPathIterator(null); + final PathIterator itB = pathB.getPathIterator(null); + + float[] coordsA = new float[6]; + float[] coordsB = new float[6]; + + int n = 0; + for (; !itA.isDone() && !itB.isDone(); itA.next(), itB.next(), n++) { + int typeA = itA.currentSegment(coordsA); + int typeB = itB.currentSegment(coordsB); + + if (typeA != typeB) { + throw new IllegalStateException("Path-segment[" + n + "] " + + " type are not equals [" + typeA + "|" + typeB + "] !"); + } + if (!equalsArray(coordsA, coordsB, getLength(typeA))) { + throw new IllegalStateException("Path-segment[" + n + "] coords" + + " are not equals [" + Arrays.toString(coordsA) + "|" + + Arrays.toString(coordsB) + "] !"); + } + } + if (!itA.isDone() || !itB.isDone()) { + throw new IllegalStateException("Paths do not have same lengths !"); + } + log("testEqual: " + n + " segments."); + } + + static void testIterator(Path2D pathA, Path2D pathB) { + final PathIterator itA = pathA.getPathIterator(at); + final PathIterator itB = pathB.getPathIterator(at); + + float[] coordsA = new float[6]; + float[] coordsB = new float[6]; + + int n = 0; + for (; !itA.isDone() && !itB.isDone(); itA.next(), itB.next(), n++) { + int typeA = itA.currentSegment(coordsA); + int typeB = itB.currentSegment(coordsB); + + if (typeA != typeB) { + throw new IllegalStateException("Path-segment[" + n + "] " + + "type are not equals [" + typeA + "|" + typeB + "] !"); + } + // Take care of floating-point precision: + if (!equalsArrayEps(coordsA, coordsB, getLength(typeA))) { + throw new IllegalStateException("Path-segment[" + n + "] coords" + + " are not equals [" + Arrays.toString(coordsA) + "|" + + Arrays.toString(coordsB) + "] !"); + } + } + if (!itA.isDone() || !itB.isDone()) { + throw new IllegalStateException("Paths do not have same lengths !"); + } + log("testIterator: " + n + " segments."); + } + + static void testFlattening(Path2D pathA, Path2D pathB) { + final PathIterator itA = pathA.getPathIterator(at, FLATNESS); + final PathIterator itB = pathB.getPathIterator(at, FLATNESS); + + float[] coordsA = new float[6]; + float[] coordsB = new float[6]; + + int n = 0; + for (; !itA.isDone() && !itB.isDone(); itA.next(), itB.next(), n++) { + int typeA = itA.currentSegment(coordsA); + int typeB = itB.currentSegment(coordsB); + + if (typeA != typeB) { + throw new IllegalStateException("Path-segment[" + n + "] " + + "type are not equals [" + typeA + "|" + typeB + "] !"); + } + // Take care of floating-point precision: + if (!equalsArrayEps(coordsA, coordsB, getLength(typeA))) { + throw new IllegalStateException("Path-segment[" + n + "] coords" + + " are not equals [" + Arrays.toString(coordsA) + "|" + + Arrays.toString(coordsB) + "] !"); + } + } + if (!itA.isDone() || !itB.isDone()) { + throw new IllegalStateException("Paths do not have same lengths !"); + } + log("testFlattening: " + n + " segments."); + } + + static void testAddMove(Path2D pathA) { + addMove(pathA); + log("testAddMove: passed."); + } + + static void testAddLine(Path2D pathA, boolean isEmpty) { + try { + addLines(pathA); + } + catch (IllegalPathStateException ipse) { + if (isEmpty) { + log("testAddLine: passed " + + "(expected IllegalPathStateException catched)."); + return; + } else { + throw ipse; + } + } + if (isEmpty) { + throw new IllegalStateException("IllegalPathStateException not thrown !"); + } + log("testAddLine: passed."); + } + + static void testAddQuad(Path2D pathA, boolean isEmpty) { + try { + addQuads(pathA); + } + catch (IllegalPathStateException ipse) { + if (isEmpty) { + log("testAddQuad: passed " + + "(expected IllegalPathStateException catched)."); + return; + } else { + throw ipse; + } + } + if (isEmpty) { + throw new IllegalStateException("IllegalPathStateException not thrown !"); + } + log("testAddQuad: passed."); + } + + static void testAddCubic(Path2D pathA, boolean isEmpty) { + try { + addCubics(pathA); + } + catch (IllegalPathStateException ipse) { + if (isEmpty) { + log("testAddCubic: passed " + + "(expected IllegalPathStateException catched)."); + return; + } else { + throw ipse; + } + } + if (isEmpty) { + throw new IllegalStateException("IllegalPathStateException not thrown !"); + } + log("testAddCubic: passed."); + } + + static void testAddClose(Path2D pathA, boolean isEmpty) { + try { + addClose(pathA); + } + catch (IllegalPathStateException ipse) { + if (isEmpty) { + log("testAddClose: passed " + + "(expected IllegalPathStateException catched)."); + return; + } else { + throw ipse; + } + } + if (isEmpty) { + throw new IllegalStateException("IllegalPathStateException not thrown !"); + } + log("testAddClose: passed."); + } + + static void testGetBounds(Path2D pathA, Path2D pathB) { + final Rectangle rA = pathA.getBounds(); + final Rectangle rB = pathB.getBounds(); + + if (!rA.equals(rB)) { + throw new IllegalStateException("Bounds are not equals [" + rA + + "|" + rB + "] !"); + } + final Rectangle2D r2dA = pathA.getBounds2D(); + final Rectangle2D r2dB = pathB.getBounds2D(); + + if (!equalsRectangle2D(r2dA, r2dB)) { + throw new IllegalStateException("Bounds2D are not equals [" + + r2dA + "|" + r2dB + "] !"); + } + log("testGetBounds: passed."); + } + + static void testTransform(Path2D pathA) { + pathA.transform(at); + log("testTransform: passed."); + } + + static void testIntersect(Path2D pathA, Path2D pathB) { + boolean resA = pathA.intersects(rect2d); + boolean resB = pathB.intersects(rect2d); + if (resA != resB) { + throw new IllegalStateException("Intersects(rect2d) are not equals [" + + resA + "|" + resB + "] !"); + } + resA = pathA.intersects(1.0, 2.0, 13.0, 17.0); + resB = pathB.intersects(1.0, 2.0, 13.0, 17.0); + if (resA != resB) { + throw new IllegalStateException("Intersects(doubles) are not equals [" + + resA + "|" + resB + "] !"); + } + log("testIntersect: passed."); + } + + static void testContains(Path2D pathA, Path2D pathB) { + boolean resA = pathA.contains(pt2d); + boolean resB = pathB.contains(pt2d); + if (resA != resB) { + throw new IllegalStateException("Contains(pt) are not equals [" + + resA + "|" + resB + "] !"); + } + resA = pathA.contains(pt2d.getX(), pt2d.getY()); + resB = pathB.contains(pt2d.getX(), pt2d.getY()); + if (resA != resB) { + throw new IllegalStateException("Contains(x,y) are not equals [" + + resA + "|" + resB + "] !"); + } + resA = pathA.contains(rect2d); + resB = pathB.contains(rect2d); + if (resA != resB) { + throw new IllegalStateException("Contains(rect2d) are not equals [" + + resA + "|" + resB + "] !"); + } + resA = pathA.contains(1.0, 2.0, 13.0, 17.0); + resB = pathB.contains(1.0, 2.0, 13.0, 17.0); + if (resA != resB) { + throw new IllegalStateException("Contains(doubles) are not equals [" + + resA + "|" + resB + "] !"); + } + log("testContains: passed."); + } + + static void testGetCurrentPoint(Path2D pathA, Path2D pathB) { + final Point2D ptA = pathA.getCurrentPoint(); + final Point2D ptB = pathA.getCurrentPoint(); + if (((ptA == null) && (ptB != null)) + || ((ptA != null) && !ptA.equals(ptB))) + { + throw new IllegalStateException("getCurrentPoint() are not equals [" + + ptA + "|" + ptB + "] !"); + } + log("testGetCurrentPoint: passed."); + } + + static int getLength(int type) { + switch(type) { + case PathIterator.SEG_CUBICTO: + return 6; + case PathIterator.SEG_QUADTO: + return 4; + case PathIterator.SEG_LINETO: + case PathIterator.SEG_MOVETO: + return 2; + case PathIterator.SEG_CLOSE: + return 0; + default: + throw new IllegalStateException("Invalid type: " + type); + } + } + + + // Custom equals methods --- + + public static boolean equalsArray(float[] a, float[] a2, final int len) { + for (int i = 0; i < len; i++) { + if (Float.floatToIntBits(a[i]) != Float.floatToIntBits(a2[i])) { + return false; + } + } + return true; + } + + static boolean equalsArrayEps(float[] a, float[] a2, final int len) { + for (int i = 0; i < len; i++) { + if (!equalsEps(a[i], a2[i])) { + return false; + } + } + + return true; + } + + static boolean equalsRectangle2D(Rectangle2D a, Rectangle2D b) { + if (a == b) { + return true; + } + return equalsEps(a.getX(), b.getX()) + && equalsEps(a.getY(), b.getY()) + && equalsEps(a.getWidth(), b.getWidth()) + && equalsEps(a.getHeight(), b.getHeight()); + } + + static boolean equalsEps(float a, float b) { + return (Math.abs(a - b) <= EPSILON); + } + + static boolean equalsEps(double a, double b) { + return (Math.abs(a - b) <= EPSILON); + } +} diff --git a/jdk/test/java/awt/keyboard/EqualKeyCode/EqualKeyCode.java b/jdk/test/java/awt/keyboard/EqualKeyCode/EqualKeyCode.java index d4acc95ef2b..9f8598c14b7 100644 --- a/jdk/test/java/awt/keyboard/EqualKeyCode/EqualKeyCode.java +++ b/jdk/test/java/awt/keyboard/EqualKeyCode/EqualKeyCode.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,18 +24,14 @@ /* @test @bug 6799551 - @library ../../regtesthelpers - @build Util Sysout @summary Extended key codes for small letters undefined @author Andrei Dmitriev: area=awt.keyboard @run main EqualKeyCode */ -import sun.awt.*; import java.awt.*; -import test.java.awt.regtesthelpers.Util; -import test.java.awt.regtesthelpers.Sysout; +import java.awt.event.KeyEvent; public class EqualKeyCode { @@ -46,13 +42,13 @@ public class EqualKeyCode { char cSmall = LETTERS.charAt(i); char cLarge = Character.toUpperCase(cSmall); - int iSmall = ExtendedKeyCodes.getExtendedKeyCodeForChar(cSmall); - int iLarge = ExtendedKeyCodes.getExtendedKeyCodeForChar(cLarge); + int iSmall = KeyEvent.getExtendedKeyCodeForChar(cSmall); + int iLarge = KeyEvent.getExtendedKeyCodeForChar(cLarge); System.out.print(" " + cSmall + ":" + iSmall + " ---- "); System.out.println(" " + cLarge + " : " + iLarge); - if (ExtendedKeyCodes.getExtendedKeyCodeForChar(cSmall) != - ExtendedKeyCodes.getExtendedKeyCodeForChar(cLarge)) + if (KeyEvent.getExtendedKeyCodeForChar(cSmall) != + KeyEvent.getExtendedKeyCodeForChar(cLarge)) { throw new RuntimeException("ExtendedKeyCode doesn't exist or doesn't match between capital and small letters."); } diff --git a/jdk/test/java/beans/SimpleBeanInfo/LoadingStandardIcons/LoadingStandardIcons.java b/jdk/test/java/beans/SimpleBeanInfo/LoadingStandardIcons/LoadingStandardIcons.java new file mode 100644 index 00000000000..9b96bd2f668 --- /dev/null +++ b/jdk/test/java/beans/SimpleBeanInfo/LoadingStandardIcons/LoadingStandardIcons.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Image; +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; + +import javax.swing.JButton; + +/** + * @test + * @bug 4141523 + * @run main/othervm/policy=java.policy -Djava.security.manager LoadingStandardIcons + */ +public final class LoadingStandardIcons { + + public static void main(final String[] args) { + final Object bi; + try { + bi = Introspector.getBeanInfo(JButton.class); + } catch (IntrospectionException e) { + throw new RuntimeException(e); + } + final Image m16 = ((BeanInfo) bi).getIcon(BeanInfo.ICON_MONO_16x16); + final Image m32 = ((BeanInfo) bi).getIcon(BeanInfo.ICON_MONO_32x32); + final Image c16 = ((BeanInfo) bi).getIcon(BeanInfo.ICON_COLOR_16x16); + final Image c32 = ((BeanInfo) bi).getIcon(BeanInfo.ICON_COLOR_32x32); + if (m16 == null || m32 == null || c16 == null || c32 == null) { + throw new RuntimeException("Image should not be null"); + } + } +} diff --git a/jdk/test/java/beans/SimpleBeanInfo/LoadingStandardIcons/java.policy b/jdk/test/java/beans/SimpleBeanInfo/LoadingStandardIcons/java.policy new file mode 100644 index 00000000000..1c8a0e79762 --- /dev/null +++ b/jdk/test/java/beans/SimpleBeanInfo/LoadingStandardIcons/java.policy @@ -0,0 +1 @@ +; \ No newline at end of file diff --git a/jdk/test/java/io/DataInputStream/ReadUTF.java b/jdk/test/java/io/DataInputStream/ReadUTF.java index 16f346499e1..02c0f75efd4 100644 --- a/jdk/test/java/io/DataInputStream/ReadUTF.java +++ b/jdk/test/java/io/DataInputStream/ReadUTF.java @@ -24,6 +24,7 @@ /* @test * @bug 4806007 * @summary Checks for vague exceptions from writeUTF/readUTF + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/io/File/GetXSpace.java b/jdk/test/java/io/File/GetXSpace.java index e9aed50bbed..726a205d295 100644 --- a/jdk/test/java/io/File/GetXSpace.java +++ b/jdk/test/java/io/File/GetXSpace.java @@ -28,6 +28,7 @@ * @run build GetXSpace * @run shell GetXSpace.sh * @summary Basic functionality of File.get-X-Space methods. + * @key randomness */ import java.io.BufferedReader; diff --git a/jdk/test/java/io/InputStream/TransferTo.java b/jdk/test/java/io/InputStream/TransferTo.java index a32df7a62a3..50d8569caf9 100644 --- a/jdk/test/java/io/InputStream/TransferTo.java +++ b/jdk/test/java/io/InputStream/TransferTo.java @@ -37,6 +37,7 @@ import static java.lang.String.format; * @bug 8066867 * @summary tests whether java.io.InputStream.transferTo conforms to its * contract defined in the javadoc + * @key randomness */ public class TransferTo { diff --git a/jdk/test/java/io/PrintStream/OversynchronizedTest.java b/jdk/test/java/io/PrintStream/OversynchronizedTest.java index 1f687f8cab6..c5ac2bb2b80 100644 --- a/jdk/test/java/io/PrintStream/OversynchronizedTest.java +++ b/jdk/test/java/io/PrintStream/OversynchronizedTest.java @@ -24,6 +24,7 @@ /* @test @bug 4905777 @summary PrintStream.println(Object) oversynchronized, can deadlock + @key randomness */ import java.io.PrintStream; diff --git a/jdk/test/java/io/Serializable/corruptedUTFConsumption/CorruptedUTFConsumption.java b/jdk/test/java/io/Serializable/corruptedUTFConsumption/CorruptedUTFConsumption.java index 0071b8d3acf..3cae0268be3 100644 --- a/jdk/test/java/io/Serializable/corruptedUTFConsumption/CorruptedUTFConsumption.java +++ b/jdk/test/java/io/Serializable/corruptedUTFConsumption/CorruptedUTFConsumption.java @@ -28,6 +28,7 @@ * ObjectInputStream consumes at most the expected number of utf * bytes, even if the last byte(s) of the utf string indicate that the * string overflows its expected length. + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/io/Serializable/longString/LongString.java b/jdk/test/java/io/Serializable/longString/LongString.java index 3e1b4c3129f..6fbf3e340c8 100644 --- a/jdk/test/java/io/Serializable/longString/LongString.java +++ b/jdk/test/java/io/Serializable/longString/LongString.java @@ -25,6 +25,7 @@ * @bug 4217676 * @summary Ensure that object streams support serialization of long strings * (strings whose UTF representation > 64k in length) + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/io/Serializable/proxy/Basic.java b/jdk/test/java/io/Serializable/proxy/Basic.java index 402f797b139..3519334710b 100644 --- a/jdk/test/java/io/Serializable/proxy/Basic.java +++ b/jdk/test/java/io/Serializable/proxy/Basic.java @@ -23,6 +23,7 @@ /* @test * @summary Verifies basic correct functioning of proxy serialization. + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/io/Serializable/sanityCheck/SanityCheck.java b/jdk/test/java/io/Serializable/sanityCheck/SanityCheck.java index 486f55b547b..e2659868fe8 100644 --- a/jdk/test/java/io/Serializable/sanityCheck/SanityCheck.java +++ b/jdk/test/java/io/Serializable/sanityCheck/SanityCheck.java @@ -24,6 +24,7 @@ /* @test * @summary Basic sanity check to test if default (de)serialization is * transmitting values properly. + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/lang/Boolean/MakeBooleanComparable.java b/jdk/test/java/lang/Boolean/MakeBooleanComparable.java index 900900a2c5d..81478209c85 100644 --- a/jdk/test/java/lang/Boolean/MakeBooleanComparable.java +++ b/jdk/test/java/lang/Boolean/MakeBooleanComparable.java @@ -26,6 +26,7 @@ * @bug 4329937 * @summary Basic test for making Boolean implement Comparable * @author Josh Bloch + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/lang/ClassLoader/Assert.java b/jdk/test/java/lang/ClassLoader/Assert.java index 2abe45ac156..fb2376d45d4 100644 --- a/jdk/test/java/lang/ClassLoader/Assert.java +++ b/jdk/test/java/lang/ClassLoader/Assert.java @@ -28,6 +28,7 @@ * @run main/othervm Assert * @summary Test the assertion facility * @author Mike McCloskey + * @key randomness */ import package1.*; diff --git a/jdk/test/java/lang/Compare.java b/jdk/test/java/lang/Compare.java index c037f76fd3c..eba0ae93c1e 100644 --- a/jdk/test/java/lang/Compare.java +++ b/jdk/test/java/lang/Compare.java @@ -25,6 +25,7 @@ * @test * @bug 6582946 * @summary Test the primitive wrappers compare and compareTo methods + * @key randomness */ import java.util.Random; diff --git a/jdk/test/java/lang/Double/ParseHexFloatingPoint.java b/jdk/test/java/lang/Double/ParseHexFloatingPoint.java index b99ae5de1c1..0c70e02eca6 100644 --- a/jdk/test/java/lang/Double/ParseHexFloatingPoint.java +++ b/jdk/test/java/lang/Double/ParseHexFloatingPoint.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * 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,14 +23,15 @@ /* * @test - * @bug 4826774 - * @summary Numerical tests for hexadecimal inputs to parseDouble, parseFloat + * @library /lib/testlibrary/ + * @build jdk.testlibrary.* + * @run main ParseHexFloatingPoint + * @bug 4826774 8078672 + * @summary Numerical tests for hexadecimal inputs to parse{Double, Float} (use -Dseed=X to set PRNG seed) * @author Joseph D. Darcy + * @key randomness */ - -import java.util.regex.*; - public class ParseHexFloatingPoint { private ParseHexFloatingPoint(){} @@ -255,7 +256,7 @@ public class ParseHexFloatingPoint { failures += significandAlignmentTests(); { - java.util.Random rand = new java.util.Random(); + java.util.Random rand = RandomFactory.getRandom(); // Consistency check; double => hexadecimal => double // preserves the original value. for(int i = 0; i < 1000; i++) { diff --git a/jdk/test/java/lang/Enum/ValueOf.java b/jdk/test/java/lang/Enum/ValueOf.java index d01b9083ae5..711819653df 100644 --- a/jdk/test/java/lang/Enum/ValueOf.java +++ b/jdk/test/java/lang/Enum/ValueOf.java @@ -29,6 +29,7 @@ * * @compile ValueOf.java * @run main ValueOf + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/lang/HashCode.java b/jdk/test/java/lang/HashCode.java index d113cb0d0fd..5f1d03f491a 100644 --- a/jdk/test/java/lang/HashCode.java +++ b/jdk/test/java/lang/HashCode.java @@ -25,6 +25,7 @@ * @test * @bug 4245470 7088913 * @summary Test the primitive wrappers hashCode() + * @key randomness */ import java.util.Objects; diff --git a/jdk/test/java/lang/Integer/BitTwiddle.java b/jdk/test/java/lang/Integer/BitTwiddle.java index 6926facb5a4..95104df08ef 100644 --- a/jdk/test/java/lang/Integer/BitTwiddle.java +++ b/jdk/test/java/lang/Integer/BitTwiddle.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * 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,9 +23,13 @@ /* * @test - * @bug 4495754 - * @summary Basic test for int bit twiddling + * @library /lib/testlibrary/ + * @build jdk.testlibrary.* + * @run main BitTwiddle + * @bug 4495754 8078672 + * @summary Basic test for int bit twiddling (use -Dseed=X to set PRNG seed) * @author Josh Bloch + * @key randomness */ import java.util.Random; @@ -35,7 +39,7 @@ public class BitTwiddle { private static final int N = 1000; // # of repetitions per test public static void main(String args[]) { - Random rnd = new Random(); + Random rnd = RandomFactory.getRandom(); if (highestOneBit(0) != 0) throw new RuntimeException("a"); diff --git a/jdk/test/java/lang/Long/BitTwiddle.java b/jdk/test/java/lang/Long/BitTwiddle.java index 5a34ccec3ec..9dacbc7579f 100644 --- a/jdk/test/java/lang/Long/BitTwiddle.java +++ b/jdk/test/java/lang/Long/BitTwiddle.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * 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,9 +23,13 @@ /* * @test - * @bug 4495754 - * @summary Basic test for long bit twiddling + * @library /lib/testlibrary/ + * @build jdk.testlibrary.* + * @run main BitTwiddle + * @bug 4495754 8078672 + * @summary Basic test for long bit twiddling (use -Dseed=X to set PRNG seed) * @author Josh Bloch + * @key randomness */ import java.util.Random; @@ -35,7 +39,7 @@ public class BitTwiddle { private static final int N = 1000; // # of repetitions per test public static void main(String args[]) { - Random rnd = new Random(); + Random rnd = RandomFactory.getRandom(); if (highestOneBit(0) != 0) throw new RuntimeException("a"); diff --git a/jdk/test/java/lang/Math/CubeRootTests.java b/jdk/test/java/lang/Math/CubeRootTests.java index 116a7f4d4a7..956949f8ca4 100644 --- a/jdk/test/java/lang/Math/CubeRootTests.java +++ b/jdk/test/java/lang/Math/CubeRootTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * 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,9 +23,13 @@ /* * @test - * @bug 4347132 4939441 - * @summary Tests for {Math, StrictMath}.cbrt + * @library /lib/testlibrary/ + * @build jdk.testlibrary.* + * @run main CubeRootTests + * @bug 4347132 4939441 8078672 + * @summary Tests for {Math, StrictMath}.cbrt (use -Dseed=X to set PRNG seed) * @author Joseph D. Darcy + * @key randomness */ public class CubeRootTests { @@ -35,7 +39,7 @@ public class CubeRootTests { static final double NaNd = Double.NaN; // Initialize shared random number generator - static java.util.Random rand = new java.util.Random(); + static java.util.Random rand = RandomFactory.getRandom(); static int testCubeRootCase(double input, double expected) { int failures=0; diff --git a/jdk/test/java/lang/Math/HypotTests.java b/jdk/test/java/lang/Math/HypotTests.java index 1c1ff8c4d5d..21fa0b51736 100644 --- a/jdk/test/java/lang/Math/HypotTests.java +++ b/jdk/test/java/lang/Math/HypotTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * 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,9 +23,13 @@ /* * @test - * @bug 4851638 4939441 - * @summary Tests for {Math, StrictMath}.hypot + * @library /lib/testlibrary/ + * @build jdk.testlibrary.* + * @run main HypotTests + * @bug 4851638 4939441 8078672 + * @summary Tests for {Math, StrictMath}.hypot (use -Dseed=X to set PRNG seed) * @author Joseph D. Darcy + * @key randomness */ public class HypotTests { @@ -119,7 +123,7 @@ public class HypotTests { * exponent). While the exponent of r is less than or equal * to (MAX_EXPONENT - 3), the computation should not overflow. */ - java.util.Random rand = new java.util.Random(); + java.util.Random rand = RandomFactory.getRandom(); for(int i = 0; i < 1000; i++) { double d = rand.nextDouble(); // Scale d to have an exponent equal to MAX_EXPONENT -15 diff --git a/jdk/test/java/lang/Math/IeeeRecommendedTests.java b/jdk/test/java/lang/Math/IeeeRecommendedTests.java index d1d28245850..e9e276044f0 100644 --- a/jdk/test/java/lang/Math/IeeeRecommendedTests.java +++ b/jdk/test/java/lang/Math/IeeeRecommendedTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * 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,9 +23,13 @@ /* * @test - * @bug 4860891 4826732 4780454 4939441 4826652 - * @summary Tests for IEEE 754[R] recommended functions and similar methods + * @library /lib/testlibrary/ + * @build jdk.testlibrary.* + * @run main IeeeRecommendedTests + * @bug 4860891 4826732 4780454 4939441 4826652 8078672 + * @summary Tests for IEEE 754[R] recommended functions and similar methods (use -Dseed=X to set PRNG seed) * @author Joseph D. Darcy + * @key randomness */ public class IeeeRecommendedTests { @@ -45,7 +49,7 @@ public class IeeeRecommendedTests { static final double Double_MAX_SUBNORMALmm = 0x0.ffffffffffffeP-1022; // Initialize shared random number generator - static java.util.Random rand = new java.util.Random(); + static java.util.Random rand = RandomFactory.getRandom(); /** * Returns a floating-point power of two in the normal range. diff --git a/jdk/test/java/lang/Math/Log1pTests.java b/jdk/test/java/lang/Math/Log1pTests.java index eb4e8800224..445b0e3dfdc 100644 --- a/jdk/test/java/lang/Math/Log1pTests.java +++ b/jdk/test/java/lang/Math/Log1pTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * 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,9 +23,13 @@ /* * @test - * @bug 4851638 4939441 - * @summary Tests for {Math, StrictMath}.log1p + * @library /lib/testlibrary/ + * @build jdk.testlibrary.* + * @run main Log1pTests + * @bug 4851638 4939441 8078672 + * @summary Tests for {Math, StrictMath}.log1p (use -Dseed=X to set PRNG seed) * @author Joseph D. Darcy + * @key randomness */ public class Log1pTests { @@ -98,7 +102,7 @@ public class Log1pTests { // Construct random values with exponents ranging from -53 to // 52 and compare against HP-15C formula. - java.util.Random rand = new java.util.Random(); + java.util.Random rand = RandomFactory.getRandom(); for(int i = 0; i < 1000; i++) { double d = rand.nextDouble(); diff --git a/jdk/test/java/lang/ProcessBuilder/Basic.java b/jdk/test/java/lang/ProcessBuilder/Basic.java index cfc4d443ff8..93855f19bcb 100644 --- a/jdk/test/java/lang/ProcessBuilder/Basic.java +++ b/jdk/test/java/lang/ProcessBuilder/Basic.java @@ -27,6 +27,7 @@ * 5026830 5023243 5070673 4052517 4811767 6192449 6397034 6413313 * 6464154 6523983 6206031 4960438 6631352 6631966 6850957 6850958 * 4947220 7018606 7034570 4244896 5049299 8003488 8054494 8058464 + * 8067796 * @summary Basic tests for Process and Environment Variable code * @run main/othervm/timeout=300 Basic * @run main/othervm/timeout=300 -Djdk.lang.Process.launchMechanism=fork Basic @@ -2386,6 +2387,56 @@ public class Basic { p.destroy(); } catch (Throwable t) { unexpected(t); } + //---------------------------------------------------------------- + // Check that Process.waitFor(timeout, null) throws NPE. + //---------------------------------------------------------------- + try { + List childArgs = new ArrayList(javaChildArgs); + childArgs.add("sleep"); + final Process p = new ProcessBuilder(childArgs).start(); + THROWS(NullPointerException.class, + () -> p.waitFor(10L, null)); + THROWS(NullPointerException.class, + () -> p.waitFor(0L, null)); + THROWS(NullPointerException.class, + () -> p.waitFor(-1L, null)); + // Terminate process and recheck after it exits + p.destroy(); + p.waitFor(); + THROWS(NullPointerException.class, + () -> p.waitFor(10L, null)); + THROWS(NullPointerException.class, + () -> p.waitFor(0L, null)); + THROWS(NullPointerException.class, + () -> p.waitFor(-1L, null)); + } catch (Throwable t) { unexpected(t); } + + //---------------------------------------------------------------- + // Check that default implementation of Process.waitFor(timeout, null) throws NPE. + //---------------------------------------------------------------- + try { + List childArgs = new ArrayList(javaChildArgs); + childArgs.add("sleep"); + final Process proc = new ProcessBuilder(childArgs).start(); + final DelegatingProcess p = new DelegatingProcess(proc); + + THROWS(NullPointerException.class, + () -> p.waitFor(10L, null)); + THROWS(NullPointerException.class, + () -> p.waitFor(0L, null)); + THROWS(NullPointerException.class, + () -> p.waitFor(-1L, null)); + // Terminate process and recheck after it exits + p.destroy(); + p.waitFor(); + THROWS(NullPointerException.class, + () -> p.waitFor(10L, null)); + THROWS(NullPointerException.class, + () -> p.waitFor(0L, null)); + THROWS(NullPointerException.class, + () -> p.waitFor(-1L, null)); + } catch (Throwable t) { unexpected(t); } + //---------------------------------------------------------------- // Check the default implementation for // Process.waitFor(long, TimeUnit) diff --git a/jdk/test/java/lang/Runtime/exec/LotsOfOutput.java b/jdk/test/java/lang/Runtime/exec/LotsOfOutput.java index 2f8e594f2b6..b75f8e89eb1 100644 --- a/jdk/test/java/lang/Runtime/exec/LotsOfOutput.java +++ b/jdk/test/java/lang/Runtime/exec/LotsOfOutput.java @@ -41,7 +41,12 @@ public class LotsOfOutput { long initMemory = Runtime.getRuntime().totalMemory(); for (int i=1; i< 10; i++) { Thread.sleep(100); - if (Runtime.getRuntime().totalMemory() > initMemory + 1000000) + long totalMemory = Runtime.getRuntime().totalMemory(); + if (totalMemory != initMemory) { + System.out.printf("consuming memory: i: %d, initial: %d, total: %d, delta: %d%n", + i, initMemory, totalMemory, totalMemory - initMemory); + } + if (totalMemory > initMemory + 1000000) throw new Exception("Process consumes memory."); } diff --git a/jdk/test/java/lang/Runtime/exec/WinCommand.java b/jdk/test/java/lang/Runtime/exec/WinCommand.java index 1504c891eab..0d4c256393a 100644 --- a/jdk/test/java/lang/Runtime/exec/WinCommand.java +++ b/jdk/test/java/lang/Runtime/exec/WinCommand.java @@ -25,6 +25,7 @@ * @bug 5006520 * @summary Check many different ways to run Windows programs * @author Martin Buchholz + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/lang/String/ContentEquals.java b/jdk/test/java/lang/String/ContentEquals.java index 2231b71d0c7..eb46f58abab 100644 --- a/jdk/test/java/lang/String/ContentEquals.java +++ b/jdk/test/java/lang/String/ContentEquals.java @@ -25,6 +25,7 @@ * @test * @bug 4242309 4982981 * @summary Test equals and contentEquals in String + * @key randomness */ import java.util.Random; import java.nio.CharBuffer; diff --git a/jdk/test/java/lang/String/ICCBasher.java b/jdk/test/java/lang/String/ICCBasher.java index ed9a780629c..33cb1a2d7ee 100644 --- a/jdk/test/java/lang/String/ICCBasher.java +++ b/jdk/test/java/lang/String/ICCBasher.java @@ -25,6 +25,7 @@ * @test * @bug 4152868 * @summary test Case Insensitive Comparator in String + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/lang/String/SBConstructor.java b/jdk/test/java/lang/String/SBConstructor.java index 7566fea4379..0b38ed0c54e 100644 --- a/jdk/test/java/lang/String/SBConstructor.java +++ b/jdk/test/java/lang/String/SBConstructor.java @@ -25,7 +25,7 @@ * @test * @bug 4915187 * @summary Test java.lang.String constructor that takes StringBuilder - * + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/lang/String/Split.java b/jdk/test/java/lang/String/Split.java index a70213a61ca..d95a26a56bc 100644 --- a/jdk/test/java/lang/String/Split.java +++ b/jdk/test/java/lang/String/Split.java @@ -25,6 +25,7 @@ * @test * @bug 6840246 6559590 * @summary test String.split() + * @key randomness */ import java.util.Arrays; import java.util.Random; diff --git a/jdk/test/java/lang/StringBuffer/AppendCharSequence.java b/jdk/test/java/lang/StringBuffer/AppendCharSequence.java index b7738ac68d1..e6012ca2718 100644 --- a/jdk/test/java/lang/StringBuffer/AppendCharSequence.java +++ b/jdk/test/java/lang/StringBuffer/AppendCharSequence.java @@ -24,6 +24,7 @@ /* @test * @bug 4812591 4705328 5019111 * @summary Test append and insert methods with CharSequence params + * @key randomness */ import java.util.Random; diff --git a/jdk/test/java/lang/StringBuffer/AppendSB.java b/jdk/test/java/lang/StringBuffer/AppendSB.java index f1bcc475074..2ecc37903a1 100644 --- a/jdk/test/java/lang/StringBuffer/AppendSB.java +++ b/jdk/test/java/lang/StringBuffer/AppendSB.java @@ -24,6 +24,7 @@ /* @test * @bug 4144267 * @summary Test StringBuffer.append(StringBuffer); + * @key randomness */ import java.util.Random; diff --git a/jdk/test/java/lang/StringBuffer/AppendStringBuilder.java b/jdk/test/java/lang/StringBuffer/AppendStringBuilder.java index a27f6a12a28..fed81ac253b 100644 --- a/jdk/test/java/lang/StringBuffer/AppendStringBuilder.java +++ b/jdk/test/java/lang/StringBuffer/AppendStringBuilder.java @@ -23,6 +23,7 @@ /* @test * @bug 6206780 * @summary Test StringBuffer.append(StringBuilder); + * @key randomness */ import java.util.Random; diff --git a/jdk/test/java/lang/StringBuffer/Capacity.java b/jdk/test/java/lang/StringBuffer/Capacity.java index 4d2bc83445a..937ad8f9a76 100644 --- a/jdk/test/java/lang/StringBuffer/Capacity.java +++ b/jdk/test/java/lang/StringBuffer/Capacity.java @@ -25,6 +25,7 @@ * @test * @bug 6952330 * @summary Test StringBuffer/StringBuilder capacity handling. + * @key randomness */ import java.util.Random; diff --git a/jdk/test/java/lang/StringBuffer/IndexOf.java b/jdk/test/java/lang/StringBuffer/IndexOf.java index f5741d80ed8..aceb25265b7 100644 --- a/jdk/test/java/lang/StringBuffer/IndexOf.java +++ b/jdk/test/java/lang/StringBuffer/IndexOf.java @@ -24,6 +24,7 @@ /* @test * @bug 4162796 4162796 * @summary Test indexOf and lastIndexOf + * @key randomness */ import java.util.Random; diff --git a/jdk/test/java/lang/StringBuffer/SBBasher.java b/jdk/test/java/lang/StringBuffer/SBBasher.java index 9155f3b99c0..4cc6be46fb0 100644 --- a/jdk/test/java/lang/StringBuffer/SBBasher.java +++ b/jdk/test/java/lang/StringBuffer/SBBasher.java @@ -25,7 +25,7 @@ * @test * @bug 4120694 * @summary Test new methods in StringBuffer - * + * @key randomness */ import java.lang.*; diff --git a/jdk/test/java/lang/StringBuffer/Trim.java b/jdk/test/java/lang/StringBuffer/Trim.java index 3d1cc6acd91..d44720d9d45 100644 --- a/jdk/test/java/lang/StringBuffer/Trim.java +++ b/jdk/test/java/lang/StringBuffer/Trim.java @@ -24,6 +24,7 @@ /* @test * @bug 4546734 5007612 * @summary Test StringBuffer.trimToSize + * @key randomness */ import java.util.Random; diff --git a/jdk/test/java/lang/StringBuilder/AppendStringBuffer.java b/jdk/test/java/lang/StringBuilder/AppendStringBuffer.java index a54cf0a0d29..3cb1de55a84 100644 --- a/jdk/test/java/lang/StringBuilder/AppendStringBuffer.java +++ b/jdk/test/java/lang/StringBuilder/AppendStringBuffer.java @@ -24,6 +24,7 @@ /* @test * @bug 6206780 * @summary Test StringBuilder.append(StringBuffer); + * @key randomness */ import java.util.Random; diff --git a/jdk/test/java/lang/ToString.java b/jdk/test/java/lang/ToString.java index 3d90dd0c69c..181a4ec44d6 100644 --- a/jdk/test/java/lang/ToString.java +++ b/jdk/test/java/lang/ToString.java @@ -25,6 +25,7 @@ * @test * @bug 4031762 * @summary Test the primitive wrappers static toString() + * @key randomness */ import java.util.Random; diff --git a/jdk/test/java/lang/instrument/SingleTransformerTest.java b/jdk/test/java/lang/instrument/SingleTransformerTest.java index bcbf04d8a97..d04adf1b266 100644 --- a/jdk/test/java/lang/instrument/SingleTransformerTest.java +++ b/jdk/test/java/lang/instrument/SingleTransformerTest.java @@ -30,6 +30,7 @@ * @run build SingleTransformerTest * @run shell MakeJAR.sh redefineAgent * @run main/othervm -javaagent:redefineAgent.jar SingleTransformerTest SingleTransformerTest + * @key randomness */ public class SingleTransformerTest diff --git a/jdk/test/java/lang/instrument/TransformMethodTest.java b/jdk/test/java/lang/instrument/TransformMethodTest.java index 38e48d5288f..610729f1185 100644 --- a/jdk/test/java/lang/instrument/TransformMethodTest.java +++ b/jdk/test/java/lang/instrument/TransformMethodTest.java @@ -30,6 +30,7 @@ * @run build TransformMethodTest * @run shell MakeJAR.sh redefineAgent * @run main/othervm -javaagent:redefineAgent.jar TransformMethodTest TransformMethodTest + * @key randomness */ import java.lang.instrument.*; diff --git a/jdk/test/java/lang/invoke/MethodHandles/CatchExceptionTest.java b/jdk/test/java/lang/invoke/MethodHandles/CatchExceptionTest.java index 44e11e0985d..1d3cbeb64d1 100644 --- a/jdk/test/java/lang/invoke/MethodHandles/CatchExceptionTest.java +++ b/jdk/test/java/lang/invoke/MethodHandles/CatchExceptionTest.java @@ -41,7 +41,7 @@ import java.util.concurrent.TimeUnit; * @library /lib/testlibrary/jsr292 /lib/testlibrary/ * @compile CatchExceptionTest.java * @run main/othervm -esa test.java.lang.invoke.MethodHandles.CatchExceptionTest - * @key intermittent + * @key intermittent randomness */ public class CatchExceptionTest { private static final List> ARGS_CLASSES; diff --git a/jdk/test/java/lang/management/BufferPoolMXBean/Basic.java b/jdk/test/java/lang/management/BufferPoolMXBean/Basic.java index 6bdd96a2fa8..180551fdd26 100644 --- a/jdk/test/java/lang/management/BufferPoolMXBean/Basic.java +++ b/jdk/test/java/lang/management/BufferPoolMXBean/Basic.java @@ -25,6 +25,7 @@ * @bug 6606598 7024172 * @summary Unit test for java.lang.management.BufferPoolMXBean * @run main/othervm Basic + * @key randomness */ import java.nio.ByteBuffer; diff --git a/jdk/test/java/math/BigDecimal/StringConstructor.java b/jdk/test/java/math/BigDecimal/StringConstructor.java index c8051eb98a5..fde327dd075 100644 --- a/jdk/test/java/math/BigDecimal/StringConstructor.java +++ b/jdk/test/java/math/BigDecimal/StringConstructor.java @@ -23,20 +23,20 @@ /* * @test - * @library .. - * @bug 4103117 4331084 4488017 4490929 6255285 6268365 8074460 + * @library /lib/testlibrary/ + * @build jdk.testlibrary.* + * @run main StringConstructor + * @bug 4103117 4331084 4488017 4490929 6255285 6268365 8074460 8078672 * @summary Tests the BigDecimal string constructor (use -Dseed=X to set PRNG seed). + * @key randomness */ import java.math.*; +import java.util.Random; public class StringConstructor { - private static RandomSeed rndSeed = new RandomSeed(false); - public static void main(String[] args) throws Exception { - System.out.println("Random number generator seed = " + rndSeed.getSeed()); - constructWithError(""); constructWithError("+"); constructWithError("-"); @@ -71,13 +71,14 @@ public class StringConstructor { nonAsciiZeroTest(); // Roundtrip tests + Random random = RandomFactory.getRandom(); for (int i=0; i<100; i++) { - int size = rndSeed.getRandom().nextInt(100) + 1; - BigInteger bi = new BigInteger(size, rndSeed.getRandom()); - if (rndSeed.getRandom().nextBoolean()) + int size = random.nextInt(100) + 1; + BigInteger bi = new BigInteger(size, random); + if (random.nextBoolean()) bi = bi.negate(); int decimalLength = bi.toString().length(); - int scale = rndSeed.getRandom().nextInt(decimalLength); + int scale = random.nextInt(decimalLength); BigDecimal bd = new BigDecimal(bi, scale); String bdString = bd.toString(); // System.err.println("bi" + bi.toString() + "\tscale " + scale); diff --git a/jdk/test/java/math/BigInteger/BigIntegerTest.java b/jdk/test/java/math/BigInteger/BigIntegerTest.java index e1b36c0812b..687d06e70e9 100644 --- a/jdk/test/java/math/BigInteger/BigIntegerTest.java +++ b/jdk/test/java/math/BigInteger/BigIntegerTest.java @@ -23,11 +23,14 @@ /* * @test - * @library .. - * @bug 4181191 4161971 4227146 4194389 4823171 4624738 4812225 4837946 4026465 8074460 + * @library /lib/testlibrary/ + * @build jdk.testlibrary.* + * @run main BigIntegerTest + * @bug 4181191 4161971 4227146 4194389 4823171 4624738 4812225 4837946 4026465 8074460 8078672 * @summary tests methods in BigInteger (use -Dseed=X to set PRNG seed) * @run main/timeout=400 BigIntegerTest * @author madbot + * @key randomness */ import java.io.File; @@ -36,6 +39,7 @@ import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; +import java.util.Random; /** * This is a simple test class created to ensure that the results @@ -86,7 +90,7 @@ public class BigIntegerTest { static final int SIZE = 1000; // numbers per batch - private static RandomSeed rndSeed = new RandomSeed(false); + private static Random random = RandomFactory.getRandom(); static boolean failure = false; @@ -98,7 +102,7 @@ public class BigIntegerTest { int arrayLength = 23; int halfLength = arrayLength/2; byte[] array = new byte[arrayLength]; - rndSeed.getRandom().nextBytes(array); + random.nextBytes(array); int[][] offLen = new int[][] { // offset, length, num exceptions {-1, arrayLength, 1}, // negative offset @@ -162,7 +166,7 @@ public class BigIntegerTest { } byte[] magNonZeroLength = new byte[42]; - rndSeed.getRandom().nextBytes(magNonZeroLength); + random.nextBytes(magNonZeroLength); for (int signum = -1; signum <= 1; signum++) { BigInteger bi = new BigInteger(signum, magNonZeroLength, 0, 0); if (bi.compareTo(BigInteger.ZERO) != 0) { @@ -175,13 +179,13 @@ public class BigIntegerTest { for (int i = 0; i < SIZE; i++) { // create reference value via a different code path from those tested - BigInteger reference = new BigInteger(2 + rndSeed.getRandom().nextInt(336), 4, rndSeed.getRandom()); + BigInteger reference = new BigInteger(2 + random.nextInt(336), 4, random); byte[] refArray = reference.toByteArray(); int refLen = refArray.length; - int factor = rndSeed.getRandom().nextInt(5); - int objLen = refArray.length + factor*rndSeed.getRandom().nextInt(refArray.length) + 1; - int offset = rndSeed.getRandom().nextInt(objLen - refLen); + int factor = random.nextInt(5); + int objLen = refArray.length + factor*random.nextInt(refArray.length) + 1; + int offset = random.nextInt(objLen - refLen); byte[] objArray = new byte[objLen]; System.arraycopy(refArray, 0, objArray, offset, refLen); @@ -192,7 +196,7 @@ public class BigIntegerTest { failCount++; } - boolean isNegative = rndSeed.getRandom().nextBoolean(); + boolean isNegative = random.nextBoolean(); BigInteger signMag = new BigInteger(isNegative ? -1 : 1, objArray, offset, refLen); if (signMag.compareTo(isNegative ? reference.negate() : reference) != 0) { System.err.println("Sign-magnitude BigInteger not equal for offset " + @@ -209,7 +213,7 @@ public class BigIntegerTest { for (int i=0; i= lower; bits--) { for (int i = 0; i < 50; i++) { - BigInteger x = BigInteger.ONE.shiftLeft(bits - 1).or(new BigInteger(bits - 2, rndSeed.getRandom())); + BigInteger x = BigInteger.ONE.shiftLeft(bits - 1).or(new BigInteger(bits - 2, random)); for (int radix = Character.MIN_RADIX; radix < Character.MAX_RADIX; radix++) { String result = x.toString(radix); @@ -765,9 +769,9 @@ public class BigIntegerTest { int failCount = 0; for (int i=0; i<10; i++) { - BigInteger m = new BigInteger(100, 5, rndSeed.getRandom()); + BigInteger m = new BigInteger(100, 5, random); while(m.compareTo(BigInteger.ONE) != 1) - m = new BigInteger(100, 5, rndSeed.getRandom()); + m = new BigInteger(100, 5, random); BigInteger exp = m.subtract(BigInteger.ONE); BigInteger base = fetchNumber(order).abs(); while(base.compareTo(m) != -1) @@ -827,7 +831,7 @@ public class BigIntegerTest { // Test consistency for(int i=0; i<10; i++) { - p1 = BigInteger.probablePrime(100, rndSeed.getRandom()); + p1 = BigInteger.probablePrime(100, random); if (!p1.isProbablePrime(100)) { System.err.println("Consistency "+p1.toString(16)); failCount++; @@ -868,7 +872,7 @@ public class BigIntegerTest { // Numbers of the form (6k+1)(12k+1)(18k+1) are Carmichael numbers if // each of the factors is prime int found = 0; - BigInteger f1 = new BigInteger(40, 100, rndSeed.getRandom()); + BigInteger f1 = new BigInteger(40, 100, random); while (found < NUM_CARMICHAELS_TO_TEST) { BigInteger k = null; BigInteger f2, f3; @@ -895,8 +899,8 @@ public class BigIntegerTest { // Test some composites that are products of 2 primes for (int i=0; i<50; i++) { - p1 = BigInteger.probablePrime(100, rndSeed.getRandom()); - p2 = BigInteger.probablePrime(100, rndSeed.getRandom()); + p1 = BigInteger.probablePrime(100, random); + p2 = BigInteger.probablePrime(100, random); c1 = p1.multiply(p2); if (c1.isProbablePrime(100)) { System.err.println("Composite failed "+c1.toString(16)); @@ -905,8 +909,8 @@ public class BigIntegerTest { } for (int i=0; i<4; i++) { - p1 = BigInteger.probablePrime(600, rndSeed.getRandom()); - p2 = BigInteger.probablePrime(600, rndSeed.getRandom()); + p1 = BigInteger.probablePrime(600, random); + p2 = BigInteger.probablePrime(600, random); c1 = p1.multiply(p2); if (c1.isProbablePrime(100)) { System.err.println("Composite failed "+c1.toString(16)); @@ -961,7 +965,7 @@ public class BigIntegerTest { // Next, pick some large primes, use nextProbablePrime to find the // next one, and make sure there are no primes in between for (int i=0; i<100; i+=10) { - p1 = BigInteger.probablePrime(50 + i, rndSeed.getRandom()); + p1 = BigInteger.probablePrime(50 + i, random); p2 = p1.add(ONE); p3 = p1.nextProbablePrime(); while(p2.compareTo(p3) < 0) { @@ -1026,7 +1030,7 @@ public class BigIntegerTest { } for(int i=0; i<10; i++) { - BigInteger b1 = fetchNumber(rndSeed.getRandom().nextInt(100)); + BigInteger b1 = fetchNumber(random.nextInt(100)); BigInteger b2 = null; File f = new File("serialtest"); try (FileOutputStream fos = new FileOutputStream(f)) { @@ -1060,8 +1064,6 @@ public class BigIntegerTest { * */ public static void main(String[] args) throws Exception { - System.out.println("Random number generator seed = " + rndSeed.getSeed()); - // Some variables for sizing test numbers in bits int order1 = ORDER_MEDIUM; int order2 = ORDER_SMALL; @@ -1133,8 +1135,8 @@ public class BigIntegerTest { * If order is less than 2, order is changed to 2. */ private static BigInteger fetchNumber(int order) { - boolean negative = rndSeed.getRandom().nextBoolean(); - int numType = rndSeed.getRandom().nextInt(7); + boolean negative = random.nextBoolean(); + int numType = random.nextInt(7); BigInteger result = null; if (order < 2) order = 2; @@ -1158,14 +1160,14 @@ public class BigIntegerTest { break; case 3: // One bit in number - result = BigInteger.ONE.shiftLeft(rndSeed.getRandom().nextInt(order)); + result = BigInteger.ONE.shiftLeft(random.nextInt(order)); break; case 4: // Random bit density byte[] val = new byte[(order+7)/8]; - int iterations = rndSeed.getRandom().nextInt(order); + int iterations = random.nextInt(order); for (int i=0; i 0) { - int runLength = Math.min(remaining, rndSeed.getRandom().nextInt(order)); + int runLength = Math.min(remaining, random.nextInt(order)); result = result.shiftLeft(runLength); if (bit > 0) result = result.add(ONE.shiftLeft(runLength).subtract(ONE)); @@ -1185,7 +1187,7 @@ public class BigIntegerTest { break; default: // random bits - result = new BigInteger(order, rndSeed.getRandom()); + result = new BigInteger(order, random); } if (negative) diff --git a/jdk/test/java/math/BigInteger/ModPow65537.java b/jdk/test/java/math/BigInteger/ModPow65537.java index f8e4a5422d1..7d9607acd3f 100644 --- a/jdk/test/java/math/BigInteger/ModPow65537.java +++ b/jdk/test/java/math/BigInteger/ModPow65537.java @@ -23,16 +23,20 @@ /* * @test - * @library .. - * @bug 4891312 8074460 + * @library /lib/testlibrary/ + * @build jdk.testlibrary.* + * @run main ModPow65537 + * @bug 4891312 8074460 8078672 * @summary verify that modPow() not broken by the special case for 65537 (use -Dseed=X to set PRNG seed) * @author Andreas Sterbenz + * @key randomness */ import java.math.BigInteger; import java.security.*; import java.security.spec.*; +import java.util.Random; public class ModPow65537 { @@ -78,9 +82,8 @@ public class ModPow65537 { private static void testSigning(KeyPair kp) throws Exception { System.out.println(kp.getPublic()); byte[] data = new byte[1024]; - RandomSeed rndSeed = new RandomSeed(false); - System.out.println("Random number generator seed = " + rndSeed.getSeed()); - rndSeed.getRandom().nextBytes(data); + Random random = RandomFactory.getRandom(); + random.nextBytes(data); Signature sig = Signature.getInstance("SHA1withRSA", "SunRsaSign"); sig.initSign(kp.getPrivate()); diff --git a/jdk/test/java/math/BigInteger/PrimeTest.java b/jdk/test/java/math/BigInteger/PrimeTest.java index fae4fd7979b..bb3d3494a0d 100644 --- a/jdk/test/java/math/BigInteger/PrimeTest.java +++ b/jdk/test/java/math/BigInteger/PrimeTest.java @@ -25,10 +25,13 @@ /* * @test - * @library .. - * @bug 8026236 8074460 + * @library /lib/testlibrary/ + * @build jdk.testlibrary.* + * @run main PrimeTest + * @bug 8026236 8074460 8078672 * @summary test primality verification methods in BigInteger (use -Dseed=X to set PRNG seed) * @author bpb + * @key randomness */ import java.math.BigInteger; import java.util.BitSet; @@ -178,9 +181,8 @@ public class PrimeTest { } // Create a list of non-prime BigIntegers. - RandomSeed rndSeed = new RandomSeed(true); - System.out.println("Random number generator seed = " + rndSeed.getSeed()); - List nonPrimeBigInts = (rndSeed.getSplittableRandom()) + SplittableRandom splitRandom = RandomFactory.getSplittableRandom(); + List nonPrimeBigInts = (splitRandom) .ints(NUM_NON_PRIMES, 2, maxPrime).mapToObj(BigInteger::valueOf) .filter(b -> !b.isProbablePrime(certainty)).collect(toList()); diff --git a/jdk/test/java/math/BigInteger/SymmetricRangeTests.java b/jdk/test/java/math/BigInteger/SymmetricRangeTests.java index d3cb73cbef2..6565ff23b67 100644 --- a/jdk/test/java/math/BigInteger/SymmetricRangeTests.java +++ b/jdk/test/java/math/BigInteger/SymmetricRangeTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 1025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,11 +24,13 @@ /* * @test * @ignore This test has huge memory requirements - * @library .. + * @library /lib/testlibrary/ + * @build jdk.testlibrary.* * @run main/timeout=180/othervm -Xmx8g SymmetricRangeTests - * @bug 6910473 8021204 8021203 9005933 8074460 + * @bug 6910473 8021204 8021203 9005933 8074460 8078672 * @summary Test range of BigInteger values (use -Dseed=X to set PRNG seed) * @author Dmitry Nadezhin + * @key randomness */ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -37,6 +39,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.math.BigInteger; +import java.util.Random; public class SymmetricRangeTests { @@ -114,9 +117,8 @@ public class SymmetricRangeTests { System.out.println("Testing overflow in BitSieve.sieveSingle"); int bitLength = (5 << 27) - 1; try { - RandomSeed rndSeed = new RandomSeed(false); - System.out.println("Random number generator seed = " + rndSeed.getSeed()); - BigInteger actual = new BigInteger(bitLength, 0, rndSeed.getRandom()); + Random random = RandomFactory.getRandom(); + BigInteger actual = new BigInteger(bitLength, 0, random); throw new RuntimeException("new BigInteger(bitLength, 0, null).bitLength()=" + actual.bitLength()); } catch (ArithmeticException e) { // expected diff --git a/jdk/test/java/math/RandomSeed.java b/jdk/test/java/math/RandomSeed.java deleted file mode 100644 index 494705c5fd6..00000000000 --- a/jdk/test/java/math/RandomSeed.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.util.Random; -import java.util.SplittableRandom; - -public class RandomSeed { - private long seed = 0L; - private Random rnd = null; - private SplittableRandom srnd = null; - - public RandomSeed(boolean isSplittableRandom) { - init(isSplittableRandom); - } - - private void init(boolean isSplittableRandom) { - // obtain seed from environment if supplied - boolean isSeedProvided = false; - try { - // note that Long.valueOf(null) also throws a NumberFormatException - // so if the property is undefined this will still work correctly - seed = Long.valueOf(System.getProperty("seed")); - isSeedProvided = true; - } catch (NumberFormatException e) { - // do nothing: isSeedProvided is already false - } - - // if no seed from environment, create a fresh one - Random tmpRnd = null; - if (!isSeedProvided) { - tmpRnd = new Random(); - seed = tmpRnd.nextLong(); - } - - // create the PRNG - if (isSplittableRandom) { - srnd = new SplittableRandom(seed); - } else { - rnd = tmpRnd != null ? tmpRnd : new Random(); - rnd.setSeed(seed); - } - } - - public Random getRandom() { - if (rnd == null) { - throw new IllegalStateException("Variable of type Random not initialized"); - } - return rnd; - } - - public SplittableRandom getSplittableRandom() { - if (srnd == null) { - throw new IllegalStateException("Variable of type SplittableRandom not initialized"); - } - return srnd; - } - - public long getSeed() { - return seed; - } -} diff --git a/jdk/test/java/net/InetAddress/HashSpread.java b/jdk/test/java/net/InetAddress/HashSpread.java index 17f59438470..990eb531bd7 100644 --- a/jdk/test/java/net/InetAddress/HashSpread.java +++ b/jdk/test/java/net/InetAddress/HashSpread.java @@ -26,6 +26,7 @@ * @bug 4687909 * @summary Check Inet6Address.hashCode returns a reasonable spread of hash * codes. + * @key randomness */ import java.net.InetAddress; import java.net.UnknownHostException; diff --git a/jdk/test/java/net/URL/HandlersPkgPrefix/HandlersPkgPrefix.java b/jdk/test/java/net/URL/HandlersPkgPrefix/HandlersPkgPrefix.java new file mode 100644 index 00000000000..83b06ccd621 --- /dev/null +++ b/jdk/test/java/net/URL/HandlersPkgPrefix/HandlersPkgPrefix.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.function.Consumer; + +/* + * @test + * @bug 8075139 + * @summary Basic test for java.protocol.handler.pkgs + * @compile handlers/foo/Handler.java handlers/bar/Handler.java HandlersPkgPrefix.java + * @run main/othervm HandlersPkgPrefix + */ + +public class HandlersPkgPrefix { + static final Consumer KNOWN = r -> { + if (r.exception != null) + throw new RuntimeException("Unexpected exception " + r.exception); + String p = r.url.getProtocol(); + if (!r.protocol.equals(p)) + throw new RuntimeException("Expected:" + r.protocol + ", got:" + p); + }; + static final Consumer UNKNOWN = r -> { + if (r.url != null) + throw new RuntimeException("Unexpected url:" + r.url); + if (!(r.exception instanceof MalformedURLException)) + throw new RuntimeException("Expected MalformedURLException, got:" + + r.exception); + }; + + public static void main(String[] args) { + withPrefix("unknown", "", UNKNOWN); + withPrefix("unknown", "handlers", UNKNOWN); + + withPrefix("foo", "", UNKNOWN); + withPrefix("foo", "xxx|yyy|zzz", UNKNOWN); + withPrefix("foo", "||||", UNKNOWN); + withPrefix("foo", "|a|b|c|handlers", KNOWN); + + withPrefix("bar", "", UNKNOWN); + withPrefix("bar", "x.y.z|y.y.y|z.z.z", UNKNOWN); + withPrefix("bar", " x.y.z | y.y.y | z.z.z| | ", UNKNOWN); + withPrefix("bar", "| a | b | c | handlers | d | e", KNOWN); + } + + static void withPrefix(String protocol, String pkgPrefix, + Consumer resultChecker) { + System.out.println("Testing, " + protocol + ", " + pkgPrefix); + + // The long standing implementation behavior is that the + // property is read multiple times, not cached. + System.setProperty("java.protocol.handler.pkgs", pkgPrefix); + URL url = null; + Exception exception = null; + try { + url = new URL(protocol + "://"); + } catch (MalformedURLException x) { + exception = x; + } + resultChecker.accept(new Result(protocol, url, exception)); + } + + static class Result { + final String protocol; + final URL url; + final Exception exception; + Result(String protocol, URL url, Exception exception) { + this.protocol = protocol; + this.url = url; + this.exception = exception; + } + } +} + diff --git a/jdk/test/jdk/lambda/shapegen/Rule.java b/jdk/test/java/net/URL/HandlersPkgPrefix/handlers/bar/Handler.java similarity index 72% rename from jdk/test/jdk/lambda/shapegen/Rule.java rename to jdk/test/java/net/URL/HandlersPkgPrefix/handlers/bar/Handler.java index 7ff02e050ed..c94e9288ebc 100644 --- a/jdk/test/jdk/lambda/shapegen/Rule.java +++ b/jdk/test/java/net/URL/HandlersPkgPrefix/handlers/bar/Handler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,26 +21,17 @@ * questions. */ -package shapegen; +package handlers.bar; -/** - * - * @author Robert Field - */ -public abstract class Rule { - - public final String name; - - public Rule(String name) { - this.name = name; - } - - abstract boolean guard(ClassCase cc); - - abstract void eval(ClassCase cc); +import java.io.IOException; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; +public class Handler extends URLStreamHandler { @Override - public String toString() { - return name; + protected URLConnection openConnection(URL u) throws IOException { + return null; } } + diff --git a/jdk/test/java/net/URL/HandlersPkgPrefix/handlers/foo/Handler.java b/jdk/test/java/net/URL/HandlersPkgPrefix/handlers/foo/Handler.java new file mode 100644 index 00000000000..21bde96c13a --- /dev/null +++ b/jdk/test/java/net/URL/HandlersPkgPrefix/handlers/foo/Handler.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 handlers.foo; + +import java.io.IOException; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; + +public class Handler extends URLStreamHandler { + @Override + protected URLConnection openConnection(URL u) throws IOException { + return null; + } +} + diff --git a/jdk/test/java/nio/Buffer/Chars.java b/jdk/test/java/nio/Buffer/Chars.java index ef2df66ac14..01b53ea2405 100644 --- a/jdk/test/java/nio/Buffer/Chars.java +++ b/jdk/test/java/nio/Buffer/Chars.java @@ -26,6 +26,7 @@ * @bug 8014854 * @summary Exercises CharBuffer#chars on each of the CharBuffer types * @run testng Chars + * @key randomness */ import java.nio.ByteBuffer; diff --git a/jdk/test/java/nio/Buffer/genBasic.sh b/jdk/test/java/nio/Buffer/genBasic.sh index df271b948cd..1090476807c 100644 --- a/jdk/test/java/nio/Buffer/genBasic.sh +++ b/jdk/test/java/nio/Buffer/genBasic.sh @@ -1,7 +1,7 @@ #! /bin/sh # -# Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ # questions. # -javac -d . ../../../../make/tools/src/build/tools/spp/Spp.java +javac -d . ../../../../make/src/classes/build/tools/spp/Spp.java gen() { java build.tools.spp.Spp -K$1 -Dtype=$1 -DType=$2 -DFulltype=$3 Basic$2.java diff --git a/jdk/test/java/nio/Buffer/genCopyDirectMemory.sh b/jdk/test/java/nio/Buffer/genCopyDirectMemory.sh index b6c2421b13e..64c51e52904 100644 --- a/jdk/test/java/nio/Buffer/genCopyDirectMemory.sh +++ b/jdk/test/java/nio/Buffer/genCopyDirectMemory.sh @@ -1,7 +1,7 @@ #! /bin/sh # -# Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ # questions. # -javac -d . ../../../../make/tools/src/build/tools/spp/Spp.java > Spp.java +javac -d . ../../../../make/src/classes/build/tools/spp/Spp.java > Spp.java gen() { java build.tools.spp.Spp -K$1 -Dtype=$1 -DType=$2 -DFulltype=$3CopyDirect$2Memory.java diff --git a/jdk/test/java/nio/MappedByteBuffer/Force.java b/jdk/test/java/nio/MappedByteBuffer/Force.java index 52717642c94..f9ae0810bce 100644 --- a/jdk/test/java/nio/MappedByteBuffer/Force.java +++ b/jdk/test/java/nio/MappedByteBuffer/Force.java @@ -25,6 +25,7 @@ * @bug 4625907 * @summary Testing force() * @run main/othervm Force + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/MappedByteBuffer/ZeroMap.java b/jdk/test/java/nio/MappedByteBuffer/ZeroMap.java index 7c00bf72750..f28e1eb8963 100644 --- a/jdk/test/java/nio/MappedByteBuffer/ZeroMap.java +++ b/jdk/test/java/nio/MappedByteBuffer/ZeroMap.java @@ -25,6 +25,7 @@ * @bug 4802340 * @summary Testing force(), load() isLoaded() of zero len MBB * @run main/othervm ZeroMap + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/AsynchronousChannelGroup/Basic.java b/jdk/test/java/nio/channels/AsynchronousChannelGroup/Basic.java index 1c5da1309b3..0a62be8fc57 100644 --- a/jdk/test/java/nio/channels/AsynchronousChannelGroup/Basic.java +++ b/jdk/test/java/nio/channels/AsynchronousChannelGroup/Basic.java @@ -24,6 +24,7 @@ /* @test * @bug 4607272 * @summary Unit test for AsynchronousChannelGroup + * @key randomness */ import java.nio.ByteBuffer; diff --git a/jdk/test/java/nio/channels/AsynchronousChannelGroup/Identity.java b/jdk/test/java/nio/channels/AsynchronousChannelGroup/Identity.java index 366449bfc32..654d5f92183 100644 --- a/jdk/test/java/nio/channels/AsynchronousChannelGroup/Identity.java +++ b/jdk/test/java/nio/channels/AsynchronousChannelGroup/Identity.java @@ -24,6 +24,7 @@ /* @test * @bug 4607272 6842687 * @summary Unit test for AsynchronousChannelGroup + * @key randomness */ import java.nio.ByteBuffer; diff --git a/jdk/test/java/nio/channels/AsynchronousChannelGroup/Restart.java b/jdk/test/java/nio/channels/AsynchronousChannelGroup/Restart.java index 456f66a2eee..4d364017f0e 100644 --- a/jdk/test/java/nio/channels/AsynchronousChannelGroup/Restart.java +++ b/jdk/test/java/nio/channels/AsynchronousChannelGroup/Restart.java @@ -24,6 +24,7 @@ /* @test * @bug 4607272 6842687 * @summary Unit test for AsynchronousChannelGroup + * @key randomness */ import java.nio.channels.*; diff --git a/jdk/test/java/nio/channels/AsynchronousFileChannel/Basic.java b/jdk/test/java/nio/channels/AsynchronousFileChannel/Basic.java index 10f51c978ca..55de744c0db 100644 --- a/jdk/test/java/nio/channels/AsynchronousFileChannel/Basic.java +++ b/jdk/test/java/nio/channels/AsynchronousFileChannel/Basic.java @@ -24,6 +24,7 @@ /* @test * @bug 4607272 6822643 6830721 6842687 * @summary Unit test for AsynchronousFileChannel + * @key randomness */ import java.nio.file.*; diff --git a/jdk/test/java/nio/channels/AsynchronousFileChannel/Lock.java b/jdk/test/java/nio/channels/AsynchronousFileChannel/Lock.java index a7f2c7bb0cb..13a094e7d25 100644 --- a/jdk/test/java/nio/channels/AsynchronousFileChannel/Lock.java +++ b/jdk/test/java/nio/channels/AsynchronousFileChannel/Lock.java @@ -25,6 +25,7 @@ /* @test * @bug 4607272 6814948 6842687 * @summary Unit test for AsynchronousFileChannel#lock method + * @key randomness */ import java.net.*; diff --git a/jdk/test/java/nio/channels/AsynchronousFileChannel/LotsOfWrites.java b/jdk/test/java/nio/channels/AsynchronousFileChannel/LotsOfWrites.java index 02453e57f26..9c2d5ec3f6b 100644 --- a/jdk/test/java/nio/channels/AsynchronousFileChannel/LotsOfWrites.java +++ b/jdk/test/java/nio/channels/AsynchronousFileChannel/LotsOfWrites.java @@ -24,6 +24,7 @@ /* @test * @bug 6913877 * @summary Stress AsynchronousFileChannel.write + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/AsynchronousSocketChannel/Basic.java b/jdk/test/java/nio/channels/AsynchronousSocketChannel/Basic.java index 8f9e426a740..23d9eb36e4e 100644 --- a/jdk/test/java/nio/channels/AsynchronousSocketChannel/Basic.java +++ b/jdk/test/java/nio/channels/AsynchronousSocketChannel/Basic.java @@ -25,7 +25,7 @@ * @bug 4607272 6842687 6878369 6944810 7023403 * @summary Unit test for AsynchronousSocketChannel * @run main Basic -skipSlowConnectTest - * @key intermittent + * @key randomness */ import java.nio.ByteBuffer; diff --git a/jdk/test/java/nio/channels/AsynchronousSocketChannel/StressLoopback.java b/jdk/test/java/nio/channels/AsynchronousSocketChannel/StressLoopback.java index 4627aaa2a5a..8f8f816cad6 100644 --- a/jdk/test/java/nio/channels/AsynchronousSocketChannel/StressLoopback.java +++ b/jdk/test/java/nio/channels/AsynchronousSocketChannel/StressLoopback.java @@ -26,6 +26,7 @@ * @summary Stress test connections through the loopback interface * @run main StressLoopback * @run main/othervm -Djdk.net.useFastTcpLoopback StressLoopback + * @key randomness */ import java.nio.ByteBuffer; diff --git a/jdk/test/java/nio/channels/Channels/Basic2.java b/jdk/test/java/nio/channels/Channels/Basic2.java index 27a56c56bca..73acdf7b3c2 100644 --- a/jdk/test/java/nio/channels/Channels/Basic2.java +++ b/jdk/test/java/nio/channels/Channels/Basic2.java @@ -25,6 +25,7 @@ * @bug 4607272 * @summary Test Channels methods for interoperability between streams and * asynchronous byte channels + * @key randomness */ import java.net.*; diff --git a/jdk/test/java/nio/channels/Channels/ShortWrite.java b/jdk/test/java/nio/channels/Channels/ShortWrite.java index 82c8f7265d8..d39f69e4842 100644 --- a/jdk/test/java/nio/channels/Channels/ShortWrite.java +++ b/jdk/test/java/nio/channels/Channels/ShortWrite.java @@ -25,6 +25,7 @@ * @bug 6448457 * @summary Test Channels.newOutputStream returns OutputStream that handles * short writes from the underlying channel + * @key randomness */ import java.io.OutputStream; diff --git a/jdk/test/java/nio/channels/DatagramChannel/AdaptDatagramSocket.java b/jdk/test/java/nio/channels/DatagramChannel/AdaptDatagramSocket.java index 7937b56c59f..b8ec1c1060b 100644 --- a/jdk/test/java/nio/channels/DatagramChannel/AdaptDatagramSocket.java +++ b/jdk/test/java/nio/channels/DatagramChannel/AdaptDatagramSocket.java @@ -25,6 +25,7 @@ * @bug 4313882 4981129 * @summary Unit test for datagram-socket-channel adaptors * @library .. + * @key randomness */ import java.net.*; diff --git a/jdk/test/java/nio/channels/DatagramChannel/MulticastSendReceiveTests.java b/jdk/test/java/nio/channels/DatagramChannel/MulticastSendReceiveTests.java index 8f0f9a5fba3..db061a833fc 100644 --- a/jdk/test/java/nio/channels/DatagramChannel/MulticastSendReceiveTests.java +++ b/jdk/test/java/nio/channels/DatagramChannel/MulticastSendReceiveTests.java @@ -27,6 +27,7 @@ * @build MulticastSendReceiveTests NetworkConfiguration * @run main MulticastSendReceiveTests * @run main/othervm -Djava.net.preferIPv4Stack=true MulticastSendReceiveTests + * @key randomness */ import java.nio.ByteBuffer; @@ -97,7 +98,7 @@ public class MulticastSendReceiveTests { // no datagram received if (sa == null) { if (expectedSender != null) { - throw new RuntimeException("Expected message not recieved"); + throw new RuntimeException("Expected message not received"); } System.out.println("No message received (correct)"); return; @@ -109,10 +110,15 @@ public class MulticastSendReceiveTests { buf.flip(); byte[] bytes = new byte[buf.remaining()]; buf.get(bytes); - int receivedId = Integer.parseInt(new String(bytes)); - - System.out.format("Received message from %s (id=0x%x)\n", - sender, receivedId); + String s = new String(bytes, "UTF-8"); + int receivedId = -1; + try { + receivedId = Integer.parseInt(s); + System.out.format("Received message from %s (id=0x%x)\n", + sender, receivedId); + } catch (NumberFormatException x) { + System.out.format("Received message from %s (msg=%s)\n", sender, s); + } if (expectedSender == null) { if (receivedId == id) diff --git a/jdk/test/java/nio/channels/DatagramChannel/Promiscuous.java b/jdk/test/java/nio/channels/DatagramChannel/Promiscuous.java index 027b4b79eea..884baaf581a 100644 --- a/jdk/test/java/nio/channels/DatagramChannel/Promiscuous.java +++ b/jdk/test/java/nio/channels/DatagramChannel/Promiscuous.java @@ -28,6 +28,7 @@ * @build Promiscuous NetworkConfiguration * @run main Promiscuous * @run main/othervm -Djava.net.preferIPv4Stack=true Promiscuous + * @key randomness */ import java.nio.ByteBuffer; diff --git a/jdk/test/java/nio/channels/FileChannel/AtomicAppend.java b/jdk/test/java/nio/channels/FileChannel/AtomicAppend.java index 25f6b64924c..8e00c60bfd4 100644 --- a/jdk/test/java/nio/channels/FileChannel/AtomicAppend.java +++ b/jdk/test/java/nio/channels/FileChannel/AtomicAppend.java @@ -24,6 +24,7 @@ /* * @test * @summary Check that appends are atomic + * @key randomness */ import java.io.File; diff --git a/jdk/test/java/nio/channels/FileChannel/ClosedByInterrupt.java b/jdk/test/java/nio/channels/FileChannel/ClosedByInterrupt.java index 153a2ad451f..a14d111b6f0 100644 --- a/jdk/test/java/nio/channels/FileChannel/ClosedByInterrupt.java +++ b/jdk/test/java/nio/channels/FileChannel/ClosedByInterrupt.java @@ -25,6 +25,7 @@ * @bug 6979009 * @summary Ensure ClosedByInterruptException is thrown when I/O operation * interrupted by Thread.interrupt + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/FileChannel/MapTest.java b/jdk/test/java/nio/channels/FileChannel/MapTest.java index 066d6097389..f2bbb08680e 100644 --- a/jdk/test/java/nio/channels/FileChannel/MapTest.java +++ b/jdk/test/java/nio/channels/FileChannel/MapTest.java @@ -25,6 +25,7 @@ * @bug 4429043 8002180 * @summary Test file mapping with FileChannel * @run main/othervm MapTest + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/FileChannel/Position.java b/jdk/test/java/nio/channels/FileChannel/Position.java index cbb7dd9de6e..825ba628248 100644 --- a/jdk/test/java/nio/channels/FileChannel/Position.java +++ b/jdk/test/java/nio/channels/FileChannel/Position.java @@ -24,6 +24,7 @@ /* @test * @bug 4429043 6526860 * @summary Test position method of FileChannel + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/FileChannel/Pread.java b/jdk/test/java/nio/channels/FileChannel/Pread.java index fca93f97f3f..8e3dd026c94 100644 --- a/jdk/test/java/nio/channels/FileChannel/Pread.java +++ b/jdk/test/java/nio/channels/FileChannel/Pread.java @@ -24,6 +24,7 @@ /* @test * @bug 4862382 4862408 * @summary Test positional read method of FileChannel + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/FileChannel/Pwrite.java b/jdk/test/java/nio/channels/FileChannel/Pwrite.java index 21f1c298b63..94f7780328e 100644 --- a/jdk/test/java/nio/channels/FileChannel/Pwrite.java +++ b/jdk/test/java/nio/channels/FileChannel/Pwrite.java @@ -24,6 +24,7 @@ /* @test * @bug 4862411 * @summary Test positional write method of FileChannel + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/FileChannel/Size.java b/jdk/test/java/nio/channels/FileChannel/Size.java index 8a658e07b05..d06ba81fa51 100644 --- a/jdk/test/java/nio/channels/FileChannel/Size.java +++ b/jdk/test/java/nio/channels/FileChannel/Size.java @@ -25,6 +25,7 @@ * @bug 4563125 * @summary Test size method of FileChannel * @run main/othervm Size + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/FileChannel/Transfer.java b/jdk/test/java/nio/channels/FileChannel/Transfer.java index e9524be7b5f..04a0f3251b2 100644 --- a/jdk/test/java/nio/channels/FileChannel/Transfer.java +++ b/jdk/test/java/nio/channels/FileChannel/Transfer.java @@ -26,6 +26,7 @@ * 6984545 * @summary Test FileChannel.transferFrom and transferTo * @library .. + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/FileChannel/Truncate.java b/jdk/test/java/nio/channels/FileChannel/Truncate.java index ff62d724a98..38a020d7de8 100644 --- a/jdk/test/java/nio/channels/FileChannel/Truncate.java +++ b/jdk/test/java/nio/channels/FileChannel/Truncate.java @@ -24,6 +24,7 @@ /* @test * @bug 6191269 6709457 8000330 * @summary Test truncate method of FileChannel + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/Pipe/PipeChannel.java b/jdk/test/java/nio/channels/Pipe/PipeChannel.java index 0ec9aaed735..2aaa4f84f08 100644 --- a/jdk/test/java/nio/channels/Pipe/PipeChannel.java +++ b/jdk/test/java/nio/channels/Pipe/PipeChannel.java @@ -23,6 +23,7 @@ /* @test * @summary Test reading and writing from Pipes + * @key randomness */ import java.io.*; @@ -37,7 +38,7 @@ import java.util.Random; */ public class PipeChannel { - private static Random generator = new Random(); + private static Random generator = new Random(); public static void main(String[] args) throws Exception { for (int x=0; x<100; x++) { diff --git a/jdk/test/java/nio/channels/Pipe/ScatteringRead.java b/jdk/test/java/nio/channels/Pipe/ScatteringRead.java index 83b520ceda5..a2685eea55f 100644 --- a/jdk/test/java/nio/channels/Pipe/ScatteringRead.java +++ b/jdk/test/java/nio/channels/Pipe/ScatteringRead.java @@ -22,8 +22,9 @@ */ /* @test - @bug 4526754 + * @bug 4526754 * @summary Test Pipe scattering reads + * @key randomness */ import java.nio.channels.*; diff --git a/jdk/test/java/nio/channels/Pipe/SelectPipe.java b/jdk/test/java/nio/channels/Pipe/SelectPipe.java index 85938eb1789..f782ee3ae1f 100644 --- a/jdk/test/java/nio/channels/Pipe/SelectPipe.java +++ b/jdk/test/java/nio/channels/Pipe/SelectPipe.java @@ -23,6 +23,7 @@ /* @test * @summary Test selection of ready pipe + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/Selector/SelectorTest.java b/jdk/test/java/nio/channels/Selector/SelectorTest.java index 8e835d88e2b..bd17d001816 100644 --- a/jdk/test/java/nio/channels/Selector/SelectorTest.java +++ b/jdk/test/java/nio/channels/Selector/SelectorTest.java @@ -24,6 +24,7 @@ /* @test * @summary Test selectors and socketchannels * @library .. + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/Selector/Wakeup.java b/jdk/test/java/nio/channels/Selector/Wakeup.java index e51bd1d38fc..40aa71729c8 100644 --- a/jdk/test/java/nio/channels/Selector/Wakeup.java +++ b/jdk/test/java/nio/channels/Selector/Wakeup.java @@ -25,7 +25,6 @@ * @bug 6405995 * @summary Unit test for selector wakeup and interruption * @library .. - * @key intermittent */ import java.io.*; diff --git a/jdk/test/java/nio/channels/ServerSocketChannel/NonBlockingAccept.java b/jdk/test/java/nio/channels/ServerSocketChannel/NonBlockingAccept.java index 7a425ad88ed..1b985e8c68a 100644 --- a/jdk/test/java/nio/channels/ServerSocketChannel/NonBlockingAccept.java +++ b/jdk/test/java/nio/channels/ServerSocketChannel/NonBlockingAccept.java @@ -27,6 +27,7 @@ * @library .. * @build TestUtil * @run main NonBlockingAccept + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/SocketChannel/CloseDuringWrite.java b/jdk/test/java/nio/channels/SocketChannel/CloseDuringWrite.java index 83d05bfd96e..50b7dbb3747 100644 --- a/jdk/test/java/nio/channels/SocketChannel/CloseDuringWrite.java +++ b/jdk/test/java/nio/channels/SocketChannel/CloseDuringWrite.java @@ -23,6 +23,7 @@ /* @test * @summary Test asynchronous close during a blocking write + * @key randomness */ import java.io.Closeable; diff --git a/jdk/test/java/nio/channels/SocketChannel/OutOfBand.java b/jdk/test/java/nio/channels/SocketChannel/OutOfBand.java index 68b973dca89..cd46f9ee6a2 100644 --- a/jdk/test/java/nio/channels/SocketChannel/OutOfBand.java +++ b/jdk/test/java/nio/channels/SocketChannel/OutOfBand.java @@ -24,6 +24,7 @@ /* @test * @summary Test socket adapter sendUrgentData method * @bug 6963907 + * @key randomness */ import java.net.*; diff --git a/jdk/test/java/nio/channels/SocketChannel/ShortWrite.java b/jdk/test/java/nio/channels/SocketChannel/ShortWrite.java index 0988006800a..c1d7c33fc5d 100644 --- a/jdk/test/java/nio/channels/SocketChannel/ShortWrite.java +++ b/jdk/test/java/nio/channels/SocketChannel/ShortWrite.java @@ -24,6 +24,7 @@ /* @test * @bug 7176630 7074436 * @summary Check for short writes on SocketChannels configured in blocking mode + * @key randomness */ import java.net.*; diff --git a/jdk/test/java/nio/channels/SocketChannel/VectorIO.java b/jdk/test/java/nio/channels/SocketChannel/VectorIO.java index 84c5a7f59e8..d7975dbfa44 100644 --- a/jdk/test/java/nio/channels/SocketChannel/VectorIO.java +++ b/jdk/test/java/nio/channels/SocketChannel/VectorIO.java @@ -24,6 +24,7 @@ /* @test * @summary Test socketchannel vector IO * @library .. + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/channels/etc/AdaptorCloseAndInterrupt.java b/jdk/test/java/nio/channels/etc/AdaptorCloseAndInterrupt.java index 8d99fde7a41..292851873ca 100644 --- a/jdk/test/java/nio/channels/etc/AdaptorCloseAndInterrupt.java +++ b/jdk/test/java/nio/channels/etc/AdaptorCloseAndInterrupt.java @@ -24,6 +24,7 @@ /* @test * @bug 7184932 * @summary Test asynchronous close and interrupt of timed socket adapter methods + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/charset/coders/BashCache.java b/jdk/test/java/nio/charset/coders/BashCache.java index 2019af82393..2ded5c0ce07 100644 --- a/jdk/test/java/nio/charset/coders/BashCache.java +++ b/jdk/test/java/nio/charset/coders/BashCache.java @@ -24,6 +24,7 @@ /* @test * @bug 4517279 * @summary Stochastic test of thread-local coder caches + * @key randomness */ import java.nio.*; diff --git a/jdk/test/java/nio/charset/coders/BashStreams.java b/jdk/test/java/nio/charset/coders/BashStreams.java index 5781464aeee..15ea14c3ddf 100644 --- a/jdk/test/java/nio/charset/coders/BashStreams.java +++ b/jdk/test/java/nio/charset/coders/BashStreams.java @@ -23,6 +23,7 @@ /* @test * @summary Stochastic test of charset-based streams + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/nio/file/Files/BytesAndLines.java b/jdk/test/java/nio/file/Files/BytesAndLines.java index c3a1db74ce1..ca486ab87fc 100644 --- a/jdk/test/java/nio/file/Files/BytesAndLines.java +++ b/jdk/test/java/nio/file/Files/BytesAndLines.java @@ -27,6 +27,7 @@ * @run testng BytesAndLines * @summary Unit test for methods for Files readAllBytes, readAllLines and * and write methods. + * @key randomness */ import java.nio.ByteBuffer; diff --git a/jdk/test/java/nio/file/Files/CopyAndMove.java b/jdk/test/java/nio/file/Files/CopyAndMove.java index 4853b0dcdf4..38470cc810b 100644 --- a/jdk/test/java/nio/file/Files/CopyAndMove.java +++ b/jdk/test/java/nio/file/Files/CopyAndMove.java @@ -27,6 +27,7 @@ * @library .. * @build CopyAndMove PassThroughFileSystem * @run main/othervm CopyAndMove + * @key randomness */ import java.nio.ByteBuffer; diff --git a/jdk/test/java/nio/file/Files/InterruptCopy.java b/jdk/test/java/nio/file/Files/InterruptCopy.java index 29cfa006e40..c83479c9e46 100644 --- a/jdk/test/java/nio/file/Files/InterruptCopy.java +++ b/jdk/test/java/nio/file/Files/InterruptCopy.java @@ -25,7 +25,6 @@ * @bug 4313887 6993267 * @summary Unit test for Sun-specific ExtendedCopyOption.INTERRUPTIBLE option * @library .. - * @key intermittent */ import java.nio.file.*; diff --git a/jdk/test/java/nio/file/Files/walkFileTree/SkipSiblings.java b/jdk/test/java/nio/file/Files/walkFileTree/SkipSiblings.java index bcdc4e1256c..d7bbdd974bc 100644 --- a/jdk/test/java/nio/file/Files/walkFileTree/SkipSiblings.java +++ b/jdk/test/java/nio/file/Files/walkFileTree/SkipSiblings.java @@ -27,6 +27,7 @@ * @library ../.. * @compile SkipSiblings.java CreateFileTree.java * @run main SkipSiblings + * @key randomness */ import java.nio.file.*; diff --git a/jdk/test/java/nio/file/Files/walkFileTree/SkipSubtree.java b/jdk/test/java/nio/file/Files/walkFileTree/SkipSubtree.java index c5522839b5b..8a2eeb7d1ff 100644 --- a/jdk/test/java/nio/file/Files/walkFileTree/SkipSubtree.java +++ b/jdk/test/java/nio/file/Files/walkFileTree/SkipSubtree.java @@ -27,6 +27,7 @@ * @library ../.. * @compile SkipSubtree.java CreateFileTree.java * @run main SkipSubtree + * @key randomness */ import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; diff --git a/jdk/test/java/nio/file/Files/walkFileTree/TerminateWalk.java b/jdk/test/java/nio/file/Files/walkFileTree/TerminateWalk.java index a4b3cf724d5..445b7bfe33c 100644 --- a/jdk/test/java/nio/file/Files/walkFileTree/TerminateWalk.java +++ b/jdk/test/java/nio/file/Files/walkFileTree/TerminateWalk.java @@ -27,6 +27,7 @@ * @library ../.. * @compile TerminateWalk.java CreateFileTree.java * @run main TerminateWalk + * @key randomness */ import java.nio.file.*; diff --git a/jdk/test/java/nio/file/WatchService/LotsOfEvents.java b/jdk/test/java/nio/file/WatchService/LotsOfEvents.java index 64ab7aca65d..042dfd94146 100644 --- a/jdk/test/java/nio/file/WatchService/LotsOfEvents.java +++ b/jdk/test/java/nio/file/WatchService/LotsOfEvents.java @@ -26,6 +26,7 @@ * @summary Tests WatchService behavior when lots of events are pending * @library .. * @run main/timeout=180 LotsOfEvents + * @key randomness */ import java.nio.file.*; diff --git a/jdk/test/java/nio/file/WatchService/MayFlies.java b/jdk/test/java/nio/file/WatchService/MayFlies.java index ad0ed4c4131..3052ff6e695 100644 --- a/jdk/test/java/nio/file/WatchService/MayFlies.java +++ b/jdk/test/java/nio/file/WatchService/MayFlies.java @@ -27,6 +27,7 @@ * short lived files * @library .. * @run main MayFlies + * @key randomness */ import java.nio.file.*; diff --git a/jdk/test/java/nio/file/WatchService/SensitivityModifier.java b/jdk/test/java/nio/file/WatchService/SensitivityModifier.java index 4b7629db204..823539d1a23 100644 --- a/jdk/test/java/nio/file/WatchService/SensitivityModifier.java +++ b/jdk/test/java/nio/file/WatchService/SensitivityModifier.java @@ -26,6 +26,7 @@ * @summary Sanity test for Sun-specific sensitivity level watch event modifier * @library .. * @run main/timeout=240 SensitivityModifier + * @key randomness */ import java.nio.file.*; diff --git a/jdk/test/java/nio/file/attribute/AclFileAttributeView/Basic.java b/jdk/test/java/nio/file/attribute/AclFileAttributeView/Basic.java index aa613e22b78..00afd2cd1bf 100644 --- a/jdk/test/java/nio/file/attribute/AclFileAttributeView/Basic.java +++ b/jdk/test/java/nio/file/attribute/AclFileAttributeView/Basic.java @@ -25,6 +25,7 @@ * @bug 4313887 6838333 6891404 * @summary Unit test for java.nio.file.attribute.AclFileAttribueView * @library ../.. + * @key randomness */ import java.nio.file.*; diff --git a/jdk/test/java/nio/file/attribute/FileTime/Basic.java b/jdk/test/java/nio/file/attribute/FileTime/Basic.java index 8731ce77147..9e18d81d3db 100644 --- a/jdk/test/java/nio/file/attribute/FileTime/Basic.java +++ b/jdk/test/java/nio/file/attribute/FileTime/Basic.java @@ -24,6 +24,7 @@ /* @test * @bug 6844313 8011647 * @summary Unit test for java.nio.file.FileTime + * @key randomness */ diff --git a/jdk/test/java/nio/file/attribute/UserDefinedFileAttributeView/Basic.java b/jdk/test/java/nio/file/attribute/UserDefinedFileAttributeView/Basic.java index 69393a30a61..5f40d193cf0 100644 --- a/jdk/test/java/nio/file/attribute/UserDefinedFileAttributeView/Basic.java +++ b/jdk/test/java/nio/file/attribute/UserDefinedFileAttributeView/Basic.java @@ -25,6 +25,7 @@ * @bug 4313887 6838333 * @summary Unit test for java.nio.file.attribute.UserDefinedFileAttributeView * @library ../.. + * @key randomness */ import java.nio.ByteBuffer; diff --git a/jdk/test/java/security/KeyStore/PKCS12/WriteP12Test.java b/jdk/test/java/security/KeyStore/PKCS12/WriteP12Test.java new file mode 100644 index 00000000000..f4024090f2f --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/WriteP12Test.java @@ -0,0 +1,371 @@ +/* + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import static java.lang.System.out; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.Key; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.UnrecoverableKeyException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Base64; +import java.util.Enumeration; + +/* + * @test + * @bug 8048618 + * @summary Write different types p12 key store to Check the write related + * APIs. + * @run main WriteP12Test + */ + +public class WriteP12Test { + + private static final String IN_KEYSTORE_TYPE = "jks"; + private static final String IN_KEYSTORE_PRV = "SUN"; + + private static final String IN_KEYSTORE_ENDUSER = "keystoreEU.jks.data"; + private static final String IN_KEYSTORE_CA = "keystoreCA.jks.data"; + private static final String OUT_KEYSTORE = "outKeyStore.p12"; + + private static final String IN_STORE_PASS = "storepass"; + private static final String IN_KEY_PASS = "keypass"; + + private static final String CERT_PATH = System.getProperty("test.src", ".") + + File.separator + "certs" + File.separator + "writeP12" + + File.separator; + + private static final String CA_CERT_STR = "-----BEGIN CERTIFICATE-----\n" + + "MIIDFzCCAf8CBD8+0nAwDQYJKoZIhvcNAQEFBQAwUDELMAkGA1UEBhMCV\n" + + "VMxETAPBgNVBAoTCEphdmFTb2Z0MRUwEwYDVQQLEwxTZWN1cml0eSBTUU\n" + + "UxFzAVBgNVBAMTDlBLQ1MxMiBUZXN0IENBMB4XDTAzMDgxNzAwNTUxMlo\n" + + "XDTEzMDgxNDAwNTUxMlowUDELMAkGA1UEBhMCVVMxETAPBgNVBAoTCEph\n" + + "dmFTb2Z0MRUwEwYDVQQLEwxTZWN1cml0eSBTUUUxFzAVBgNVBAMTDlBLQ\n" + + "1MxMiBUZXN0IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQ\n" + + "EAk7Sh+K/yGsmJacZnjfkZfuWxGNJCPW0q69exwoRP+eBHMQwG00yi9aL\n" + + "SsZAqNpJSCDvpgySOAUmBd+f8WFhHqJfRVREVfv3mradDKZCjhqtsUI7I\n" + + "wRTYYy9clFkeeK4dHaxbuFMPpUu7yQfwSTXgvOA/UJ4kJuGtaYAdTJI4e\n" + + "f1mUASo6+dea0UZA/FHCuV7O6z3hr5VHlyhJL2/o/8M5tGBTBISODJSnn\n" + + "GNBvtQLNHnWYvs470UAE2BtuCGYh1V/3HAH1tRirS3MBBcb1XnIkiiXR3\n" + + "tjaBSB+XhoCfuG8KtInXXFaAnvKfY9mYFw6VJt9JYQpY2VDC7281/Pbz0\n" + + "dQIDAQABMA0GCSqGSIb3DQEBBQUAA4IBAQBzXZ8zHWrnC8/E+N/n2Czhx\n" + + "i18YQc2LPWBDLYTTxoFEazWmYLv1k/JT7Nta1qu1quvxXJ4uV1XHbd9NF\n" + + "AJWKwtFQEpfv4o6I7qWUPoxnfA+jyqKXxv27z25tzt+Y4xOEhqvO03G0Q\n" + + "imhkiNt9MF7L69y2U0/U73+uFNGzdAEDiI9EibvICiOnr1TeQ5GekK3Yb\n" + + "k5qe3lviMZPkkSXepTJI8m0AiXCji+eXj97jVLeH+RxeBchBY+uELrqUr\n" + + "sVOVWh7IBCqC/V7FqUTkmD1IFlzkkinatpl42s1MbhJId2yQkzaeBRc\n" + + "suE63bDEtuRWp9ynMO3QA4Yu85uBRWGzQ1Di\n" + + "-----END CERTIFICATE-----"; + private static final String LEAD_CERT = "-----BEGIN CERTIFICATE-----\n" + + "MIICwDCCAaigAwIBAgIEPz7S1jANBgkqhkiG9w0BAQQFADBQMQswCQYDV\n" + + "QQGEwJVUzERMA8GA1UEChMISmF2YVNvZnQxFTATBgNVBAsTDFNlY3VyaX\n" + + "R5IFNRRTEXMBUGA1UEAxMOUEtDUzEyIFRlc3QgQ0EwHhcNMDAwODA5MDc\n" + + "wMDAwWhcNMTAwODA3MDcwMDAwWjBSMQswCQYDVQQGEwJVUzERMA8GA1UE\n" + + "ChMISmF2YVNvZnQxFTATBgNVBAsTDFNlY3VyaXR5IFNRRTEZMBcGA1UEA\n" + + "xMQUEtDUzEyIFRlc3QgTGVhZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgY\n" + + "kCgYEAzq9X2USz/WjDhT+jUyZWqB5h4A33tS11YqH5qYvqjTXjcUI6gOp\n" + + "moXMafDG9RHRlIccvp51xLp7Ap3WMrv411lWBttqtZi5c1/DEC1cEM/Sl\n" + + "PCk1r2zFbkJu7QKieXeMcrjZEo6LcBHMwQjIpI+up9cr3VjuyqG/olQkU\n" + + "mXVuS0CAwEAAaMkMCIwDwYDVR0PAQH/BAUDAweAADAPBgNVHRMBAf8EBT\n" + + "ADAQH/MA0GCSqGSIb3DQEBBAUAA4IBAQBhbuim98TWmtv9vSldRE7RvQ8\n" + + "FlS0TyZVO7kcSNtfCUE4R76J1ElN74Koc5pQnUtduLeQJs2ao/mEcCZsE\n" + + "zVcwI3mSZrSzPhc8s7w5gOQA4TUwVLSSjKgBCaZ7R3+qJ3QeqPJ5O6sFz\n" + + "pvBYkgSa4MWptK41jbmT8cwZQJXFCi8WxFFJ+p97F1Ppm3LgmYmtiUP4M\n" + + "ZQwOBvpTZWXU0WrqFXpzWQx0mg4SX19fZm4nLcJAerCEUphf8ILagtpQM\n" + + "EErT3/jg6mfCdT3Rj055QXPfF4OiRFevPF5a1fZgrCePCukRQZcd7s8K5\n" + + "OBIaryuM0MdFtlzxi6XWeUNpVFFHURcy\n" + + "-----END CERTIFICATE-----"; + private static final String END_CERT = "-----BEGIN CERTIFICATE-----\n" + + "MIICNjCCAZ+gAwIBAgIEPz7WtzANBgkqhkiG9w0BAQQFADBSMQswCQYDV\n" + + "QQGEwJVUzERMA8GA1UEChMISmF2YVNvZnQxFTATBgNVBAsTDFNlY3VyaX\n" + + "R5IFNRRTEZMBcGA1UEAxMQUEtDUzEyIFRlc3QgTGVhZDAeFw0wMDA4MDk\n" + + "wNzAwMDBaFw0xMDA4MDcwNzAwMDBaMFgxCzAJBgNVBAYTAlVTMREwDwYD\n" + + "VQQKEwhKYXZhU29mdDEVMBMGA1UECxMMU2VjdXJpdHkgU1FFMR8wHQYDV\n" + + "QQDExZQS0NTMTIgVGVzdCBFbmQgVXNlciAxMIGfMA0GCSqGSIb3DQEBAQ\n" + + "UAA4GNADCBiQKBgQDIKomSYomDzH/V63eDQEG7od0DLcnnVZ81pbWhDss\n" + + "8gHV2m8pADdRqdihBmnSQEaMW4D3uZ4sFE1LtkQls6hjd7SdOsG5Y24L8\n" + + "15jot9a2JcB73H8H0VKirrObL5BZdt7BtASPDnYtW4Spt++YjDoJFxyF0\n" + + "HchkavzXaVTlexakwIDAQABoxMwETAPBgNVHQ8BAf8EBQMDB4AAMA0GCS\n" + + "qGSIb3DQEBBAUAA4GBAIFA3JXEmb9AXn3RD7t+Mn6DoyVDIy5jsn6xOKT\n" + + "JV25I0obpDUzgw4QaAMmM0ZvusOmZ2wZNS8MtyTUgdANyakbzn5SdxbTy\n" + + "TLEqQsFbX8UVC38fx5ZM6ExA5YSAvgmXudZpOVC0ATccoZS3JFU8CxSfW\n" + + "+Q3IC2MLh+QTg3hUJ5b\n-----END CERTIFICATE-----"; + + private final Certificate testerCert; + private final Certificate testLeadCert; + private final Certificate caCert; + + WriteP12Test() throws CertificateException { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + caCert = cf.generateCertificate(new ByteArrayInputStream(CA_CERT_STR + .getBytes())); + testLeadCert = cf.generateCertificate(new ByteArrayInputStream( + LEAD_CERT.getBytes())); + testerCert = cf.generateCertificate(new ByteArrayInputStream(END_CERT + .getBytes())); + } + + public static void main(String[] args) throws CertificateException, + UnrecoverableKeyException, KeyStoreException, + NoSuchProviderException, NoSuchAlgorithmException, IOException { + WriteP12Test jstest = new WriteP12Test(); + out.println("test WriteP12CertChain"); + /* + * WriteP12CertChain: This test creates a p12 keystore contains one + * entry with private key and a certificate chains contains three + * certificates in the order of user->lead->ca. This case expects to + * pass. + */ + jstest.test(new Certificate[] { jstest.testerCert, jstest.testLeadCert, + jstest.caCert }, IN_KEYSTORE_ENDUSER, "pkcs12testenduser1", + "pass", "pass"); + + /* + * WriteP12CertChainBad: same as WriteP12CertChain but chains order is + * user-ca-lead, the order is wrong so expects to fail. + */ + out.println("test WriteP12CertChainBad"); + try { + jstest.test(new Certificate[] { jstest.testerCert, jstest.caCert, + jstest.testLeadCert }, IN_KEYSTORE_ENDUSER, + "pkcs12testenduser1", "pass", "pass"); + throw new RuntimeException( + " Certificate chain is not valid, test should not pass." + + " Test failed."); + } catch (KeyStoreException e) { + e.printStackTrace(); + out.println(" Certificate chain is not valid,exception is" + + " expected. Test passed."); + } + /* + * WriteP12PrivateKey:This test creates a p12 contains a self-signed + * cert and private key,expects no exception + */ + out.println("test WriteP12PrivateKey"); + jstest.test(null, IN_KEYSTORE_ENDUSER, "pkcs12testenduser1", "pass", + "pass"); + + /* + * WriteP12TwoEntry: This test creates a p12 keystore with different + * storepass and keypass, and contains two entries. + */ + out.println("test WriteP12TwoEntry"); + jstest.testTwoEntry(IN_KEYSTORE_ENDUSER, IN_KEYSTORE_CA, + "pkcs12testenduser1", "pass", "pass"); + /* + * WriteP12TwoPass: This test creates a p12 keystore with different + * storepass and keypass, and contains one entry with private key and a + * certificate + */ + out.println("test WriteP12TwoPass"); + jstest.test(null, IN_KEYSTORE_CA, "pkcs12testCA", "storepass", + "keypass"); + } + + private void test(Certificate certs[], String inKeyStorePath, + String userAlias, String outStorePass, String outKeyPass) + throws KeyStoreException, NoSuchProviderException, IOException, + CertificateException, UnrecoverableKeyException, + NoSuchAlgorithmException { + // init output key store + KeyStore outputKeyStore = KeyStore.getInstance("pkcs12", "SunJSSE"); + outputKeyStore.load(null, null); + try (FileOutputStream fout = new FileOutputStream(OUT_KEYSTORE)) { + // KeyStore have encoded by Base64.getMimeEncoder().encode(),need + // decode first. + byte[] input = Files.readAllBytes(Paths.get(CERT_PATH, + inKeyStorePath)); + ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64 + .getMimeDecoder().decode(input)); + // input key store + KeyStore inputKeyStore = KeyStore.getInstance(IN_KEYSTORE_TYPE, + IN_KEYSTORE_PRV); + inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray()); + // add key/certificate to output key store + Key key = inputKeyStore + .getKey(userAlias, IN_KEY_PASS.toCharArray()); + out.println("Input Key Algorithm " + key.getAlgorithm()); + out.println("====Input Certs====="); + if (certs == null) { + certs = new Certificate[] { inputKeyStore + .getCertificate(userAlias) }; + } + for (Certificate cert : certs) { + out.println(((X509Certificate) cert).getSubjectDN()); + } + outputKeyStore.setKeyEntry(userAlias, key, + outKeyPass.toCharArray(), certs); + Certificate retCerts[] = outputKeyStore + .getCertificateChain(userAlias); + out.println("====Output Certs====="); + for (Certificate retCert : retCerts) { + out.println(((X509Certificate) retCert).getSubjectDN()); + } + out.println("====Output Key Algorithm====="); + Key outKey = outputKeyStore.getKey(userAlias, + outKeyPass.toCharArray()); + out.println(outKey.getAlgorithm()); + + if (!key.equals(outKey)) { + throw new RuntimeException("key don't match"); + } + if (!Arrays.equals(certs, retCerts)) { + throw new RuntimeException("certs don't match"); + } + // save output + outputKeyStore.store(fout, outStorePass.toCharArray()); + // test output + testKeyStore(outputKeyStore, outKeyPass.toCharArray()); + } + } + + private void testTwoEntry(String inKeyStoreOnePath, + String inKeyStoreTwoPath, String userAlias, String outStorePass, + String outKeyPass) throws KeyStoreException, + NoSuchProviderException, NoSuchAlgorithmException, + CertificateException, IOException, UnrecoverableKeyException { + // initial KeyStore + KeyStore outputKeyStore = KeyStore.getInstance("pkcs12", "SunJSSE"); + try (FileOutputStream fout = new FileOutputStream(OUT_KEYSTORE);) { + outputKeyStore.load(null, null); + KeyStore inputKeyStoreOne, inputKeyStoreTwo; + inputKeyStoreOne = KeyStore.getInstance(IN_KEYSTORE_TYPE, + IN_KEYSTORE_PRV); + // KeyStore have encoded by Base64.getMimeEncoder().encode(),need + // decode first. + byte[] inputBytes = Files.readAllBytes(Paths.get(CERT_PATH, + inKeyStoreOnePath)); + ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64 + .getMimeDecoder().decode(inputBytes)); + // input key store + inputKeyStoreOne.load(arrayIn, IN_STORE_PASS.toCharArray()); + + inputBytes = Files.readAllBytes(Paths.get(CERT_PATH, + inKeyStoreTwoPath)); + arrayIn = new ByteArrayInputStream(Base64.getMimeDecoder().decode( + inputBytes)); + inputKeyStoreTwo = KeyStore.getInstance(IN_KEYSTORE_TYPE, + IN_KEYSTORE_PRV); + inputKeyStoreTwo.load(arrayIn, IN_STORE_PASS.toCharArray()); + + // add key/certificate to output key store + out.println("====First Entry====="); + Key inputKey = inputKeyStoreOne.getKey(userAlias, + IN_KEY_PASS.toCharArray()); + Certificate cert = inputKeyStoreOne.getCertificate(userAlias); + Certificate certs[] = new Certificate[1]; + certs[0] = cert; + + out.println("====Input1 Key====="); + out.println(inputKey.getAlgorithm()); + out.println("====Input1 Certs====="); + out.println("Certificate :"); + out.println(((X509Certificate) cert).getSubjectDN()); + outputKeyStore.setKeyEntry("USER", inputKey, + outKeyPass.toCharArray(), certs); + out.println("====Second Entry====="); + String caAlias = "pkcs12testca"; + inputKey = inputKeyStoreTwo.getKey(caAlias, + IN_KEY_PASS.toCharArray()); + cert = inputKeyStoreTwo.getCertificate(caAlias); + certs[0] = cert; + out.println("====Input2 Key====="); + out.println(inputKey.getAlgorithm()); + out.println("====Input2 Certs====="); + out.println("Certificate :"); + out.println(((X509Certificate) cert).getSubjectDN()); + outputKeyStore.setKeyEntry("CA", inputKey, + outKeyPass.toCharArray(), certs); + // save output + outputKeyStore.store(fout, outStorePass.toCharArray()); + // test output + testKeyStore(outputKeyStore, outKeyPass.toCharArray()); + } + } + + private void testKeyStore(KeyStore inputKeyStore, char[] keypass) + throws KeyStoreException, UnrecoverableKeyException, + NoSuchAlgorithmException { + out.println("========== Key Store =========="); + out.println("getProvider : " + inputKeyStore.getProvider()); + out.println("getType : " + inputKeyStore.getType()); + out.println("getDefaultType : " + KeyStore.getDefaultType()); + + int idx = 0; + Enumeration e = inputKeyStore.aliases(); + String alias; + while (e.hasMoreElements()) { + alias = e.nextElement(); + if (!inputKeyStore.containsAlias(alias)) { + throw new RuntimeException("Alias not found"); + } + out.println("Alias " + idx + " : " + alias); + out.println("getCreationDate : " + + inputKeyStore.getCreationDate(alias)); + X509Certificate cert = (X509Certificate) inputKeyStore + .getCertificate(alias); + out.println("getCertificate : " + cert.getSubjectDN()); + String retAlias = inputKeyStore.getCertificateAlias(cert); + if (!retAlias.equals(alias)) { + throw new RuntimeException("Alias mismatch, actually " + + retAlias + ", expected " + alias); + } + out.println("getCertificateAlias : " + retAlias); + Certificate[] certs = inputKeyStore.getCertificateChain(alias); + int i = 0; + for (Certificate certification : certs) { + out.println("getCertificateChain " + i + + ((X509Certificate) certification).getSubjectDN()); + i++; + } + if (inputKeyStore.isCertificateEntry(alias)) { + throw new RuntimeException( + "inputKeystore should not be certEntry because this" + + " keystore only contain key pair entries."); + } + if (!inputKeyStore.isKeyEntry(alias)) { + throw new RuntimeException("Entry type unknown."); + } + idx++; + } + int size = inputKeyStore.size(); + if (idx != size) { + throw new RuntimeException("Size not match, actually " + idx + + ", expected " + size); + } + } + +} diff --git a/jdk/test/java/security/KeyStore/PKCS12/certs/writeP12/keystoreCA.jks.data b/jdk/test/java/security/KeyStore/PKCS12/certs/writeP12/keystoreCA.jks.data new file mode 100644 index 00000000000..1d6b5a4b6ac --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/certs/writeP12/keystoreCA.jks.data @@ -0,0 +1,38 @@ +/u3+7QAAAAIAAAABAAAAAQAMcGtjczEydGVzdGNhAAAA9w1mDAMAAAUCMIIE/jAOBgorBgEEASoC +EQEBBQAEggTqFhceJz85XyVsicsfonXYx+vvFXkb9Jmr11eh9n570ZdiFZ1hv4XRk/x/1C1spy5X +J2wv4lABGAOA5gV0aTKij+82NLoEz9zDW5fwAnrBKVjAq/NxdwEi9lvipiSVx1qglx/mQAHeEi4i +6vDoai3hVNQqVmd/TG2deyk/fQ9MZ7U2fmWcJDH4YbP39psQ+7rp9cDJ0P7GWoLXwbWs1vftbN0R +4fWitH1+6hBbIbVT9o0cM9ilAjpkNFr10pBEsfrikaE8IsN562soWfNxGwwrsjExEFeKlMrtNtWM +Wc4+YZ1ybVi/6krK/kFfOa+R3mtjBoD7zM4TSG9dptuvBLVgey8RXh3BQ8pU7uN5q+9Omqo1SsRN +wHYKjTrfWMozt+37ZlyCZ70Kb/2jJYWFuo9+wqXQU+MYnpZZB+cLt3PIFMakhIu1vpMpJCcoceaS +bjDWxCG8HHZjjFJPxAE3HEbCzaj4BevxQfxtp57llmtI2I0NJvua8JbFjf0U9MK6iRi4IpmBztpP +vxvaetT54wC+2c0QaDqANIn3Oc4tmvD4RGJfmFrEYEX6dQbCwYHAJF8sczqDb4xIYwrGmiMNeeha +4g9fcEa7Q+t1o1XLmNOp5e6I/TjUfXGvKlEyYeQ1FNLRqTtI5KvHQ1l71n1aQyEPvcff93NlF3jv +jWuqOqLzFT7sIZQxgjoum4i0DwLzOtuAWIDELNJ03MCciq5j0SjoLO2/ISctNTyGuYBmerjGCI9c +CLhGYnwLCOvvZN1yIqT79Se6qe/tBV5nEYUdXEt4ROJNabf1H4GmkXYeDQvtHrQ1IHM+Kg1UyEJz +fwdhJ68EU3gFenTtFgVJ+90YpemGtptgS6CvS3qC2H/H3XaKKQGpsXRCMSCRZcfMMOQEc6WLPsVY +rEhorQIAbbgHp4//H+RkNzG+5NN4pac5bo0kDTpeQkiOXGZZKyMHgagFvwLCN35rTi2HnHEXnYoi +jU1sGmUV+kRgRJ+N3Gx6D+uWNctkZMeTuVg+9ftIhEClGdtBSXWZu9lr/48cXkWJBubd4CWYrFMm +cTYezlQiTvmQgodrrwtcdo17J/L4PK74C72aIqPlWdEImGQs7I4n1mvceXoHvjYu5+tOxS0HH4sm +Y4iMr3hsqVAag2/LeLCG1gumpGiTdh9hk/aOcSWASv7rjq8JVpxWJe3JbrQ5k0U3e1nE2AdSXjEj +knBDpDFpGsnJaP2xxTdvQ+oV1pZ3m30xOeCTVV+0VBIw8eL0PDATSgqQ7FuWnYZ/FGaOrgnn14JM +HQicEfFN7TOa8q3/lbY5JTRtuG5umoWL2AWaaAW6G5GRTUNMOvBI5xTvR/kr3iNKTK2caKi0XTJ3 +WXd9jeuyLstpbtokG6xBbSiAb/SSL9yoh400DbKFTlVHKD8cijfuLKIM1TmL2ZksEh6JvF8GfdLl +FXZH7Ny8aJ63Ef947P9Y8+6WMzZDrkyoV+uInRq1TVXk6Ps6qiqI0j9fhMI8XMju61vjkeXprzBE +Pk2GbXo7MtHrBTobffkD3BszrFJai8n9vDrQgsaZYwWi4IxlKYefmWDaagiq/qDBZhKQCgyuJNN/ +5sQZDb6+J/MIgDk0M2bXEs6f2gT1rAyuH+rbnsnfUu9jRQupP4q0/ZCY2WOIaf8W34FnMdNzOUH8 +iE2T59UbMGQ0DLJeHwAAAAEABVguNTA5AAADGzCCAxcwggH/AgQ/PtJwMA0GCSqGSIb3DQEBBQUA +MFAxCzAJBgNVBAYTAlVTMREwDwYDVQQKEwhKYXZhU29mdDEVMBMGA1UECxMMU2VjdXJpdHkgU1FF +MRcwFQYDVQQDEw5QS0NTMTIgVGVzdCBDQTAeFw0wMzA4MTcwMDU1MTJaFw0xMzA4MTQwMDU1MTJa +MFAxCzAJBgNVBAYTAlVTMREwDwYDVQQKEwhKYXZhU29mdDEVMBMGA1UECxMMU2VjdXJpdHkgU1FF +MRcwFQYDVQQDEw5QS0NTMTIgVGVzdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +AJO0ofiv8hrJiWnGZ435GX7lsRjSQj1tKuvXscKET/ngRzEMBtNMovWi0rGQKjaSUgg76YMkjgFJ +gXfn/FhYR6iX0VURFX795q2nQymQo4arbFCOyMEU2GMvXJRZHniuHR2sW7hTD6VLu8kH8Ek14Lzg +P1CeJCbhrWmAHUySOHn9ZlAEqOvnXmtFGQPxRwrlezus94a+VR5coSS9v6P/DObRgUwSEjgyUp5x +jQb7UCzR51mL7OO9FABNgbbghmIdVf9xwB9bUYq0tzAQXG9V5yJIol0d7Y2gUgfl4aAn7hvCrSJ1 +1xWgJ7yn2PZmBcOlSbfSWEKWNlQwu9vNfz289HUCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAc12f +Mx1q5wvPxPjf59gs4cYtfGEHNiz1gQy2E08aBRGs1pmC79ZPyU+zbWtartarr8VyeLldVx23fTRQ +CVisLRUBKX7+KOiO6llD6MZ3wPo8qil8b9u89ubc7fmOMThIarztNxtEIpoZIjbfTBey+vctlNP1 +O9/rhTRs3QBA4iPRIm7yAojp69U3kORnpCt2G5Oant5b4jGT5JEl3qUySPJtAIlwo4vnl4/e41S3 +h/kcXgXIQWPrhC66lK7FTlVoeyAQqgv1exalE5Jg9SBZc5JIp2raZeNrNTG4SSHdskJM2ngUXLLh +Ot2wxLbkVqfcpzDt0AOGLvObgUVhs0NQ4nYQH5SPMKBNY+nGGfmMLaFPAelF \ No newline at end of file diff --git a/jdk/test/java/security/KeyStore/PKCS12/certs/writeP12/keystoreEU.jks.data b/jdk/test/java/security/KeyStore/PKCS12/certs/writeP12/keystoreEU.jks.data new file mode 100644 index 00000000000..c8e4ecf4705 --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/certs/writeP12/keystoreEU.jks.data @@ -0,0 +1,79 @@ +/u3+7QAAAAIAAAADAAAAAgAMcGtjczEydGVzdGNhAAAA9w18bwQABVguNTA5AAADGzCCAxcwggH/ +AgQ/PtJwMA0GCSqGSIb3DQEBBQUAMFAxCzAJBgNVBAYTAlVTMREwDwYDVQQKEwhKYXZhU29mdDEV +MBMGA1UECxMMU2VjdXJpdHkgU1FFMRcwFQYDVQQDEw5QS0NTMTIgVGVzdCBDQTAeFw0wMzA4MTcw +MDU1MTJaFw0xMzA4MTQwMDU1MTJaMFAxCzAJBgNVBAYTAlVTMREwDwYDVQQKEwhKYXZhU29mdDEV +MBMGA1UECxMMU2VjdXJpdHkgU1FFMRcwFQYDVQQDEw5QS0NTMTIgVGVzdCBDQTCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAJO0ofiv8hrJiWnGZ435GX7lsRjSQj1tKuvXscKET/ngRzEM +BtNMovWi0rGQKjaSUgg76YMkjgFJgXfn/FhYR6iX0VURFX795q2nQymQo4arbFCOyMEU2GMvXJRZ +HniuHR2sW7hTD6VLu8kH8Ek14LzgP1CeJCbhrWmAHUySOHn9ZlAEqOvnXmtFGQPxRwrlezus94a+ +VR5coSS9v6P/DObRgUwSEjgyUp5xjQb7UCzR51mL7OO9FABNgbbghmIdVf9xwB9bUYq0tzAQXG9V +5yJIol0d7Y2gUgfl4aAn7hvCrSJ11xWgJ7yn2PZmBcOlSbfSWEKWNlQwu9vNfz289HUCAwEAATAN +BgkqhkiG9w0BAQUFAAOCAQEAc12fMx1q5wvPxPjf59gs4cYtfGEHNiz1gQy2E08aBRGs1pmC79ZP +yU+zbWtartarr8VyeLldVx23fTRQCVisLRUBKX7+KOiO6llD6MZ3wPo8qil8b9u89ubc7fmOMThI +arztNxtEIpoZIjbfTBey+vctlNP1O9/rhTRs3QBA4iPRIm7yAojp69U3kORnpCt2G5Oant5b4jGT +5JEl3qUySPJtAIlwo4vnl4/e41S3h/kcXgXIQWPrhC66lK7FTlVoeyAQqgv1exalE5Jg9SBZc5JI +p2raZeNrNTG4SSHdskJM2ngUXLLhOt2wxLbkVqfcpzDt0AOGLvObgUVhs0NQ4gAAAAIADnBrY3Mx +MnRlc3RsZWFkAAAA9w1+meMABVguNTA5AAACxDCCAsAwggGooAMCAQICBD8+0tYwDQYJKoZIhvcN +AQEEBQAwUDELMAkGA1UEBhMCVVMxETAPBgNVBAoTCEphdmFTb2Z0MRUwEwYDVQQLEwxTZWN1cml0 +eSBTUUUxFzAVBgNVBAMTDlBLQ1MxMiBUZXN0IENBMB4XDTAwMDgwOTA3MDAwMFoXDTEwMDgwNzA3 +MDAwMFowUjELMAkGA1UEBhMCVVMxETAPBgNVBAoTCEphdmFTb2Z0MRUwEwYDVQQLEwxTZWN1cml0 +eSBTUUUxGTAXBgNVBAMTEFBLQ1MxMiBUZXN0IExlYWQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ +AoGBAM6vV9lEs/1ow4U/o1MmVqgeYeAN97UtdWKh+amL6o0143FCOoDqZqFzGnwxvUR0ZSHHL6ed +cS6ewKd1jK7+NdZVgbbarWYuXNfwxAtXBDP0pTwpNa9sxW5Cbu0Conl3jHK42RKOi3ARzMEIyKSP +rqfXK91Y7sqhv6JUJFJl1bktAgMBAAGjJDAiMA8GA1UdDwEB/wQFAwMHgAAwDwYDVR0TAQH/BAUw +AwEB/zANBgkqhkiG9w0BAQQFAAOCAQEAYW7opvfE1prb/b0pXURO0b0PBZUtE8mVTu5HEjbXwlBO +Ee+idRJTe+CqHOaUJ1LXbi3kCbNmqP5hHAmbBM1XMCN5kma0sz4XPLO8OYDkAOE1MFS0koyoAQmm +e0d/qid0HqjyeTurBc6bwWJIEmuDFqbSuNY25k/HMGUCVxQovFsRRSfqfexdT6Zty4JmJrYlD+DG +UMDgb6U2Vl1NFq6hV6c1kMdJoOEl9fX2ZuJy3CQHqwhFKYX/CC2oLaUDBBK09/44OpnwnU90Y9Oe +UFz3xeDokRXrzxeWtX2YKwnjwrpEUGXHe7PCuTgSGq8rjNDHRbZc8Yul1nlDaVRRR1EXMgAAAAEA +EnBrY3MxMnRlc3RlbmR1c2VyMQAAAPcNgTivAAACuTCCArUwDgYKKwYBBAEqAhEBAQUABIICoU6N +bD6qkNDM8KJFHCTHUevURAV8SUuzzBwsfYC0tEDMa2zGNUEvrmgyM3b5z7qR8XbTZvVBFJJLp3Jx +HmQpg0vLltDFFIPiVgRVcUEDPSmks1KP/bP/mE1uos31R6VyfNMGS3JnQblcSipcB893NrFFXNu2 +PUPjKCC9GrQZAmSM78BBTrwWD/Yd4rKcVh57DLKtUySoF29qXthusJjhSaqRZERaMV6egviE5+W8 +f8ppTYLx2gJmOyi9edJEdHxMcPzRvWgxlmUqUCDg0KVsosbxjjJKcmJ9b1KWuadKyAYkqxSDi8sx +2iwEQW3PQjLGBVHeQNntUF1wapp21sD1lVmDV3+61+fIphAUVRQXjmoYsEhrTc93IkDtQWgfJsgz +xjVVDbcy29VnMAK4f3tT/p5HeFO6yRQBE2B3IngSomRxbNh143VswNYqtZYy03UhOm8vbF2OfOJ/ +NzwC/F+19XgntnC0qv5j6VzwMGTt2NYPWXUqSzVIFswSunj70+ZsprCRX5IEFnpHDSL7OwDjEMFc +z6dpYQ9pwgyKh7JiLZxAr/9Nhb8QQDGrolzHoDt1QnC/DYvDGfTKu0ZjlXR4EQN4XFV+FAiykRfA +N1jIsTY7fCmLpLuW4paQnR1lPSGLeSvi63DOgN+lfVSJ5YjZm4yIRIS6lpvLVgcqodDqBRmPMP7x +fJ3osv1Wt4L/77BdJpZrUUygysRpzyUKlC6NwXr338HKPyAnfrkzIpHKnhTUaRVmfgAuzrXMFp8C +ejyYXJQwPPFAL5mIdUMkLDQKzESI0T3AD1LWVDM/0mGud9GhqiycI6AqC0j7MynRCvQG0LyRunFG +EQ2KipM//qPFKqwoVukxrLTunmGyeOe6UxodtK+qcn7SIXZ8jJM14a5rSDwAAAADAAVYLjUwOQAA +AjowggI2MIIBn6ADAgECAgQ/Pta3MA0GCSqGSIb3DQEBBAUAMFIxCzAJBgNVBAYTAlVTMREwDwYD +VQQKEwhKYXZhU29mdDEVMBMGA1UECxMMU2VjdXJpdHkgU1FFMRkwFwYDVQQDExBQS0NTMTIgVGVz +dCBMZWFkMB4XDTAwMDgwOTA3MDAwMFoXDTEwMDgwNzA3MDAwMFowWDELMAkGA1UEBhMCVVMxETAP +BgNVBAoTCEphdmFTb2Z0MRUwEwYDVQQLEwxTZWN1cml0eSBTUUUxHzAdBgNVBAMTFlBLQ1MxMiBU +ZXN0IEVuZCBVc2VyIDEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMgqiZJiiYPMf9Xrd4NA +Qbuh3QMtyedVnzWltaEOyzyAdXabykAN1Gp2KEGadJARoxbgPe5niwUTUu2RCWzqGN3tJ06wbljb +gvzXmOi31rYlwHvcfwfRUqKus5svkFl23sG0BI8Odi1bhKm375iMOgkXHIXQdyGRq/NdpVOV7FqT +AgMBAAGjEzARMA8GA1UdDwEB/wQFAwMHgAAwDQYJKoZIhvcNAQEEBQADgYEAgUDclcSZv0BefdEP +u34yfoOjJUMjLmOyfrE4pMlXbkjShukNTODDhBoAyYzRm+6w6ZnbBk1Lwy3JNSB0A3JqRvOflJ3F +tPJMsSpCwVtfxRULfx/HlkzoTEDlhIC+CZe51mk5ULQBNxyhlLckVTwLFJ9b5DcgLYwuH5BODeFQ +nlsABVguNTA5AAACxDCCAsAwggGooAMCAQICBD8+0tYwDQYJKoZIhvcNAQEEBQAwUDELMAkGA1UE +BhMCVVMxETAPBgNVBAoTCEphdmFTb2Z0MRUwEwYDVQQLEwxTZWN1cml0eSBTUUUxFzAVBgNVBAMT +DlBLQ1MxMiBUZXN0IENBMB4XDTAwMDgwOTA3MDAwMFoXDTEwMDgwNzA3MDAwMFowUjELMAkGA1UE +BhMCVVMxETAPBgNVBAoTCEphdmFTb2Z0MRUwEwYDVQQLEwxTZWN1cml0eSBTUUUxGTAXBgNVBAMT +EFBLQ1MxMiBUZXN0IExlYWQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAM6vV9lEs/1ow4U/ +o1MmVqgeYeAN97UtdWKh+amL6o0143FCOoDqZqFzGnwxvUR0ZSHHL6edcS6ewKd1jK7+NdZVgbba +rWYuXNfwxAtXBDP0pTwpNa9sxW5Cbu0Conl3jHK42RKOi3ARzMEIyKSPrqfXK91Y7sqhv6JUJFJl +1bktAgMBAAGjJDAiMA8GA1UdDwEB/wQFAwMHgAAwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B +AQQFAAOCAQEAYW7opvfE1prb/b0pXURO0b0PBZUtE8mVTu5HEjbXwlBOEe+idRJTe+CqHOaUJ1LX +bi3kCbNmqP5hHAmbBM1XMCN5kma0sz4XPLO8OYDkAOE1MFS0koyoAQmme0d/qid0HqjyeTurBc6b +wWJIEmuDFqbSuNY25k/HMGUCVxQovFsRRSfqfexdT6Zty4JmJrYlD+DGUMDgb6U2Vl1NFq6hV6c1 +kMdJoOEl9fX2ZuJy3CQHqwhFKYX/CC2oLaUDBBK09/44OpnwnU90Y9OeUFz3xeDokRXrzxeWtX2Y +KwnjwrpEUGXHe7PCuTgSGq8rjNDHRbZc8Yul1nlDaVRRR1EXMgAFWC41MDkAAAMbMIIDFzCCAf8C +BD8+0nAwDQYJKoZIhvcNAQEFBQAwUDELMAkGA1UEBhMCVVMxETAPBgNVBAoTCEphdmFTb2Z0MRUw +EwYDVQQLEwxTZWN1cml0eSBTUUUxFzAVBgNVBAMTDlBLQ1MxMiBUZXN0IENBMB4XDTAzMDgxNzAw +NTUxMloXDTEzMDgxNDAwNTUxMlowUDELMAkGA1UEBhMCVVMxETAPBgNVBAoTCEphdmFTb2Z0MRUw +EwYDVQQLEwxTZWN1cml0eSBTUUUxFzAVBgNVBAMTDlBLQ1MxMiBUZXN0IENBMIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk7Sh+K/yGsmJacZnjfkZfuWxGNJCPW0q69exwoRP+eBHMQwG +00yi9aLSsZAqNpJSCDvpgySOAUmBd+f8WFhHqJfRVREVfv3mradDKZCjhqtsUI7IwRTYYy9clFke +eK4dHaxbuFMPpUu7yQfwSTXgvOA/UJ4kJuGtaYAdTJI4ef1mUASo6+dea0UZA/FHCuV7O6z3hr5V +HlyhJL2/o/8M5tGBTBISODJSnnGNBvtQLNHnWYvs470UAE2BtuCGYh1V/3HAH1tRirS3MBBcb1Xn +IkiiXR3tjaBSB+XhoCfuG8KtInXXFaAnvKfY9mYFw6VJt9JYQpY2VDC7281/Pbz0dQIDAQABMA0G +CSqGSIb3DQEBBQUAA4IBAQBzXZ8zHWrnC8/E+N/n2Czhxi18YQc2LPWBDLYTTxoFEazWmYLv1k/J +T7Nta1qu1quvxXJ4uV1XHbd9NFAJWKwtFQEpfv4o6I7qWUPoxnfA+jyqKXxv27z25tzt+Y4xOEhq +vO03G0QimhkiNt9MF7L69y2U0/U73+uFNGzdAEDiI9EibvICiOnr1TeQ5GekK3Ybk5qe3lviMZPk +kSXepTJI8m0AiXCji+eXj97jVLeH+RxeBchBY+uELrqUrsVOVWh7IBCqC/V7FqUTkmD1IFlzkkin +atpl42s1MbhJId2yQkzaeBRcsuE63bDEtuRWp9ynMO3QA4Yu85uBRWGzQ1Di7p2dz0wNRNimbVP4 +VL+NWQOgtME= \ No newline at end of file diff --git a/jdk/test/java/security/MessageDigest/ByteBuffers.java b/jdk/test/java/security/MessageDigest/ByteBuffers.java index 4ce30846368..dd3467d0e67 100644 --- a/jdk/test/java/security/MessageDigest/ByteBuffers.java +++ b/jdk/test/java/security/MessageDigest/ByteBuffers.java @@ -26,6 +26,7 @@ * @bug 4844847 * @summary Test the MessageDigest.update(ByteBuffer) method * @author Andreas Sterbenz + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/security/MessageDigest/TestDigestIOStream.java b/jdk/test/java/security/MessageDigest/TestDigestIOStream.java index 46028e85af8..868da86ef62 100644 --- a/jdk/test/java/security/MessageDigest/TestDigestIOStream.java +++ b/jdk/test/java/security/MessageDigest/TestDigestIOStream.java @@ -36,6 +36,7 @@ import static java.lang.System.out; * @bug 8050370 * @summary MessageDigest tests with DigestIOStream * @author Kevin Liu + * @key randomness */ enum ReadModel { diff --git a/jdk/test/java/security/MessageDigest/TestSameLength.java b/jdk/test/java/security/MessageDigest/TestSameLength.java index eb59815c9bd..666baf3e69e 100644 --- a/jdk/test/java/security/MessageDigest/TestSameLength.java +++ b/jdk/test/java/security/MessageDigest/TestSameLength.java @@ -33,6 +33,7 @@ import java.util.Random; * @summary Check md.getDigestLength() equal digest output length with various * algorithm/dataLen/(update,digest methods). * @author Kevin Liu + * @key randomness */ public class TestSameLength { diff --git a/jdk/test/java/security/MessageDigest/TestSameValue.java b/jdk/test/java/security/MessageDigest/TestSameValue.java index aef4ceae402..56b8652264a 100644 --- a/jdk/test/java/security/MessageDigest/TestSameValue.java +++ b/jdk/test/java/security/MessageDigest/TestSameValue.java @@ -34,6 +34,7 @@ import java.util.Random; * @summary Check md.digest(data) value whether same with digest output value * with various update/digest methods. * @author Kevin Liu + * @key randomness */ public class TestSameValue { diff --git a/jdk/test/java/security/Signature/ByteBuffers.java b/jdk/test/java/security/Signature/ByteBuffers.java index e3063511d90..937c9842c3b 100644 --- a/jdk/test/java/security/Signature/ByteBuffers.java +++ b/jdk/test/java/security/Signature/ByteBuffers.java @@ -26,6 +26,7 @@ * @bug 4844847 * @summary Test the Signature.update(ByteBuffer) method * @author Andreas Sterbenz + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/security/Signature/NONEwithRSA.java b/jdk/test/java/security/Signature/NONEwithRSA.java index 16f7b53f087..6d18c7ac96f 100644 --- a/jdk/test/java/security/Signature/NONEwithRSA.java +++ b/jdk/test/java/security/Signature/NONEwithRSA.java @@ -26,6 +26,7 @@ * @bug 4955844 * @summary ensure that the NONEwithRSA adapter works correctly * @author Andreas Sterbenz + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/security/spec/EllipticCurveMatch.java b/jdk/test/java/security/spec/EllipticCurveMatch.java index 797f6d2e0f3..85af7df9a34 100644 --- a/jdk/test/java/security/spec/EllipticCurveMatch.java +++ b/jdk/test/java/security/spec/EllipticCurveMatch.java @@ -26,6 +26,7 @@ * @bug 6738532 * @summary Check EllipticCurve.equals() does not compare seed value of curve. * @author Mike StJohns + * @key randomness */ import java.security.spec.*; diff --git a/jdk/test/java/sql/JavatimeTest.java b/jdk/test/java/sql/JavatimeTest.java index 3ff70d007d1..89344d7cdc6 100644 --- a/jdk/test/java/sql/JavatimeTest.java +++ b/jdk/test/java/sql/JavatimeTest.java @@ -25,6 +25,7 @@ *@test *@bug 8007520 *@summary Test those bridge methods to/from java.time date/time classes + * @key randomness */ import java.util.Random; diff --git a/jdk/test/java/text/Format/MessageFormat/Bug7003643.java b/jdk/test/java/text/Format/MessageFormat/Bug7003643.java index aeb722cac17..35af811d221 100644 --- a/jdk/test/java/text/Format/MessageFormat/Bug7003643.java +++ b/jdk/test/java/text/Format/MessageFormat/Bug7003643.java @@ -25,6 +25,7 @@ * @test * @bug 7003643 * @summary Make sure MessageFormat.toPattern produces correct quoting. (SPI part is tested in PluggableLocale tests.) + * @key randomness */ import java.text.*; diff --git a/jdk/test/java/time/tck/java/time/TCKLocalDateTime.java b/jdk/test/java/time/tck/java/time/TCKLocalDateTime.java index 51b1163dbca..93b385011d7 100644 --- a/jdk/test/java/time/tck/java/time/TCKLocalDateTime.java +++ b/jdk/test/java/time/tck/java/time/TCKLocalDateTime.java @@ -107,8 +107,6 @@ import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; import java.time.Clock; import java.time.DateTimeException; import java.time.DayOfWeek; @@ -260,16 +258,17 @@ public class TCKLocalDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test(timeOut=30000) // TODO: remove when time zone loading is faster public void now() { + final long DELTA = 20_000_000_000L; // 20 seconds of nanos leeway LocalDateTime expected = LocalDateTime.now(Clock.systemDefaultZone()); LocalDateTime test = LocalDateTime.now(); long diff = Math.abs(test.toLocalTime().toNanoOfDay() - expected.toLocalTime().toNanoOfDay()); - if (diff >= 100000000) { + if (diff >= DELTA) { // may be date change expected = LocalDateTime.now(Clock.systemDefaultZone()); test = LocalDateTime.now(); diff = Math.abs(test.toLocalTime().toNanoOfDay() - expected.toLocalTime().toNanoOfDay()); } - assertTrue(diff < 100000000); // less than 0.1 secs + assertTrue(diff < DELTA); } //----------------------------------------------------------------------- diff --git a/jdk/test/java/time/tck/java/time/TCKOffsetDateTime.java b/jdk/test/java/time/tck/java/time/TCKOffsetDateTime.java index b77b7a8ba15..991b447a506 100644 --- a/jdk/test/java/time/tck/java/time/TCKOffsetDateTime.java +++ b/jdk/test/java/time/tck/java/time/TCKOffsetDateTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -104,8 +104,6 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.time.Clock; @@ -235,16 +233,17 @@ public class TCKOffsetDateTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void now() { + final long DELTA = 20_000_000_000L; // 20 seconds of nanos leeway OffsetDateTime expected = OffsetDateTime.now(Clock.systemDefaultZone()); OffsetDateTime test = OffsetDateTime.now(); long diff = Math.abs(test.toLocalTime().toNanoOfDay() - expected.toLocalTime().toNanoOfDay()); - if (diff >= 100000000) { + if (diff >= DELTA) { // may be date change expected = OffsetDateTime.now(Clock.systemDefaultZone()); test = OffsetDateTime.now(); diff = Math.abs(test.toLocalTime().toNanoOfDay() - expected.toLocalTime().toNanoOfDay()); } - assertTrue(diff < 100000000); // less than 0.1 secs + assertTrue(diff < DELTA); } //----------------------------------------------------------------------- diff --git a/jdk/test/java/time/tck/java/time/TCKOffsetTime.java b/jdk/test/java/time/tck/java/time/TCKOffsetTime.java index d373be443f3..0882dfcb19e 100644 --- a/jdk/test/java/time/tck/java/time/TCKOffsetTime.java +++ b/jdk/test/java/time/tck/java/time/TCKOffsetTime.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -89,8 +89,6 @@ import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.time.Clock; @@ -202,12 +200,19 @@ public class TCKOffsetTime extends AbstractDateTimeTest { //----------------------------------------------------------------------- @Test public void now() { + final long DELTA = 20_000_000_000L; // 20 seconds of nanos leeway ZonedDateTime nowDT = ZonedDateTime.now(); OffsetTime expected = OffsetTime.now(Clock.systemDefaultZone()); OffsetTime test = OffsetTime.now(); long diff = Math.abs(test.toLocalTime().toNanoOfDay() - expected.toLocalTime().toNanoOfDay()); - assertTrue(diff < 100000000); // less than 0.1 secs + if (diff >= DELTA) { + // may be date change + expected = OffsetTime.now(Clock.systemDefaultZone()); + test = OffsetTime.now(); + diff = Math.abs(test.toLocalTime().toNanoOfDay() - expected.toLocalTime().toNanoOfDay()); + } + assertTrue(diff < DELTA); assertEquals(test.getOffset(), nowDT.getOffset()); } diff --git a/jdk/test/java/time/test/java/time/format/TestTextParser.java b/jdk/test/java/time/test/java/time/format/TestTextParser.java index 07bd2146212..a1b264a756b 100644 --- a/jdk/test/java/time/test/java/time/format/TestTextParser.java +++ b/jdk/test/java/time/test/java/time/format/TestTextParser.java @@ -68,10 +68,20 @@ import static org.testng.Assert.assertTrue; import java.text.ParsePosition; import java.time.DayOfWeek; +import java.time.chrono.ChronoLocalDate; +import java.time.chrono.JapaneseChronology; +import java.time.chrono.HijrahDate; +import java.time.chrono.JapaneseDate; +import java.time.chrono.MinguoDate; +import java.time.chrono.ThaiBuddhistDate; import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; import java.time.format.TextStyle; +import java.time.format.SignStyle; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalField; +import java.time.temporal.TemporalQueries; +import java.time.temporal.ChronoField; import java.util.Locale; import org.testng.annotations.DataProvider; @@ -243,6 +253,8 @@ public class TestTextParser extends AbstractTestPrinterParser { }; } + + @Test(dataProvider="parseText") public void test_parseText(TemporalField field, TextStyle style, int value, String input) throws Exception { ParsePosition pos = new ParsePosition(0); @@ -433,4 +445,42 @@ public class TestTextParser extends AbstractTestPrinterParser { assertEquals(pos.getIndex(), input.length()); } + //----------------------------------------------------------------------- + @DataProvider(name="parseChronoLocalDate") + Object[][] provider_chronoLocalDate() { + return new Object[][] { + { HijrahDate.now() }, + { JapaneseDate.now() }, + { MinguoDate.now() }, + { ThaiBuddhistDate.now() }}; + } + + private static final DateTimeFormatter fmt_chrono = + new DateTimeFormatterBuilder() + .optionalStart() + .appendChronologyId() + .appendLiteral(' ') + .optionalEnd() + .optionalStart() + .appendText(ChronoField.ERA, TextStyle.SHORT) + .appendLiteral(' ') + .optionalEnd() + .appendValue(ChronoField.YEAR_OF_ERA, 1, 9, SignStyle.NORMAL) + .appendLiteral('-') + .appendValue(ChronoField.MONTH_OF_YEAR, 1, 2, SignStyle.NEVER) + .appendLiteral('-') + .appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NEVER) + .toFormatter(); + + @Test(dataProvider="parseChronoLocalDate") + public void test_chronoLocalDate(ChronoLocalDate date) throws Exception { + System.out.printf(" %s, [fmt=%s]%n", date, fmt_chrono.format(date)); + assertEquals(date, fmt_chrono.parse(fmt_chrono.format(date), ChronoLocalDate::from)); + + DateTimeFormatter fmt = DateTimeFormatter.ofPattern("[GGG ]yyy-MM-dd") + .withChronology(date.getChronology()); + System.out.printf(" %s, [fmt=%s]%n", date.toString(), fmt.format(date)); + assertEquals(date, fmt.parse(fmt.format(date), ChronoLocalDate::from)); + } + } diff --git a/jdk/test/java/util/Arrays/ArrayObjectMethods.java b/jdk/test/java/util/Arrays/ArrayObjectMethods.java index 8010f1b1d80..3d3e928b08c 100644 --- a/jdk/test/java/util/Arrays/ArrayObjectMethods.java +++ b/jdk/test/java/util/Arrays/ArrayObjectMethods.java @@ -26,6 +26,7 @@ * @bug 4906359 6239296 * @summary Basic test for content-based array object methods * @author Josh Bloch, Martin Buchholz + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/Arrays/CopyMethods.java b/jdk/test/java/util/Arrays/CopyMethods.java index e19b8073a59..4e38e8adf21 100644 --- a/jdk/test/java/util/Arrays/CopyMethods.java +++ b/jdk/test/java/util/Arrays/CopyMethods.java @@ -26,6 +26,7 @@ * @bug 4655503 * @summary Test for array cloning and slicing methods. * @author John Rose + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/Arrays/Correct.java b/jdk/test/java/util/Arrays/Correct.java index 93301619928..e9ddc7edef5 100644 --- a/jdk/test/java/util/Arrays/Correct.java +++ b/jdk/test/java/util/Arrays/Correct.java @@ -26,6 +26,7 @@ * @bug 4726380 8037097 * @summary Check that different sorts give equivalent results. * @run testng Correct + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/Arrays/TimSortStackSize2.java b/jdk/test/java/util/Arrays/TimSortStackSize2.java index a456c883000..9e212fd00bd 100644 --- a/jdk/test/java/util/Arrays/TimSortStackSize2.java +++ b/jdk/test/java/util/Arrays/TimSortStackSize2.java @@ -24,22 +24,63 @@ /* * @test * @bug 8072909 - * @run main/othervm -Xms385m TimSortStackSize2 67108864 + * @library /lib/testlibrary /../../test/lib + * @build jdk.testlibrary.* + * @build TimSortStackSize2 + * @run main ClassFileInstaller sun.hotspot.WhiteBox + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions + * -XX:+WhiteBoxAPI TimSortStackSize2 * @summary Test TimSort stack size on big arrays - * big tests not for regular execution on all platforms: - * run main/othervm -Xmx8g TimSortStackSize2 1073741824 - * run main/othervm -Xmx16g TimSortStackSize2 2147483644 */ import java.util.ArrayList; import java.util.Arrays; -import java.util.Comparator; import java.util.List; import java.util.function.Consumer; +import jdk.testlibrary.OutputAnalyzer; +import jdk.testlibrary.ProcessTools; +import jdk.testlibrary.Utils; +import sun.hotspot.WhiteBox; + public class TimSortStackSize2 { public static void main(String[] args) { - int lengthOfTest = Integer.parseInt(args[0]); + if ( args == null || args.length == 0 ){ + startMeWithArgs(); + } else { + doTestOfTwoTimSorts(Integer.parseInt(args[0])); + } + } + + private static void startMeWithArgs(){ + /* + * big tests not for regular execution on all platforms: + * run main/othervm -Xmx8g TimSortStackSize2 1073741824 + * run main/othervm -Xmx16g TimSortStackSize2 2147483644 + */ + try { + Boolean compressedOops = WhiteBox.getWhiteBox() + .getBooleanVMFlag("UseCompressedOops"); + final String xmsValue = "-Xms" + + ((compressedOops == null || compressedOops) ? "385" : "770") + + "m"; + System.out.println( "compressedOops: " + compressedOops + + "; Test will be started with \"" + xmsValue + "\""); + ProcessBuilder processBuilder = ProcessTools + .createJavaProcessBuilder(Utils.addTestJavaOpts(xmsValue, + "TimSortStackSize2", "67108864" + ) + ); + OutputAnalyzer output = ProcessTools.executeProcess(processBuilder); + System.out.println(output.getOutput()); + output.shouldHaveExitValue(0); + } catch( Exception e ){ + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + private static void doTestOfTwoTimSorts(final int lengthOfTest){ boolean passed = doTest("TimSort", lengthOfTest, (Integer [] a) -> Arrays.sort(a)); passed = doTest("ComparableTimSort", lengthOfTest, (Integer [] a) -> diff --git a/jdk/test/java/util/Base64/TestBase64.java b/jdk/test/java/util/Base64/TestBase64.java index 5466cf33355..bb2330721ec 100644 --- a/jdk/test/java/util/Base64/TestBase64.java +++ b/jdk/test/java/util/Base64/TestBase64.java @@ -25,6 +25,7 @@ * @test 4235519 8004212 8005394 8007298 8006295 8006315 8006530 8007379 8008925 * 8014217 8025003 8026330 8028397 * @summary tests java.util.Base64 + * @key randomness */ import java.io.ByteArrayInputStream; diff --git a/jdk/test/java/util/BitSet/BSMethods.java b/jdk/test/java/util/BitSet/BSMethods.java index 86d7499a428..b8ed8b31999 100644 --- a/jdk/test/java/util/BitSet/BSMethods.java +++ b/jdk/test/java/util/BitSet/BSMethods.java @@ -27,6 +27,7 @@ * @summary Test the operation of the methods of BitSet class * @author Mike McCloskey, Martin Buchholz * @run main/othervm BSMethods + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/BitSet/BitSetStreamTest.java b/jdk/test/java/util/BitSet/BitSetStreamTest.java index 394f3ac3337..d4e2d8d4919 100644 --- a/jdk/test/java/util/BitSet/BitSetStreamTest.java +++ b/jdk/test/java/util/BitSet/BitSetStreamTest.java @@ -43,7 +43,7 @@ import static org.testng.Assert.fail; /** * @test * @summary test BitSet stream - * @bug 8012645 + * @bug 8012645 8076442 * @run testng BitSetStreamTest */ public class BitSetStreamTest { @@ -70,6 +70,7 @@ public class BitSetStreamTest { { "step 5", IntStream.range(0, 255).map(f -> f * 5) }, { "step 7", IntStream.range(0, 255).map(f -> f * 7) }, { "1, 10, 100, 1000", IntStream.of(1, 10, 100, 1000) }, + { "max int", IntStream.of(Integer.MAX_VALUE) }, { "25 fibs", IntStream.generate(new Fibs()).limit(25) } }; @@ -106,6 +107,8 @@ public class BitSetStreamTest { for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) { assertTrue(it.hasNext()); assertEquals(it.nextInt(), i); + if (i == Integer.MAX_VALUE) + break; // or (i+1) would overflow } assertFalse(it.hasNext()); } diff --git a/jdk/test/java/util/BitSet/ImportExport.java b/jdk/test/java/util/BitSet/ImportExport.java index 9554b2e4ba4..6d01ab4b7c5 100644 --- a/jdk/test/java/util/BitSet/ImportExport.java +++ b/jdk/test/java/util/BitSet/ImportExport.java @@ -26,6 +26,7 @@ * @bug 5037068 * @summary Test import/export constructors and methods * @author Martin Buchholz + * @key randomness */ import java.nio.*; diff --git a/jdk/test/java/util/BitSet/PreviousBits.java b/jdk/test/java/util/BitSet/PreviousBits.java index bba55318fdd..e83a6df27a8 100644 --- a/jdk/test/java/util/BitSet/PreviousBits.java +++ b/jdk/test/java/util/BitSet/PreviousBits.java @@ -25,6 +25,7 @@ * @test * @bug 6410729 6586631 * @summary Test previousClearBit, previousSetBit + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/Calendar/Bug8075548.java b/jdk/test/java/util/Calendar/Bug8075548.java new file mode 100644 index 00000000000..121a28b8b17 --- /dev/null +++ b/jdk/test/java/util/Calendar/Bug8075548.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 8075548 + * @summary Make sure that the format form of month names are produced when there are + * no stand-alone ones available. + */ + +import java.text.*; +import java.util.*; +import static java.util.Calendar.*; + +public class Bug8075548 { + static int errors = 0; + + public static void main(String[] args) throws Throwable { + Date date = new SimpleDateFormat("yyyy-MM-dd", Locale.US).parse("2010-09-15"); + String[][] FORMAT_PAIRS = { + { "LLLL", "MMMM" }, + { "LLL", "MMM" } + }; + Locale[] LOCALES = { + Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN, Locale.JAPANESE + }; + + for (Locale locale : LOCALES) { + for (String[] formats : FORMAT_PAIRS) { + String el = new SimpleDateFormat(formats[0], locale).format(date); + String em = new SimpleDateFormat(formats[1], locale).format(date); + if (!el.equals(em)) { + errors++; + System.err.println(locale + ": " + + formats[0] + " -> " + el + ", " + + formats[1] + " -> " + em); + } + } + } + + // Test Calendar.getDisplayName() and .getDisplayNames(). + for (Locale locale : LOCALES) { + testDisplayNames(locale, LONG_FORMAT, LONG_STANDALONE); + testDisplayNames(locale, SHORT_FORMAT, SHORT_STANDALONE); + testDisplayNames(locale, NARROW_FORMAT, NARROW_STANDALONE); + } + + if (errors > 0) { + throw new RuntimeException("Failed"); + } + } + + private static void testDisplayNames(Locale locale, int formatStyle, int standaloneStyle) { + Map map = new HashMap<>(); + for (int month = JANUARY; month <= DECEMBER; month++) { + Calendar cal = new GregorianCalendar(2015, month, 1); + String format = cal.getDisplayName(MONTH, formatStyle, locale); + String standalone = cal.getDisplayName(MONTH, standaloneStyle, locale); + if (!format.equals(standalone)) { + System.err.println("Calendar.getDisplayName: " + (month+1) + + ", locale=" + locale + + ", format=" + format + ", standalone=" + standalone); + errors++; + } + if (standalone != null) { + map.put(standalone, month); + } + } + if (formatStyle == NARROW_FORMAT) { + // Narrow styles don't support unique names. + // (e.g., "J" for JANUARY, JUNE, and JULY) + return; + } + Calendar cal = new GregorianCalendar(2015, JANUARY, 1); + Map mapStandalone = cal.getDisplayNames(MONTH, standaloneStyle, locale); + if (!map.equals(mapStandalone)) { + System.err.printf("Calendar.getDisplayNames: locale=%s%n map=%s%n mapStandalone=%s%n", + locale, map, mapStandalone); + errors++; + } + Map mapAll = cal.getDisplayNames(MONTH, ALL_STYLES, locale); + if (!mapAll.entrySet().containsAll(map.entrySet())) { + System.err.printf("Calendar.getDisplayNames: locale=%s%n map=%s%n mapAll=%s%n", + locale, map, mapAll); + errors++; + } + } +} diff --git a/jdk/test/java/util/Calendar/JavatimeTest.java b/jdk/test/java/util/Calendar/JavatimeTest.java index 6a0a4ff9a66..7af6e9d4c03 100644 --- a/jdk/test/java/util/Calendar/JavatimeTest.java +++ b/jdk/test/java/util/Calendar/JavatimeTest.java @@ -25,6 +25,7 @@ *@test *@bug 8007520 8008254 *@summary Test those bridge methods to/from java.time date/time classes + * @key randomness */ import java.util.Calendar; diff --git a/jdk/test/java/util/Calendar/NarrowNamesTest.java b/jdk/test/java/util/Calendar/NarrowNamesTest.java index 7338792abd3..1df04763341 100644 --- a/jdk/test/java/util/Calendar/NarrowNamesTest.java +++ b/jdk/test/java/util/Calendar/NarrowNamesTest.java @@ -86,7 +86,19 @@ public class NarrowNamesTest { "\u6728", "\u91d1", "\u571f"); - testMap(THTH, MONTH, NARROW_FORMAT); // expect null + testMap(THTH, MONTH, NARROW_FORMAT, + "\u0e21.\u0e04.", + "\u0e01.\u0e1e.", + "\u0e21\u0e35.\u0e04.", + "\u0e40\u0e21.\u0e22.", + "\u0e1e.\u0e04.", + "\u0e21\u0e34.\u0e22", // no last dot + "\u0e01.\u0e04.", + "\u0e2a.\u0e04.", + "\u0e01.\u0e22.", + "\u0e15.\u0e04.", + "\u0e1e.\u0e22.", + "\u0e18.\u0e04."); testMap(THTH, MONTH, NARROW_STANDALONE, "\u0e21.\u0e04.", "\u0e01.\u0e1e.", @@ -146,7 +158,7 @@ public class NarrowNamesTest { Calendar cal = Calendar.getInstance(locale); Map got = cal.getDisplayNames(field, style, locale); if (!(expectedMap == null && got == null) - && !expectedMap.equals(got)) { + && !(expectedMap != null && expectedMap.equals(got))) { System.err.printf("testMap: locale=%s, field=%d, style=%d, expected=%s, got=%s%n", locale, field, style, expectedMap, got); errors++; diff --git a/jdk/test/java/util/Collection/MOAT.java b/jdk/test/java/util/Collection/MOAT.java index f55a1e87745..e04659c4dda 100644 --- a/jdk/test/java/util/Collection/MOAT.java +++ b/jdk/test/java/util/Collection/MOAT.java @@ -30,6 +30,7 @@ * @summary Run many tests on many Collection and Map implementations * @author Martin Buchholz * @run main MOAT + * @key randomness */ /* Mother Of All (Collection) Tests diff --git a/jdk/test/java/util/Collections/AddAll.java b/jdk/test/java/util/Collections/AddAll.java index dc768206085..0f8e6d9d527 100644 --- a/jdk/test/java/util/Collections/AddAll.java +++ b/jdk/test/java/util/Collections/AddAll.java @@ -26,6 +26,7 @@ * @bug 4822887 * @summary Basic test for Collections.addAll * @author Josh Bloch + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/Collections/CheckedListBash.java b/jdk/test/java/util/Collections/CheckedListBash.java index dfaa8773d03..80d7e3fd475 100644 --- a/jdk/test/java/util/Collections/CheckedListBash.java +++ b/jdk/test/java/util/Collections/CheckedListBash.java @@ -26,6 +26,7 @@ * @bug 4904067 * @summary Unit test for Collections.checkedList * @author Josh Bloch + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/Collections/CheckedMapBash.java b/jdk/test/java/util/Collections/CheckedMapBash.java index 9a6aab1cafc..7f622aa8e23 100644 --- a/jdk/test/java/util/Collections/CheckedMapBash.java +++ b/jdk/test/java/util/Collections/CheckedMapBash.java @@ -27,6 +27,7 @@ * @summary Unit test for Collections.checkedMap * @author Josh Bloch * @run testng CheckedMapBash + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/Collections/CheckedSetBash.java b/jdk/test/java/util/Collections/CheckedSetBash.java index 462792cf1d8..c24878a81af 100644 --- a/jdk/test/java/util/Collections/CheckedSetBash.java +++ b/jdk/test/java/util/Collections/CheckedSetBash.java @@ -27,6 +27,7 @@ * @summary Unit test for Collections.checkedSet * @author Josh Bloch * @run testng CheckedSetBash + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/Collections/Disjoint.java b/jdk/test/java/util/Collections/Disjoint.java index 762f5164a67..e13241efbb7 100644 --- a/jdk/test/java/util/Collections/Disjoint.java +++ b/jdk/test/java/util/Collections/Disjoint.java @@ -26,6 +26,7 @@ * @bug 4339792 * @summary Basic test for Collections.disjoint * @author Josh Bloch + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/Collections/Rotate.java b/jdk/test/java/util/Collections/Rotate.java index aae1deb7bc0..a759e90e1d3 100644 --- a/jdk/test/java/util/Collections/Rotate.java +++ b/jdk/test/java/util/Collections/Rotate.java @@ -25,6 +25,7 @@ * @test * @bug 4323074 * @summary Basic test for new rotate algorithm + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/EnumSet/EnumSetBash.java b/jdk/test/java/util/EnumSet/EnumSetBash.java index a7ab57019cf..873c781bfe0 100644 --- a/jdk/test/java/util/EnumSet/EnumSetBash.java +++ b/jdk/test/java/util/EnumSet/EnumSetBash.java @@ -28,6 +28,7 @@ * @author Josh Bloch * @author Neal Gafter * @author Yo Ma Ma + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/HashSet/Serialization.java b/jdk/test/java/util/HashSet/Serialization.java index 7597ae1a564..b6f9e55373e 100644 --- a/jdk/test/java/util/HashSet/Serialization.java +++ b/jdk/test/java/util/HashSet/Serialization.java @@ -34,6 +34,7 @@ import java.util.concurrent.ThreadLocalRandom; * @test * @bug 8016252 * @summary Verify that a serialized HashSet may successfully be deserialized. + * @key randomness */ public class Serialization { diff --git a/jdk/test/java/util/IdentityHashMap/Capacity.java b/jdk/test/java/util/IdentityHashMap/Capacity.java index 3114e6c16de..1be172efc49 100644 --- a/jdk/test/java/util/IdentityHashMap/Capacity.java +++ b/jdk/test/java/util/IdentityHashMap/Capacity.java @@ -39,6 +39,7 @@ import static org.testng.Assert.*; * @summary IdentityHashMap reallocates storage when inserting expected * number of elements * @run testng Capacity + * @key randomness */ @Test diff --git a/jdk/test/java/util/List/LockStep.java b/jdk/test/java/util/List/LockStep.java index 70538fcb2bb..100b63f9fe8 100644 --- a/jdk/test/java/util/List/LockStep.java +++ b/jdk/test/java/util/List/LockStep.java @@ -26,6 +26,7 @@ * @bug 6359979 * @summary Compare List implementations for identical behavior * @author Martin Buchholz + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/util/Map/FunctionalCMEs.java b/jdk/test/java/util/Map/FunctionalCMEs.java new file mode 100644 index 00000000000..499261bbf08 --- /dev/null +++ b/jdk/test/java/util/Map/FunctionalCMEs.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2015 Oracle and/or its affiliates. All rights reserved. + * 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. + */ +import java.util.Arrays; +import java.util.ConcurrentModificationException; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.BiFunction; + +import org.testng.annotations.Test; +import org.testng.annotations.DataProvider; + +/** + * @test + * @bug 8071667 + * @summary Ensure that ConcurrentModificationExceptions are thrown as specified from Map methods that accept Functions + * @author bchristi + * @build Defaults + * @run testng FunctionalCMEs + */ +public class FunctionalCMEs { + final static String KEY = "key"; + + @DataProvider(name = "Maps", parallel = true) + private static Iterator makeMaps() { + return Arrays.asList( + // Test maps that CME + new Object[]{new HashMap<>(), true}, + new Object[]{new Hashtable<>(), true}, + new Object[]{new LinkedHashMap<>(), true}, + // Test default Map methods - no CME + new Object[]{new Defaults.ExtendsAbstractMap<>(), false} + ).iterator(); + } + + @Test(dataProvider = "Maps") + public void testComputeIfAbsent(Map map, boolean expectCME) { + checkCME(() -> { + map.computeIfAbsent(KEY, k -> { + putToForceRehash(map); + return "computedValue"; + }); + }, expectCME); + } + + @Test(dataProvider = "Maps") + public void testCompute(Map map, boolean expectCME) { + checkCME(() -> { + map.compute(KEY, mkBiFunc(map)); + }, expectCME); + } + + @Test(dataProvider = "Maps") + public void testComputeWithKeyMapped(Map map, boolean expectCME) { + map.put(KEY, "firstValue"); + checkCME(() -> { + map.compute(KEY, mkBiFunc(map)); + }, expectCME); + } + + @Test(dataProvider = "Maps") + public void testComputeIfPresent(Map map, boolean expectCME) { + map.put(KEY, "firstValue"); + checkCME(() -> { + map.computeIfPresent(KEY, mkBiFunc(map)); + }, expectCME); + } + + @Test(dataProvider = "Maps") + public void testMerge(Map map, boolean expectCME) { + map.put(KEY, "firstValue"); + checkCME(() -> { + map.merge(KEY, "nextValue", mkBiFunc(map)); + }, expectCME); + } + + @Test(dataProvider = "Maps") + public void testForEach(Map map, boolean ignored) { + checkCME(() -> { + map.put(KEY, "firstValue"); + putToForceRehash(map); + map.forEach((k,v) -> { + map.remove(KEY); + }); + }, true); + } + + @Test(dataProvider = "Maps") + public void testReplaceAll(Map map, boolean ignored) { + checkCME(() -> { + map.put(KEY, "firstValue"); + putToForceRehash(map); + map.replaceAll((k,v) -> { + map.remove(KEY); + return "computedValue"; + }); + },true); + } + + private static void checkCME(Runnable code, boolean expectCME) { + try { + code.run(); + } catch (ConcurrentModificationException cme) { + if (expectCME) { return; } else { throw cme; } + } + if (expectCME) { + throw new RuntimeException("Expected CME, but wasn't thrown"); + } + } + + private static BiFunction mkBiFunc(Map map) { + return (k,v) -> { + putToForceRehash(map); + return "computedValue"; + }; + } + + private static void putToForceRehash(Map map) { + for (int i = 0; i < 64; ++i) { + map.put(i + "", "value"); + } + } +} diff --git a/jdk/test/java/util/Map/LockStep.java b/jdk/test/java/util/Map/LockStep.java index 35cf98b9d52..45754a2f644 100644 --- a/jdk/test/java/util/Map/LockStep.java +++ b/jdk/test/java/util/Map/LockStep.java @@ -25,6 +25,7 @@ * @test * @bug 6612102 * @summary Test Map implementations for mutual compatibility + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/NavigableMap/LockStep.java b/jdk/test/java/util/NavigableMap/LockStep.java index 62ffc72877d..94f2cb1c93e 100644 --- a/jdk/test/java/util/NavigableMap/LockStep.java +++ b/jdk/test/java/util/NavigableMap/LockStep.java @@ -29,6 +29,7 @@ * @run main/othervm -XX:+AggressiveOpts LockStep * @run main/othervm -XX:+AggressiveOpts -Dthorough=true LockStep * @author Martin Buchholz + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/util/PluggableLocale/ExecTest.sh b/jdk/test/java/util/PluggableLocale/ExecTest.sh index 7e8a5365f45..888f9348e51 100644 --- a/jdk/test/java/util/PluggableLocale/ExecTest.sh +++ b/jdk/test/java/util/PluggableLocale/ExecTest.sh @@ -1,6 +1,6 @@ #!/bin/sh # -# Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -33,7 +33,7 @@ # Parameters: # providersToTest: [foo|bar|foobar] # java class name: -# providersInExtDir: [true|false] +# java security policy file: (Optional. Installs security manager if exists) if [ "${TESTSRC}" = "" ] then @@ -113,8 +113,14 @@ else exit $result fi +# security options +if [ "$3" != "" ] +then + SECURITYOPTS="-Djava.security.manager -Djava.security.policy=${TESTSRC}${FS}$3" +fi + # run -RUNCMD="${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -classpath ${CLASSPATHARG} $2 " +RUNCMD="${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} ${SECURITYOPTS} -classpath ${CLASSPATHARG} $2 " echo ${RUNCMD} ${RUNCMD} diff --git a/jdk/test/java/util/PluggableLocale/PermissionTest.java b/jdk/test/java/util/PluggableLocale/PermissionTest.java new file mode 100644 index 00000000000..c70c5d195cb --- /dev/null +++ b/jdk/test/java/util/PluggableLocale/PermissionTest.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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. + */ +/* + * + */ +public class PermissionTest{ + + // Make sure provider impls can be instantiated under a security manager.ZZ + com.foo.BreakIteratorProviderImpl breakIP = new com.foo.BreakIteratorProviderImpl(); + com.foo.CollatorProviderImpl collatorP = new com.foo.CollatorProviderImpl(); + com.foo.DateFormatProviderImpl dateFP = new com.foo.DateFormatProviderImpl(); + com.foo.DateFormatSymbolsProviderImpl dateFSP = new com.foo.DateFormatSymbolsProviderImpl(); + com.foo.DecimalFormatSymbolsProviderImpl decimalFSP = new com.foo.DecimalFormatSymbolsProviderImpl(); + com.foo.NumberFormatProviderImpl numberFP = new com.foo.NumberFormatProviderImpl(); + com.bar.CurrencyNameProviderImpl currencyNP = new com.bar.CurrencyNameProviderImpl(); + com.bar.CurrencyNameProviderImpl2 currencyNP2 = new com.bar.CurrencyNameProviderImpl2(); + com.bar.LocaleNameProviderImpl localeNP = new com.bar.LocaleNameProviderImpl(); + com.bar.TimeZoneNameProviderImpl tzNP = new com.bar.TimeZoneNameProviderImpl(); + com.bar.GenericTimeZoneNameProviderImpl tzGenNP = new com.bar.GenericTimeZoneNameProviderImpl(); + com.bar.CalendarDataProviderImpl calDataP = new com.bar.CalendarDataProviderImpl(); + com.bar.CalendarNameProviderImpl calNameP = new com.bar.CalendarNameProviderImpl(); + + public static void main(String[] s) { + new PermissionTest(); + } +} diff --git a/jdk/test/java/util/PluggableLocale/PermissionTest.sh b/jdk/test/java/util/PluggableLocale/PermissionTest.sh new file mode 100644 index 00000000000..50a42f1ff3e --- /dev/null +++ b/jdk/test/java/util/PluggableLocale/PermissionTest.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# +# Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. +# 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 8075545 +# @summary Check whether RuntimePermission("localeServiceProvider") is +# handled correctly +# @run shell ExecTest.sh foobar PermissionTest +# @run shell/fail ExecTest.sh foobar PermissionTest dummy +# @run shell ExecTest.sh foobar PermissionTest localeServiceProvider.policy diff --git a/jdk/test/java/util/PluggableLocale/TimeZoneNameProviderTest.java b/jdk/test/java/util/PluggableLocale/TimeZoneNameProviderTest.java index edd991b4cd1..8eab9947dd7 100644 --- a/jdk/test/java/util/PluggableLocale/TimeZoneNameProviderTest.java +++ b/jdk/test/java/util/PluggableLocale/TimeZoneNameProviderTest.java @@ -25,6 +25,7 @@ */ import java.text.*; +import java.time.format.TextStyle; import java.util.*; import sun.util.locale.provider.*; import sun.util.resources.*; @@ -42,6 +43,7 @@ public class TimeZoneNameProviderTest extends ProviderTest { test2(); test3(); aliasTest(); + genericFallbackTest(); } void test1() { @@ -169,9 +171,9 @@ public class TimeZoneNameProviderTest extends ProviderTest { for (int style : new int[] { TimeZone.LONG, TimeZone.SHORT }) { String osakaStd = tz.getDisplayName(false, style, OSAKA); if (osakaStd != null) { - // No API for getting generic time zone names - String generic = TimeZoneNameUtility.retrieveGenericDisplayName(tzname, - style, GENERIC); + String generic = tz.toZoneId().getDisplayName( + style == TimeZone.LONG ? TextStyle.FULL : TextStyle.SHORT, + GENERIC); String expected = "Generic " + osakaStd; if (!expected.equals(generic)) { throw new RuntimeException("Wrong generic name: got=\"" + generic @@ -230,4 +232,20 @@ public class TimeZoneNameProviderTest extends ProviderTest { throw new RuntimeException("Provider's localized name is not available for an alias ID: "+JAPAN+". result: "+japan+" expected: "+JST_IN_OSAKA); } } + + /* + * Tests whether generic names can be retrieved through fallback. + * The test assumes the provider impl for OSAKA locale does NOT + * provide generic names. + */ + final String PT = "PT"; // SHORT generic name for "America/Los_Angeles" + void genericFallbackTest() { + String generic = + TimeZone.getTimeZone(LATIME) + .toZoneId() + .getDisplayName(TextStyle.SHORT, OSAKA); + if (!PT.equals(generic)) { + throw new RuntimeException("Generic name fallback failed. got: "+generic); + } + } } diff --git a/jdk/test/java/util/PluggableLocale/localeServiceProvider.policy b/jdk/test/java/util/PluggableLocale/localeServiceProvider.policy new file mode 100644 index 00000000000..4a5d969c0b0 --- /dev/null +++ b/jdk/test/java/util/PluggableLocale/localeServiceProvider.policy @@ -0,0 +1,3 @@ +grant { + permission java.lang.RuntimePermission "localeServiceProvider"; +}; diff --git a/jdk/test/java/util/Properties/ConcurrentLoadAndStoreXML.java b/jdk/test/java/util/Properties/ConcurrentLoadAndStoreXML.java index 7bb187c228c..ed573a46a67 100644 --- a/jdk/test/java/util/Properties/ConcurrentLoadAndStoreXML.java +++ b/jdk/test/java/util/Properties/ConcurrentLoadAndStoreXML.java @@ -25,6 +25,7 @@ * @bug 8005281 * @summary Test that the Properties storeToXML and loadFromXML methods are * thread safe + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/util/Properties/Basic.java b/jdk/test/java/util/Properties/LoadAndStoreNPE.java similarity index 91% rename from jdk/test/java/util/Properties/Basic.java rename to jdk/test/java/util/Properties/LoadAndStoreNPE.java index 7827ed02957..5050139007a 100644 --- a/jdk/test/java/util/Properties/Basic.java +++ b/jdk/test/java/util/Properties/LoadAndStoreNPE.java @@ -28,10 +28,10 @@ import java.util.Properties; /* * @test - * @bug 8073214 - * @summary Basic tests of Properties methods. + * @bug 8073214 8075362 + * @summary Tests to verify that load() and store() throw NPEs as advertised. */ -public class Basic +public class LoadAndStoreNPE { public static void main(String[] args) throws Exception { @@ -68,7 +68,7 @@ public class Basic } if (failures != 0) { - throw new RuntimeException("Basic failed with " + throw new RuntimeException("LoadAndStoreNPE failed with " + failures + " errors!"); } } diff --git a/jdk/test/java/util/Random/DistinctSeeds.java b/jdk/test/java/util/Random/DistinctSeeds.java index fd2bcfcb658..ddd541b3c60 100644 --- a/jdk/test/java/util/Random/DistinctSeeds.java +++ b/jdk/test/java/util/Random/DistinctSeeds.java @@ -35,6 +35,7 @@ * @test * @bug 4949279 6937857 * @summary Independent instantiations of Random() have distinct seeds. + * @key randomness */ import java.util.ArrayList; diff --git a/jdk/test/java/util/Random/RandomStreamTest.java b/jdk/test/java/util/Random/RandomStreamTest.java index e96d57e2639..269fec8045e 100644 --- a/jdk/test/java/util/Random/RandomStreamTest.java +++ b/jdk/test/java/util/Random/RandomStreamTest.java @@ -47,6 +47,7 @@ import static org.testng.Assert.*; * @run testng RandomStreamTest * @summary test stream methods on Random * @author Brian Goetz + * @key randomness */ public class RandomStreamTest { diff --git a/jdk/test/java/util/Random/RandomTest.java b/jdk/test/java/util/Random/RandomTest.java index e56ffde1961..3055f5cbbcb 100644 --- a/jdk/test/java/util/Random/RandomTest.java +++ b/jdk/test/java/util/Random/RandomTest.java @@ -35,6 +35,7 @@ import static org.testng.Assert.*; * @test * @run testng RandomTest * @summary test methods on Random + * @key randomness */ @Test public class RandomTest { diff --git a/jdk/test/java/util/ResourceBundle/Control/StressTest.java b/jdk/test/java/util/ResourceBundle/Control/StressTest.java index abead81d2e5..9766606fba9 100644 --- a/jdk/test/java/util/ResourceBundle/Control/StressTest.java +++ b/jdk/test/java/util/ResourceBundle/Control/StressTest.java @@ -25,6 +25,7 @@ * @bug 5102289 * @summary Stress test for ResourceBundle.getBundle with ResourceBundle.Control. * @run main/othervm -esa StressTest 2 15 + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/SplittableRandom/SplittableRandomTest.java b/jdk/test/java/util/SplittableRandom/SplittableRandomTest.java index 57e1a3434a3..c2e97c1612c 100644 --- a/jdk/test/java/util/SplittableRandom/SplittableRandomTest.java +++ b/jdk/test/java/util/SplittableRandom/SplittableRandomTest.java @@ -39,6 +39,7 @@ import static org.testng.AssertJUnit.assertTrue; * @run testng SplittableRandomTest * @run testng/othervm -Djava.util.secureRandomSeed=true SplittableRandomTest * @summary test methods on SplittableRandom + * @key randomness */ @Test public class SplittableRandomTest { diff --git a/jdk/test/java/util/Timer/DelayOverflow.java b/jdk/test/java/util/Timer/DelayOverflow.java index b72a155e1b5..bf36bcc5705 100644 --- a/jdk/test/java/util/Timer/DelayOverflow.java +++ b/jdk/test/java/util/Timer/DelayOverflow.java @@ -27,6 +27,7 @@ * @summary java.util.Timer schedule delay Long.MAX_VALUE causes task to execute multiple times * @author Chris Hegarty * @author Martin Buchholz + * @key randomness */ import java.util.Date; diff --git a/jdk/test/java/util/Timer/Purge.java b/jdk/test/java/util/Timer/Purge.java index 69c92881776..b753ec81bcd 100644 --- a/jdk/test/java/util/Timer/Purge.java +++ b/jdk/test/java/util/Timer/Purge.java @@ -25,6 +25,7 @@ * @test * @bug 4481072 * @summary Basic test for purge method + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/UUID/Serial.java b/jdk/test/java/util/UUID/Serial.java index 4a6d2714135..97badcc34ac 100644 --- a/jdk/test/java/util/UUID/Serial.java +++ b/jdk/test/java/util/UUID/Serial.java @@ -25,6 +25,7 @@ * @test * @bug 5014447 * @summary Test deserialization of UUID + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/util/UUID/UUIDTest.java b/jdk/test/java/util/UUID/UUIDTest.java index 93ad7ad3490..06b240fa9fa 100644 --- a/jdk/test/java/util/UUID/UUIDTest.java +++ b/jdk/test/java/util/UUID/UUIDTest.java @@ -24,6 +24,7 @@ /* @test * @bug 4173528 5068772 * @summary Unit tests for java.util.UUID + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/WeakHashMap/GCDuringIteration.java b/jdk/test/java/util/WeakHashMap/GCDuringIteration.java index 4744ecce181..a66ad9580d7 100644 --- a/jdk/test/java/util/WeakHashMap/GCDuringIteration.java +++ b/jdk/test/java/util/WeakHashMap/GCDuringIteration.java @@ -27,6 +27,7 @@ * @ignore until 6842353 is resolved * @summary Check that iterators work properly in the presence of * concurrent finalization and removal of elements. + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/concurrent/forkjoin/SubmissionTest.java b/jdk/test/java/util/concurrent/forkjoin/SubmissionTest.java new file mode 100644 index 00000000000..5a3db577ddd --- /dev/null +++ b/jdk/test/java/util/concurrent/forkjoin/SubmissionTest.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/* + * @test + * @bug 8078490 + * @summary Test submission and execution of task without joining + */ +public class SubmissionTest { + public static void main(String[] args) throws Throwable { + final ForkJoinPool e = new ForkJoinPool(1); + final AtomicBoolean b = new AtomicBoolean(); + final Runnable setFalse = () -> b.set(false); + for (int i = 0; i < 100000; i++) { + b.set(true); + e.execute(setFalse); + long st = System.nanoTime(); + while (b.get()) { + if (System.nanoTime() - st >= TimeUnit.SECONDS.toNanos(10)) { + throw new RuntimeException("Submitted task failed to execute"); + } + } + } + } +} diff --git a/jdk/test/java/util/logging/CheckZombieLockTest.java b/jdk/test/java/util/logging/CheckZombieLockTest.java index ab65a814f0b..16909532ceb 100644 --- a/jdk/test/java/util/logging/CheckZombieLockTest.java +++ b/jdk/test/java/util/logging/CheckZombieLockTest.java @@ -37,6 +37,7 @@ * @run main/othervm CheckZombieLockTest CLEANUP * @run main/othervm CheckZombieLockTest REUSE * @run main/othervm CheckZombieLockTest CLEANUP + * @key randomness */ import java.io.File; import java.io.IOException; diff --git a/jdk/test/java/util/logging/DrainFindDeadlockTest.java b/jdk/test/java/util/logging/DrainFindDeadlockTest.java index 13a959c07ff..6d0bd084346 100644 --- a/jdk/test/java/util/logging/DrainFindDeadlockTest.java +++ b/jdk/test/java/util/logging/DrainFindDeadlockTest.java @@ -36,6 +36,7 @@ import java.util.Map; * @author jim.gish@oracle.com * @build DrainFindDeadlockTest * @run main/othervm/timeout=10 DrainFindDeadlockTest + * @key randomness */ /** diff --git a/jdk/test/java/util/logging/FileHandlerLongLimit.java b/jdk/test/java/util/logging/FileHandlerLongLimit.java index 67e4001fb81..0aa2fc04641 100644 --- a/jdk/test/java/util/logging/FileHandlerLongLimit.java +++ b/jdk/test/java/util/logging/FileHandlerLongLimit.java @@ -55,6 +55,7 @@ import java.util.logging.LoggingPermission; * @run main/othervm FileHandlerLongLimit UNSECURE * @run main/othervm FileHandlerLongLimit SECURE * @author danielfuchs + * @key randomness */ public class FileHandlerLongLimit { diff --git a/jdk/test/java/util/logging/FileHandlerPath.java b/jdk/test/java/util/logging/FileHandlerPath.java index 93859091c9b..602d4cf9c7d 100644 --- a/jdk/test/java/util/logging/FileHandlerPath.java +++ b/jdk/test/java/util/logging/FileHandlerPath.java @@ -56,6 +56,7 @@ import java.util.logging.LoggingPermission; * @run main/othervm FileHandlerPath UNSECURE * @run main/othervm FileHandlerPath SECURE * @author danielfuchs + * @key randomness */ public class FileHandlerPath { diff --git a/jdk/test/java/util/logging/FileHandlerPatternExceptions.java b/jdk/test/java/util/logging/FileHandlerPatternExceptions.java index a4026d9bde9..fdcafa04c57 100644 --- a/jdk/test/java/util/logging/FileHandlerPatternExceptions.java +++ b/jdk/test/java/util/logging/FileHandlerPatternExceptions.java @@ -49,6 +49,7 @@ import java.util.logging.LogManager; * @run main/othervm FileHandlerPatternExceptions UNSECURE * @run main/othervm FileHandlerPatternExceptions SECURE * @author danielfuchs + * @key randomness */ public class FileHandlerPatternExceptions { diff --git a/jdk/test/java/util/logging/LogManager/Configuration/InvalidEscapeConfigurationTest.java b/jdk/test/java/util/logging/LogManager/Configuration/InvalidEscapeConfigurationTest.java new file mode 100644 index 00000000000..62ca74b1477 --- /dev/null +++ b/jdk/test/java/util/logging/LogManager/Configuration/InvalidEscapeConfigurationTest.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.io.UnsupportedEncodingException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Properties; +import java.util.logging.LogManager; + + +/** + * @test + * @bug 8075810 + * @run main/othervm InvalidEscapeConfigurationTest + * @author danielfuchs + */ +public class InvalidEscapeConfigurationTest { + + public static void main(String[] args) + throws UnsupportedEncodingException, IOException { + String[] validEscapes = { + "com.f\\u006fo.level = INF\\u004f", + "com.f\\u006fo.level = INFO", + "com.foo.level = INF\\u004f" + }; + String[] invalidEscapes = { + "com.fo\\u0O6f.level = INF\\u0O4f", + "com.fo\\u0O6f.level = INFO", + "com.foo.level = INF\\u0O4f" + }; + for (String line : validEscapes) { + test(line, true); + } + for (String line : invalidEscapes) { + test(line, false); + } + try { + Properties props = new Properties(); + props.load((InputStream)null); + throw new RuntimeException("Properties.load(null): " + + "NullPointerException exception not raised"); + } catch (NullPointerException x) { + System.out.println("Properties.load(null): " + + "got expected exception: " + x); + } + try { + LogManager.getLogManager().readConfiguration(null); + throw new RuntimeException("LogManager.readConfiguration(null): " + + "NullPointerException exception not raised"); + } catch (NullPointerException x) { + System.out.println("LogManager.readConfiguration(null): " + + "got expected exception: " + x); + } + + + } + + public static void test(String line, boolean valid) throws IOException { + String test = (valid ? "valid" : "invalid") + + " line \"" +line + "\""; + System.out.println("Testing " + test); + + // First verify that we get the expected result from Properties.load() + try { + ByteArrayInputStream bais = + new ByteArrayInputStream(line.getBytes("UTF-8")); + Properties props = new Properties(); + props.load(bais); + if (!valid) { + throw new RuntimeException(test + + "\n\tProperties.load: expected exception not raised"); + } else { + System.out.println("Properties.load passed for " + test); + } + } catch(IllegalArgumentException x) { + if (!valid) { + System.out.println( + "Properties.load: Got expected exception: " + + x + "\n\tfor " + test); + } else { + throw x; + } + } + + // Then verify that we get the expected result from + // LogManager.readConfiguration + try { + String content = defaultConfiguration() + '\n' + line + '\n'; + ByteArrayInputStream bais = + new ByteArrayInputStream(content.getBytes("UTF-8")); + LogManager.getLogManager().readConfiguration(bais); + if (!valid) { + throw new RuntimeException(test + + "\n\tLogManager.readConfiguration: " + + "expected exception not raised"); + } else { + System.out.println("LogManager.readConfiguration passed for " + + test); + } + } catch(IOException x) { + if (!valid) { + System.out.println( + "LogManager.readConfiguration: Got expected exception: " + + x + "\n\tfor " + test); + } else { + throw x; + } + } + } + + static String getConfigurationFileName() { + String fname = System.getProperty("java.util.logging.config.file"); + if (fname == null) { + fname = System.getProperty("java.home"); + if (fname == null) { + throw new Error("Can't find java.home ??"); + } + fname = Paths.get(fname, "conf", "logging.properties") + .toAbsolutePath().normalize().toString(); + } + return fname; + } + + static String defaultConfiguration() throws IOException { + Properties props = new Properties(); + String fileName = getConfigurationFileName(); + if (Files.exists(Paths.get(fileName))) { + try (InputStream is = new FileInputStream(fileName);) { + props.load(is); + } catch(IOException x) { + throw new UncheckedIOException(x); + } + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + props.store(bos, null); + return bos.toString(); + } + +} diff --git a/jdk/test/java/util/logging/LogManager/Configuration/ParentLoggerWithHandlerGC.java b/jdk/test/java/util/logging/LogManager/Configuration/ParentLoggerWithHandlerGC.java index 491d7583243..38a6c56cbd5 100644 --- a/jdk/test/java/util/logging/LogManager/Configuration/ParentLoggerWithHandlerGC.java +++ b/jdk/test/java/util/logging/LogManager/Configuration/ParentLoggerWithHandlerGC.java @@ -59,6 +59,7 @@ import java.util.logging.LoggingPermission; * @run main/othervm ParentLoggerWithHandlerGC UNSECURE * @run main/othervm ParentLoggerWithHandlerGC SECURE * @author danielfuchs + * @key randomness */ public class ParentLoggerWithHandlerGC { diff --git a/jdk/test/java/util/logging/LogManager/TestLoggerNames.java b/jdk/test/java/util/logging/LogManager/TestLoggerNames.java new file mode 100644 index 00000000000..0ddb2fd1557 --- /dev/null +++ b/jdk/test/java/util/logging/LogManager/TestLoggerNames.java @@ -0,0 +1,239 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.util.Collections; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Phaser; +import java.util.concurrent.Semaphore; +import java.util.logging.Handler; +import java.util.logging.LogManager; +import java.util.logging.Logger; + + +/** + * @test + * @bug 7113878 + * @summary This is not a test that will check that 7113878 is fixed, but + * rather a test that will invoke the modified code & try to verify + * that fixing 7113878 has not introduced some big regression. + * This test should pass, whether 7113878 is there or not. + * @run main/othervm TestLoggerNames + * @author danielfuchs + */ +public class TestLoggerNames { + + static final class TestLogger extends java.util.logging.Logger { + + final Semaphore sem = new Semaphore(0); + final Semaphore wait = new Semaphore(0); + + public TestLogger(String name, String resourceBundleName) { + super(name, resourceBundleName); + } + + @Override + public Handler[] getHandlers() { + boolean found = false; + try { + System.out.println("Entering "+getName()+" getHandlers()"); + for (StackTraceElement ste : Thread.currentThread().getStackTrace()) { + if (LogManager.class.getName().equals(ste.getClassName()) + && "reset".equals(ste.getMethodName())) { + found = true; + System.out.println(getName()+" getHandlers() called by " + ste); + } + } + sem.release(); + try { + System.out.println("TestLogger: Acquiring wait for "+getName()); + wait.acquire(); + try { + System.out.println("TestLogger: Acquired wait for "+getName()); + return super.getHandlers(); + } finally { + System.out.println("TestLogger: Releasing wait for "+getName()); + wait.release(); + } + } finally { + System.out.println("Unblocking "+getName()); + sem.acquire(); + System.out.println("Unblocked "+getName()); + if (found) { + System.out.println("Reset will proceed..."); + } + } + } catch (InterruptedException x) { + throw new IllegalStateException(x); + } + } + } + + static volatile boolean stop; + static volatile Throwable resetFailed; + static volatile Throwable checkLoggerNamesFailed; + static volatile Phaser phaser = new Phaser(2); + + + static void checkLoggerNames(List loggers) { + Enumeration names = LogManager.getLogManager().getLoggerNames(); + if (names instanceof Iterator) { + for (Iterator it = Iterator.class.cast(names); it.hasNext(); ) { + try { + it.remove(); + throw new RuntimeException("Iterator supports remove!"); + } catch (UnsupportedOperationException x) { + System.out.println("OK: Iterator doesn't support remove."); + } + } + } + List loggerNames = Collections.list(names); + if (!loggerNames.contains("")) { + throw new RuntimeException("\"\"" + + " not found in " + loggerNames); + } + if (!loggerNames.contains("global")) { + throw new RuntimeException("global" + + " not found in " + loggerNames); + } + for (Logger l : loggers) { + if (!loggerNames.contains(l.getName())) { + throw new RuntimeException(l.getName() + + " not found in " + loggerNames); + } + } + System.out.println("Got all expected logger names"); + } + + + public static void main(String[] args) throws InterruptedException { + LogManager.getLogManager().addLogger(new TestLogger("com.foo.bar.zzz", null)); + try { + Logger.getLogger(null); + throw new RuntimeException("Logger.getLogger(null) didn't throw expected NPE"); + } catch (NullPointerException x) { + System.out.println("Got expected NullPointerException for Logger.getLogger(null)"); + } + List loggers = new CopyOnWriteArrayList<>(); + loggers.add(Logger.getLogger("one.two.addMeAChild")); + loggers.add(Logger.getLogger("aaa.bbb.replaceMe")); + loggers.add(Logger.getLogger("bbb.aaa.addMeAChild")); + TestLogger test = (TestLogger)Logger.getLogger("com.foo.bar.zzz"); + loggers.add(Logger.getLogger("ddd.aaa.addMeAChild")); + + checkLoggerNames(loggers); + + Thread loggerNamesThread = new Thread(() -> { + try { + while (!stop) { + checkLoggerNames(loggers); + Thread.sleep(10); + if (!stop) { + phaser.arriveAndAwaitAdvance(); + } + } + } catch (Throwable t) { + t.printStackTrace(System.err); + checkLoggerNamesFailed = t; + } + }, "loggerNames"); + + Thread resetThread = new Thread(() -> { + try { + System.out.println("Calling reset..."); + LogManager.getLogManager().reset(); + System.out.println("Reset done..."); + System.out.println("Reset again..."); + LogManager.getLogManager().reset(); + System.out.println("Reset done..."); + } catch(Throwable t) { + resetFailed = t; + System.err.println("Unexpected exception or error in reset Thread"); + t.printStackTrace(System.err); + } + }, "reset"); + + resetThread.setDaemon(true); + resetThread.start(); + + System.out.println("Waiting for reset to get handlers"); + test.sem.acquire(); + try { + loggerNamesThread.start(); + System.out.println("Reset has called getHandlers on " + test.getName()); + int i = 0; + for (Enumeration e = LogManager.getLogManager().getLoggerNames(); + e.hasMoreElements();) { + String name = e.nextElement(); + if (name.isEmpty()) continue; + if (name.endsWith(".addMeAChild")) { + Logger l = Logger.getLogger(name+".child"); + loggers.add(l); + System.out.println("*** Added " + l.getName()); + i++; + } else if (name.endsWith("replaceMe")) { + Logger l = Logger.getLogger(name); + loggers.remove(l); + l = Logger.getLogger(name.replace("replaceMe", "meReplaced")); + loggers.add(l); + System.gc(); + if (LogManager.getLogManager().getLogger(name) == null) { + System.out.println("*** "+ name + " successfully replaced with " + l.getName()); + } + i++; + } else { + System.out.println("Nothing to do for logger: " + name); + } + phaser.arriveAndAwaitAdvance(); + if (i >= 3 && i++ == 3) { + System.out.println("Loggers are now: " + + Collections.list(LogManager.getLogManager().getLoggerNames())); + test.wait.release(); + test.sem.release(); + System.out.println("Joining " + resetThread); + resetThread.join(); + } + } + } catch (RuntimeException | InterruptedException | Error x) { + test.wait.release(); + test.sem.release(); + throw x; + } finally { + stop = true; + phaser.arriveAndDeregister(); + loggerNamesThread.join(); + loggers.clear(); + } + + + if (resetFailed != null || checkLoggerNamesFailed != null) { + RuntimeException r = new RuntimeException("Some of the concurrent threads failed"); + if (resetFailed != null) r.addSuppressed(resetFailed); + if (checkLoggerNamesFailed != null) r.addSuppressed(checkLoggerNamesFailed); + throw r; + } + + } + +} diff --git a/jdk/test/java/util/logging/LoggingDeadlock.java b/jdk/test/java/util/logging/LoggingDeadlock.java index 41c9e8b3d05..131c92942f7 100644 --- a/jdk/test/java/util/logging/LoggingDeadlock.java +++ b/jdk/test/java/util/logging/LoggingDeadlock.java @@ -30,6 +30,10 @@ * * @build LoggingDeadlock * @run main/timeout=15 LoggingDeadlock + * @key randomness + */ + +/* * * There can be a deadlock between two class initializations. * It happens if the LogManager. and the Logger. diff --git a/jdk/test/java/util/logging/LoggingDeadlock2.java b/jdk/test/java/util/logging/LoggingDeadlock2.java index c5b4e893738..b33a25191fc 100644 --- a/jdk/test/java/util/logging/LoggingDeadlock2.java +++ b/jdk/test/java/util/logging/LoggingDeadlock2.java @@ -29,6 +29,10 @@ * * @build LoggingDeadlock2 * @run main LoggingDeadlock2 + * @key randomness + */ + +/* * * There is a clear deadlock between LogManager. and * Cleaner.run() methods. diff --git a/jdk/test/java/util/logging/TestLogConfigurationDeadLockWithConf.java b/jdk/test/java/util/logging/TestLogConfigurationDeadLockWithConf.java index 9bde8d516fc..af8651d38b3 100644 --- a/jdk/test/java/util/logging/TestLogConfigurationDeadLockWithConf.java +++ b/jdk/test/java/util/logging/TestLogConfigurationDeadLockWithConf.java @@ -46,6 +46,7 @@ import java.util.logging.Logger; * caused by synchronization issues in Logger and LogManager. * @run main/othervm TestLogConfigurationDeadLockWithConf * @author danielfuchs + * @key randomness */ // This test is a best effort to try & detect issues. The test itself will run // for 8secs. This is usually sufficient to detect issues. diff --git a/jdk/test/java/util/prefs/CodePointZeroPrefsTest.java b/jdk/test/java/util/prefs/CodePointZeroPrefsTest.java index eb7299b4d98..79fe3f3fb87 100644 --- a/jdk/test/java/util/prefs/CodePointZeroPrefsTest.java +++ b/jdk/test/java/util/prefs/CodePointZeroPrefsTest.java @@ -26,9 +26,8 @@ import java.util.prefs.PreferencesFactory; /* * @test - * @bug 8068373 - * @requires os.family == "linux" | os.family == "solaris" - * @summary Ensure writing a code point U+0000 null control character is detected. + * @bug 8068373 8075110 8075156 + * @summary Ensure a code point U+0000 null control character is detected. */ public class CodePointZeroPrefsTest { @@ -36,52 +35,70 @@ public class CodePointZeroPrefsTest { int failures = 0; - // Deliberately reflect so you can reproduce it on any platform. - Constructor constructor = - Class.forName("java.util.prefs.FileSystemPreferencesFactory").asSubclass(PreferencesFactory.class).getDeclaredConstructor(); - constructor.setAccessible(true); - PreferencesFactory factory = constructor.newInstance(); + Preferences node = Preferences.userRoot().node("com/acme/testing"); - Preferences node = factory.userRoot().node("com/acme/testing"); + // --- put() --- // legal key and value try { node.put("a", "1"); } catch (IllegalArgumentException iae) { - System.err.println("Unexpected IllegalArgumentException for legal key"); + System.err.println("Unexpected IllegalArgumentException for legal put() key"); failures++; } // illegal key only - int numIAEs = 0; try { node.put("a\u0000b", "1"); - System.err.println("IllegalArgumentException not thrown for illegal key"); + System.err.println("IllegalArgumentException not thrown for illegal put() key"); failures++; } catch (IllegalArgumentException iae) { // do nothing } // illegal value only - numIAEs = 0; try { node.put("ab", "2\u00003"); - System.err.println("IllegalArgumentException not thrown for illegal value"); + System.err.println("IllegalArgumentException not thrown for illegal put() value"); failures++; } catch (IllegalArgumentException iae) { // do nothing } // illegal key and value - numIAEs = 0; try { node.put("a\u0000b", "2\u00003"); - System.err.println("IllegalArgumentException not thrown for illegal entry"); + System.err.println("IllegalArgumentException not thrown for illegal put() entry"); failures++; } catch (IllegalArgumentException iae) { // do nothing } + // --- get --- + + // illegal key only + try { + String theDefault = "default"; + String value = node.get("a\u0000b", theDefault); + System.err.println("IllegalArgumentException not thrown for illegal get() key"); + failures++; + } catch (IllegalArgumentException iae) { + // do nothing + } + + // --- remove --- + + // illegal key only + try { + node.remove("a\u0000b"); + System.err.println("IllegalArgumentException not thrown for illegal remove() key"); + failures++; + } catch (IllegalArgumentException iae) { + // do nothing + } + + node.removeNode(); + if (failures != 0) { throw new RuntimeException("CodePointZeroPrefsTest failed with " + failures + " errors!"); diff --git a/jdk/test/java/util/regex/RegExTest.java b/jdk/test/java/util/regex/RegExTest.java index f04f6f1e8c7..488b431b257 100644 --- a/jdk/test/java/util/regex/RegExTest.java +++ b/jdk/test/java/util/regex/RegExTest.java @@ -33,6 +33,7 @@ * 6350801 6676425 6878475 6919132 6931676 6948903 6990617 7014645 7039066 * 7067045 7014640 7189363 8007395 8013252 8013254 8012646 8023647 6559590 * 8027645 8035076 8039124 8035975 8074678 + * @key randomness */ import java.util.function.Function; diff --git a/jdk/test/java/util/stream/boottest/java/util/stream/UnorderedTest.java b/jdk/test/java/util/stream/boottest/java/util/stream/UnorderedTest.java index 47eb533d8a2..4254b15765f 100644 --- a/jdk/test/java/util/stream/boottest/java/util/stream/UnorderedTest.java +++ b/jdk/test/java/util/stream/boottest/java/util/stream/UnorderedTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -251,7 +251,7 @@ public class UnorderedTest extends OpTestCase { final int lastLimitIndex = l; return s -> { - if (lastLimitIndex == -1) + if (lastLimitIndex == -1 && fs.size() > 0) s = fi.apply(s); for (int i = 0; i < fs.size(); i++) { s = fs.get(i).apply(s); diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/CountTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/CountTest.java index 0ed5ddc1a17..41f6ecf00b9 100644 --- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/CountTest.java +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/CountTest.java @@ -24,11 +24,12 @@ /** * @test * @summary Tests counting of streams - * @bug 8031187 8067969 + * @bug 8031187 8067969 8075307 */ package org.openjdk.tests.java.util.stream; +import java.util.HashSet; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.DoubleStream; import java.util.stream.DoubleStreamTestDataProvider; @@ -59,6 +60,19 @@ public class CountTest extends OpTestCase { terminal(s -> s.filter(e -> true), Stream::count). expectedResult(expectedCount). exercise(); + + // Test with stateful distinct op that is a barrier or lazy + // depending if source is not already distinct and encounter order is + // preserved or not + expectedCount = data.into(new HashSet<>()).size(); + withData(data). + terminal(Stream::distinct, Stream::count). + expectedResult(expectedCount). + exercise(); + withData(data). + terminal(s -> s.unordered().distinct(), Stream::count). + expectedResult(expectedCount). + exercise(); } @Test(dataProvider = "IntStreamTestData", dataProviderClass = IntStreamTestDataProvider.class) @@ -74,6 +88,16 @@ public class CountTest extends OpTestCase { terminal(s -> s.filter(e -> true), IntStream::count). expectedResult(expectedCount). exercise(); + + expectedCount = data.into(new HashSet<>()).size(); + withData(data). + terminal(IntStream::distinct, IntStream::count). + expectedResult(expectedCount). + exercise(); + withData(data). + terminal(s -> s.unordered().distinct(), IntStream::count). + expectedResult(expectedCount). + exercise(); } @Test(dataProvider = "LongStreamTestData", dataProviderClass = LongStreamTestDataProvider.class) @@ -89,6 +113,16 @@ public class CountTest extends OpTestCase { terminal(s -> s.filter(e -> true), LongStream::count). expectedResult(expectedCount). exercise(); + + expectedCount = data.into(new HashSet<>()).size(); + withData(data). + terminal(LongStream::distinct, LongStream::count). + expectedResult(expectedCount). + exercise(); + withData(data). + terminal(s -> s.unordered().distinct(), LongStream::count). + expectedResult(expectedCount). + exercise(); } @Test(dataProvider = "DoubleStreamTestData", dataProviderClass = DoubleStreamTestDataProvider.class) @@ -104,6 +138,16 @@ public class CountTest extends OpTestCase { terminal(s -> s.filter(e -> true), DoubleStream::count). expectedResult(expectedCount). exercise(); + + expectedCount = data.into(new HashSet<>()).size(); + withData(data). + terminal(DoubleStream::distinct, DoubleStream::count). + expectedResult(expectedCount). + exercise(); + withData(data). + terminal(s -> s.unordered().distinct(), DoubleStream::count). + expectedResult(expectedCount). + exercise(); } public void testNoEvaluationForSizedStream() { @@ -111,24 +155,36 @@ public class CountTest extends OpTestCase { AtomicInteger ai = new AtomicInteger(); Stream.of(1, 2, 3, 4).peek(e -> ai.getAndIncrement()).count(); assertEquals(ai.get(), 0); + + Stream.of(1, 2, 3, 4).peek(e -> ai.getAndIncrement()).parallel().count(); + assertEquals(ai.get(), 0); } { AtomicInteger ai = new AtomicInteger(); IntStream.of(1, 2, 3, 4).peek(e -> ai.getAndIncrement()).count(); assertEquals(ai.get(), 0); + + IntStream.of(1, 2, 3, 4).peek(e -> ai.getAndIncrement()).parallel().count(); + assertEquals(ai.get(), 0); } { AtomicInteger ai = new AtomicInteger(); LongStream.of(1, 2, 3, 4).peek(e -> ai.getAndIncrement()).count(); assertEquals(ai.get(), 0); + + LongStream.of(1, 2, 3, 4).peek(e -> ai.getAndIncrement()).parallel().count(); + assertEquals(ai.get(), 0); } { AtomicInteger ai = new AtomicInteger(); DoubleStream.of(1, 2, 3, 4).peek(e -> ai.getAndIncrement()).count(); assertEquals(ai.get(), 0); + + DoubleStream.of(1, 2, 3, 4).peek(e -> ai.getAndIncrement()).parallel().count(); + assertEquals(ai.get(), 0); } } } diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/DistinctOpTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/DistinctOpTest.java index 69432cfedf6..89f762010ee 100644 --- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/DistinctOpTest.java +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/DistinctOpTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -128,7 +128,7 @@ public class DistinctOpTest extends OpTestCase { @Test(dataProvider = "StreamTestData", dataProviderClass = StreamTestDataProvider.class) public void testDistinctDistinct(String name, TestData.OfRef data) { Collection result = withData(data) - .stream(s -> s.distinct().distinct(), new CollectorOps.TestParallelSizedOp<>()) + .stream(s -> s.distinct().distinct()) .exercise(); assertUnique(result); } diff --git a/jdk/test/java/util/zip/3GBZipFiles.sh b/jdk/test/java/util/zip/3GBZipFiles.sh index 7661b8445d2..a03290f9cae 100644 --- a/jdk/test/java/util/zip/3GBZipFiles.sh +++ b/jdk/test/java/util/zip/3GBZipFiles.sh @@ -29,6 +29,7 @@ # @run shell 3GBZipFiles.sh 9986 # @ignore runs for hours and eats up 7 Gigabytes of disk space # @run shell/timeout=604800 3GBZipFiles.sh 3141592653 +# @key randomness # Command-line usage: # javac FileBuilder.java && sh 3GBZipFiles.sh /path/to/jdk filesize diff --git a/jdk/test/java/util/zip/DeInflate.java b/jdk/test/java/util/zip/DeInflate.java index c3ca7acf71f..886c9d4bc47 100644 --- a/jdk/test/java/util/zip/DeInflate.java +++ b/jdk/test/java/util/zip/DeInflate.java @@ -25,6 +25,7 @@ * @test * @bug 7110149 * @summary Test basic deflater & inflater functionality + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/util/zip/DeflateIn_InflateOut.java b/jdk/test/java/util/zip/DeflateIn_InflateOut.java index 29edda840ef..dd69a7773eb 100644 --- a/jdk/test/java/util/zip/DeflateIn_InflateOut.java +++ b/jdk/test/java/util/zip/DeflateIn_InflateOut.java @@ -25,6 +25,7 @@ * @test * @bug 4679743 * @summary Test basic functionality of DeflaterInputStream and InflaterOutputStream + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/util/zip/EntryCount64k.java b/jdk/test/java/util/zip/EntryCount64k.java index c815efdded6..b59980f53ec 100644 --- a/jdk/test/java/util/zip/EntryCount64k.java +++ b/jdk/test/java/util/zip/EntryCount64k.java @@ -24,33 +24,76 @@ /** * @test * @summary Test java.util.zip behavior with ~64k entries + * @library /lib/testlibrary * @run main/othervm EntryCount64k * @run main/othervm -Djdk.util.zip.inhibitZip64=true EntryCount64k * @run main/othervm -Djdk.util.zip.inhibitZip64=false EntryCount64k */ -import java.io.*; -import java.util.*; -import java.util.zip.*; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.nio.file.Files; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.RandomAccessFile; +import java.nio.file.Paths; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + +import jdk.testlibrary.OutputAnalyzer; +import jdk.testlibrary.ProcessTools; public class EntryCount64k { + public static class Main { + public static void main(String[] args) { + System.out.print("Main"); + } + } - public static void main(String[] args) throws Exception { - for (int i = (1 << 16) - 2; i < (1 << 16) + 2; i++) + static final String MAIN_CLASS = "EntryCount64k$Main"; + static final String THIS_CLASS = "EntryCount64k"; + static final String[] SPECIAL_CLASSES = { MAIN_CLASS, THIS_CLASS }; + // static final String[] SPECIAL_CLASSES = { MAIN_CLASS }; + static final int SPECIAL_COUNT = 1 + SPECIAL_CLASSES.length; + + public static void main(String[] args) throws Throwable { + for (int i = (1 << 16) - 3; i < (1 << 16) + 2; i++) test(i); } - static void test(int entryCount) throws Exception { + static void test(int entryCount) throws Throwable { File zipFile = new File("EntryCount64k-tmp.zip"); zipFile.delete(); - try (ZipOutputStream zos = - new ZipOutputStream( - new BufferedOutputStream( - new FileOutputStream(zipFile)))) { - for (int i = 0; i < entryCount; i++) { - ZipEntry e = new ZipEntry(Integer.toString(i)); - zos.putNextEntry(e); + try (FileOutputStream fos = new FileOutputStream(zipFile); + BufferedOutputStream bos = new BufferedOutputStream(fos); + ZipOutputStream zos = new ZipOutputStream(bos)) { + + // Add entries to allow the zip file to be used with "java -jar" + zos.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF")); + for (String line : new String[] { + "Manifest-Version: 1.0", + "Main-Class: " + MAIN_CLASS, + }) + zos.write((line + "\n").getBytes("US-ASCII")); + zos.closeEntry(); + + String testClasses = System.getProperty("test.classes"); + for (String className : SPECIAL_CLASSES) { + String baseName = className + ".class"; + ZipEntry ze = new ZipEntry(baseName); + File file = new File(testClasses, baseName); + zos.putNextEntry(ze); + Files.copy(file.toPath(), zos); + zos.closeEntry(); + } + + for (int i = SPECIAL_COUNT; i < entryCount; i++) { + zos.putNextEntry(new ZipEntry(Integer.toString(i))); zos.closeEntry(); } } @@ -86,16 +129,16 @@ public class EntryCount64k { return false; } - static void checkCanRead(File zipFile, int entryCount) throws Exception { + static void checkCanRead(File zipFile, int entryCount) throws Throwable { // Check ZipInputStream API - try (ZipInputStream zis = - new ZipInputStream( - new BufferedInputStream( - new FileInputStream(zipFile)))) { + try (FileInputStream fis = new FileInputStream(zipFile); + BufferedInputStream bis = new BufferedInputStream(fis); + ZipInputStream zis = new ZipInputStream(bis)) { for (int i = 0; i < entryCount; i++) { ZipEntry e = zis.getNextEntry(); - if (Integer.parseInt(e.getName()) != i) - throw new AssertionError(); + if (i >= SPECIAL_COUNT) // skip special entries + if (Integer.parseInt(e.getName()) != i) + throw new AssertionError(e.getName()); } if (zis.getNextEntry() != null) throw new AssertionError(); @@ -106,8 +149,9 @@ public class EntryCount64k { Enumeration en = zf.entries(); for (int i = 0; i < entryCount; i++) { ZipEntry e = en.nextElement(); - if (Integer.parseInt(e.getName()) != i) - throw new AssertionError(); + if (i >= SPECIAL_COUNT) // skip special entries + if (Integer.parseInt(e.getName()) != i) + throw new AssertionError(); } if (en.hasMoreElements() || (zf.size() != entryCount) @@ -115,5 +159,15 @@ public class EntryCount64k { || (zf.getEntry(Integer.toString(entryCount)) != null)) throw new AssertionError(); } + + // Check java -jar + String javaHome = System.getProperty("java.home"); + String java = Paths.get(javaHome, "bin", "java").toString(); + String[] cmd = { java, "-jar", zipFile.getName() }; + ProcessBuilder pb = new ProcessBuilder(cmd); + OutputAnalyzer a = ProcessTools.executeProcess(pb); + a.shouldHaveExitValue(0); + a.stdoutShouldMatch("\\AMain\\Z"); + a.stderrShouldMatch("\\A\\Z"); } } diff --git a/jdk/test/java/util/zip/FlaterTest.java b/jdk/test/java/util/zip/FlaterTest.java index 2179a1303ea..ff11ab0bd1c 100644 --- a/jdk/test/java/util/zip/FlaterTest.java +++ b/jdk/test/java/util/zip/FlaterTest.java @@ -26,6 +26,7 @@ * @bug 6348045 * @summary GZipOutputStream/InputStream goes critical(calls JNI_Get*Critical) * and causes slowness. This test uses Deflater and Inflater directly. + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/util/zip/GZIP/Accordion.java b/jdk/test/java/util/zip/GZIP/Accordion.java index fa5399e6221..a0d7494a26f 100644 --- a/jdk/test/java/util/zip/GZIP/Accordion.java +++ b/jdk/test/java/util/zip/GZIP/Accordion.java @@ -25,6 +25,7 @@ * @bug 5092263 * @summary GZIPInputStream o GZIPOutputStream === the identity stream * @author Martin Buchholz + * @key randomness */ // To manually test for uncompressed streams larger than 2GB, do diff --git a/jdk/test/java/util/zip/GZIP/GZIPInputStreamRead.java b/jdk/test/java/util/zip/GZIP/GZIPInputStreamRead.java index ba87f78373a..56bd58e1aaf 100644 --- a/jdk/test/java/util/zip/GZIP/GZIPInputStreamRead.java +++ b/jdk/test/java/util/zip/GZIP/GZIPInputStreamRead.java @@ -25,6 +25,7 @@ * @bug 4691425 * @summary Test the read and write of GZIPInput/OutputStream, including * concatenated .gz inputstream + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/util/zip/InflateIn_DeflateOut.java b/jdk/test/java/util/zip/InflateIn_DeflateOut.java index 1e4ef2bd073..0747d22b0a2 100644 --- a/jdk/test/java/util/zip/InflateIn_DeflateOut.java +++ b/jdk/test/java/util/zip/InflateIn_DeflateOut.java @@ -25,6 +25,7 @@ * @test * @bug 4206909 4813885 * @summary Test basic functionality of DeflaterOutputStream/InflaterInputStream and GZIPOutputStream/GZIPInputStream, including flush + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/util/zip/InflaterBufferSize.java b/jdk/test/java/util/zip/InflaterBufferSize.java index cf5363fca3e..1c512ec2c3d 100644 --- a/jdk/test/java/util/zip/InflaterBufferSize.java +++ b/jdk/test/java/util/zip/InflaterBufferSize.java @@ -26,6 +26,7 @@ * @bug 6571338 * @summary Inflater should not require a buffer to the inflate() methods * larger than 1 byte. + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/util/zip/TestExtraTime.java b/jdk/test/java/util/zip/TestExtraTime.java index 20d9e36cc79..666121cdbfe 100644 --- a/jdk/test/java/util/zip/TestExtraTime.java +++ b/jdk/test/java/util/zip/TestExtraTime.java @@ -23,7 +23,7 @@ /** * @test - * @bug 4759491 6303183 7012868 8015666 8023713 8068790 + * @bug 4759491 6303183 7012868 8015666 8023713 8068790 8076641 * @summary Test ZOS and ZIS timestamp in extra field correctly */ @@ -40,7 +40,6 @@ import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; - public class TestExtraTime { public static void main(String[] args) throws Throwable{ @@ -71,6 +70,7 @@ public class TestExtraTime { } testNullHandling(); + testTagOnlyHandling(); testTimeConversions(); } @@ -208,4 +208,42 @@ public class TestExtraTime { } } } + + static void check(ZipEntry ze, byte[] extra) { + if (extra != null) { + byte[] extra1 = ze.getExtra(); + if (extra1 == null || extra1.length < extra.length || + !Arrays.equals(Arrays.copyOfRange(extra1, + extra1.length - extra.length, + extra1.length), + extra)) { + throw new RuntimeException("Timestamp: storing extra field failed!"); + } + } + } + + static void testTagOnlyHandling() throws Throwable { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] extra = new byte[] { 0x0a, 0, 4, 0, 0, 0, 0, 0 }; + try (ZipOutputStream zos = new ZipOutputStream(baos)) { + ZipEntry ze = new ZipEntry("TestExtraTime.java"); + ze.setExtra(extra); + zos.putNextEntry(ze); + zos.write(new byte[] { 1,2 ,3, 4}); + } + try (ZipInputStream zis = new ZipInputStream( + new ByteArrayInputStream(baos.toByteArray()))) { + ZipEntry ze = zis.getNextEntry(); + check(ze, extra); + } + Path zpath = Paths.get(System.getProperty("test.dir", "."), + "TestExtraTime.zip"); + Files.copy(new ByteArrayInputStream(baos.toByteArray()), zpath); + try (ZipFile zf = new ZipFile(zpath.toFile())) { + ZipEntry ze = zf.getEntry("TestExtraTime.java"); + check(ze, extra); + } finally { + Files.delete(zpath); + } + } } diff --git a/jdk/test/java/util/zip/TimeChecksum.java b/jdk/test/java/util/zip/TimeChecksum.java index cc81f1e7592..d6eb44f77f1 100644 --- a/jdk/test/java/util/zip/TimeChecksum.java +++ b/jdk/test/java/util/zip/TimeChecksum.java @@ -25,6 +25,7 @@ /* @test * @bug 7109837 * @summary Test Adler32/CRC32.update(ByteBuffer) + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/zip/TotalInOut.java b/jdk/test/java/util/zip/TotalInOut.java index 1ea12b3b82c..c7f22a63b31 100644 --- a/jdk/test/java/util/zip/TotalInOut.java +++ b/jdk/test/java/util/zip/TotalInOut.java @@ -24,6 +24,7 @@ /* @test * @bug 7188852 * @summary Test De/Inflater.getBytesRead/Written() + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/util/zip/ZipFile/Assortment.java b/jdk/test/java/util/zip/ZipFile/Assortment.java index b890b31ff1a..61cf415d51a 100644 --- a/jdk/test/java/util/zip/ZipFile/Assortment.java +++ b/jdk/test/java/util/zip/ZipFile/Assortment.java @@ -25,6 +25,7 @@ * @bug 4770745 6234507 6303183 8048990 * @summary test a variety of zip file entries * @author Martin Buchholz + * @key randomness */ import java.util.*; diff --git a/jdk/test/java/util/zip/ZipFile/ClearStaleZipFileInputStreams.java b/jdk/test/java/util/zip/ZipFile/ClearStaleZipFileInputStreams.java index d1be7dc9cc6..2ba02300012 100644 --- a/jdk/test/java/util/zip/ZipFile/ClearStaleZipFileInputStreams.java +++ b/jdk/test/java/util/zip/ZipFile/ClearStaleZipFileInputStreams.java @@ -30,6 +30,7 @@ * @bug 7031076 * @summary Allow stale InputStreams from ZipFiles to be GC'd * @author Neil Richards , + * @key randomness */ import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; diff --git a/jdk/test/java/util/zip/ZipFile/FinalizeZipFile.java b/jdk/test/java/util/zip/ZipFile/FinalizeZipFile.java index 74866cac808..06dd4bc3bd6 100644 --- a/jdk/test/java/util/zip/ZipFile/FinalizeZipFile.java +++ b/jdk/test/java/util/zip/ZipFile/FinalizeZipFile.java @@ -24,6 +24,7 @@ /* @test * @bug 7007609 7009618 * @summary Check that ZipFile objects are always collected + * @key randomness */ import java.io.*; diff --git a/jdk/test/java/util/zip/ZipFile/MultiThreadedReadTest.java b/jdk/test/java/util/zip/ZipFile/MultiThreadedReadTest.java index c1f69a90587..a97e1f35285 100644 --- a/jdk/test/java/util/zip/ZipFile/MultiThreadedReadTest.java +++ b/jdk/test/java/util/zip/ZipFile/MultiThreadedReadTest.java @@ -27,6 +27,7 @@ * @library /lib/testlibrary * @build jdk.testlibrary.FileUtils * @run main MultiThreadedReadTest + * @key randomness */ import java.io.File; diff --git a/jdk/test/java/util/zip/ZipFile/ReadZip.java b/jdk/test/java/util/zip/ZipFile/ReadZip.java index 44f1d9ed97f..1052642eda7 100644 --- a/jdk/test/java/util/zip/ZipFile/ReadZip.java +++ b/jdk/test/java/util/zip/ZipFile/ReadZip.java @@ -24,6 +24,7 @@ /* @test @bug 4241361 4842702 4985614 6646605 5032358 6923692 @summary Make sure we can read a zip file. + @key randomness */ import java.io.*; diff --git a/jdk/test/javax/crypto/Cipher/ByteBuffers.java b/jdk/test/javax/crypto/Cipher/ByteBuffers.java index 99c807229f1..233e62fb83a 100644 --- a/jdk/test/javax/crypto/Cipher/ByteBuffers.java +++ b/jdk/test/javax/crypto/Cipher/ByteBuffers.java @@ -26,6 +26,7 @@ * @bug 4844847 * @summary Test the Cipher.update/doFinal(ByteBuffer, ByteBuffer) methods * @author Andreas Sterbenz + * @key randomness */ import java.util.*; diff --git a/jdk/test/javax/crypto/Cipher/CipherInputStreamExceptions.java b/jdk/test/javax/crypto/Cipher/CipherInputStreamExceptions.java new file mode 100644 index 00000000000..783967a9eac --- /dev/null +++ b/jdk/test/javax/crypto/Cipher/CipherInputStreamExceptions.java @@ -0,0 +1,415 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 8064546 + * @summary Throw exceptions during reading but not closing of a + * CipherInputStream: + * - Make sure authenticated algorithms continue to throwing exceptions + * when the authentication tag fails verification. + * - Make sure other algorithms do not throw exceptions when the stream + * calls close() and only throw when read() errors. + */ + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.lang.Exception; +import java.lang.RuntimeException; +import java.lang.Throwable; +import java.security.AlgorithmParameters; +import javax.crypto.AEADBadTagException; +import javax.crypto.Cipher; +import javax.crypto.CipherInputStream; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import javax.crypto.spec.GCMParameterSpec; + +public class CipherInputStreamExceptions { + + static SecretKeySpec key = new SecretKeySpec(new byte[16], "AES"); + static GCMParameterSpec gcmspec = new GCMParameterSpec(128, new byte[16]); + static IvParameterSpec iv = new IvParameterSpec(new byte[16]); + static boolean failure = false; + + /* Full read stream, check that getMoreData() is throwing an exception + * This test + * 1) Encrypt 100 bytes with AES/GCM/PKCS5Padding + * 2) Changes the last byte to invalidate the authetication tag. + * 3) Fully reads CipherInputStream to decrypt the message and closes + */ + + static void gcm_AEADBadTag() throws Exception { + Cipher c; + byte[] read = new byte[200]; + + System.out.println("Running gcm_AEADBadTag"); + + // Encrypt 100 bytes with AES/GCM/PKCS5Padding + byte[] ct = encryptedText("GCM", 100); + // Corrupt the encrypted message + ct = corruptGCM(ct); + // Create stream for decryption + CipherInputStream in = getStream("GCM", ct); + + try { + int size = in.read(read); + throw new RuntimeException("Fail: CipherInputStream.read() " + + "returned " + size + " and didn't throw an exception."); + } catch (IOException e) { + Throwable ec = e.getCause(); + if (ec instanceof AEADBadTagException) { + System.out.println(" Pass."); + } else { + System.out.println(" Fail: " + ec.getMessage()); + throw new RuntimeException(ec); + } + } finally { + in.close(); + } + } + + /* Short read stream, + * This test + * 1) Encrypt 100 bytes with AES/GCM/PKCS5Padding + * 2) Reads 100 bytes from stream to decrypt the message and closes + * 3) Make sure no value is returned by read() + * 4) Make sure no exception is thrown + */ + + static void gcm_shortReadAEAD() throws Exception { + Cipher c; + byte[] read = new byte[100]; + + System.out.println("Running gcm_shortReadAEAD"); + + byte[] pt = new byte[600]; + pt[0] = 1; + // Encrypt provided 600 bytes with AES/GCM/PKCS5Padding + byte[] ct = encryptedText("GCM", pt); + // Create stream for decryption + CipherInputStream in = getStream("GCM", ct); + + int size = 0; + try { + size = in.read(read); + in.close(); + if (read.length != 100) { + throw new RuntimeException("Fail: read size = " + read.length + + "should be 100."); + } + if (read[0] != 1) { + throw new RuntimeException("Fail: The decrypted text does " + + "not match the plaintext: '" + read[0] +"'"); + } + } catch (IOException e) { + System.out.println(" Fail: " + e.getMessage()); + throw new RuntimeException(e.getCause()); + } + System.out.println(" Pass."); + } + + /* + * Verify doFinal() exception is suppressed when input stream is not + * read before it is closed. + * This test: + * 1) Encrypt 100 bytes with AES/GCM/PKCS5Padding + * 2) Changes the last byte to invalidate the authetication tag. + * 3) Opens a CipherInputStream and the closes it. Never reads from it. + * + * There should be no exception thrown. + */ + static void gcm_suppressUnreadCorrupt() throws Exception { + Cipher c; + byte[] read = new byte[200]; + + System.out.println("Running supressUnreadCorrupt test"); + + // Encrypt 100 bytes with AES/GCM/PKCS5Padding + byte[] ct = encryptedText("GCM", 100); + // Corrupt the encrypted message + ct = corruptGCM(ct); + // Create stream for decryption + CipherInputStream in = getStream("GCM", ct); + + try { + in.close(); + System.out.println(" Pass."); + } catch (IOException e) { + System.out.println(" Fail: " + e.getMessage()); + throw new RuntimeException(e.getCause()); + } + } + + /* + * Verify noexception thrown when 1 byte is read from a GCM stream + * and then closed + * This test: + * 1) Encrypt 100 bytes with AES/GCM/PKCS5Padding + * 2) Read one byte from the stream, expect no exception thrown. + * 4) Close stream,expect no exception thrown. + */ + static void gcm_oneReadByte() throws Exception { + + System.out.println("Running gcm_oneReadByte test"); + + // Encrypt 100 bytes with AES/GCM/PKCS5Padding + byte[] ct = encryptedText("GCM", 100); + // Create stream for decryption + CipherInputStream in = getStream("GCM", ct); + + try { + in.read(); + System.out.println(" Pass."); + } catch (Exception e) { + System.out.println(" Fail: " + e.getMessage()); + throw new RuntimeException(e.getCause()); + } + } + + /* + * Verify exception thrown when 1 byte is read from a corrupted GCM stream + * and then closed + * This test: + * 1) Encrypt 100 bytes with AES/GCM/PKCS5Padding + * 2) Changes the last byte to invalidate the authetication tag. + * 3) Read one byte from the stream, expect exception thrown. + * 4) Close stream,expect no exception thrown. + */ + static void gcm_oneReadByteCorrupt() throws Exception { + + System.out.println("Running gcm_oneReadByteCorrupt test"); + + // Encrypt 100 bytes with AES/GCM/PKCS5Padding + byte[] ct = encryptedText("GCM", 100); + // Corrupt the encrypted message + ct = corruptGCM(ct); + // Create stream for decryption + CipherInputStream in = getStream("GCM", ct); + + try { + in.read(); + System.out.println(" Fail. No exception thrown."); + } catch (IOException e) { + Throwable ec = e.getCause(); + if (ec instanceof AEADBadTagException) { + System.out.println(" Pass."); + } else { + System.out.println(" Fail: " + ec.getMessage()); + throw new RuntimeException(ec); + } + } + } + + /* Check that close() does not throw an exception with full message in + * CipherInputStream's ibuffer. + * This test: + * 1) Encrypts a 97 byte message with AES/CBC/PKCS5Padding + * 2) Create a stream that sends 96 bytes. + * 3) Read stream once, + * 4) Close and expect no exception + */ + + static void cbc_shortStream() throws Exception { + Cipher c; + AlgorithmParameters params; + byte[] read = new byte[200]; + + System.out.println("Running cbc_shortStream"); + + // Encrypt 97 byte with AES/CBC/PKCS5Padding + byte[] ct = encryptedText("CBC", 97); + // Create stream with only 96 bytes of encrypted data + CipherInputStream in = getStream("CBC", ct, 96); + + try { + int size = in.read(read); + in.close(); + if (size != 80) { + throw new RuntimeException("Fail: CipherInputStream.read() " + + "returned " + size + ". Should have been 80"); + } + System.out.println(" Pass."); + } catch (IOException e) { + System.out.println(" Fail: " + e.getMessage()); + throw new RuntimeException(e.getCause()); + } + } + + /* Check that close() does not throw an exception when the whole message is + * inside the internal buffer (ibuffer) in CipherInputStream and we read + * one byte and close the stream. + * This test: + * 1) Encrypts a 400 byte message with AES/CBC/PKCS5Padding + * 2) Read one byte from the stream + * 3) Close and expect no exception + */ + + static void cbc_shortRead400() throws Exception { + System.out.println("Running cbc_shortRead400"); + + // Encrypt 400 byte with AES/CBC/PKCS5Padding + byte[] ct = encryptedText("CBC", 400); + // Create stream with encrypted data + CipherInputStream in = getStream("CBC", ct); + + try { + in.read(); + in.close(); + System.out.println(" Pass."); + } catch (IOException e) { + System.out.println(" Fail: " + e.getMessage()); + throw new RuntimeException(e.getCause()); + } + } + + /* Check that close() does not throw an exception when the inside the + * internal buffer (ibuffer) in CipherInputStream does not contain the + * whole message. + * This test: + * 1) Encrypts a 600 byte message with AES/CBC/PKCS5Padding + * 2) Read one byte from the stream + * 3) Close and expect no exception + */ + + static void cbc_shortRead600() throws Exception { + System.out.println("Running cbc_shortRead600"); + + // Encrypt 600 byte with AES/CBC/PKCS5Padding + byte[] ct = encryptedText("CBC", 600); + // Create stream with encrypted data + CipherInputStream in = getStream("CBC", ct); + + try { + in.read(); + in.close(); + System.out.println(" Pass."); + } catch (IOException e) { + System.out.println(" Fail: " + e.getMessage()); + throw new RuntimeException(e.getCause()); + } + } + + /* Check that exception is thrown when message is fully read + * This test: + * 1) Encrypts a 96 byte message with AES/CBC/PKCS5Padding + * 2) Create a stream that sends 95 bytes. + * 3) Read stream to the end + * 4) Expect IllegalBlockSizeException thrown + */ + + static void cbc_readAllIllegalBlockSize() throws Exception { + byte[] read = new byte[200]; + + System.out.println("Running cbc_readAllIllegalBlockSize test"); + + // Encrypt 96 byte with AES/CBC/PKCS5Padding + byte[] ct = encryptedText("CBC", 96); + // Create a stream with only 95 bytes of encrypted data + CipherInputStream in = getStream("CBC", ct, 95); + + try { + int s, size = 0; + while ((s = in.read(read)) != -1) { + size += s; + } + throw new RuntimeException("Fail: No IllegalBlockSizeException. " + + "CipherInputStream.read() returned " + size); + + } catch (IOException e) { + Throwable ec = e.getCause(); + if (ec instanceof IllegalBlockSizeException) { + System.out.println(" Pass."); + } else { + System.out.println(" Fail: " + ec.getMessage()); + throw new RuntimeException(ec); + } + } + } + + /* Generic method to create encrypted text */ + static byte[] encryptedText(String mode, int length) throws Exception{ + return encryptedText(mode, new byte[length]); + } + + /* Generic method to create encrypted text */ + static byte[] encryptedText(String mode, byte[] pt) throws Exception{ + Cipher c; + if (mode.compareTo("GCM") == 0) { + c = Cipher.getInstance("AES/GCM/PKCS5Padding", "SunJCE"); + c.init(Cipher.ENCRYPT_MODE, key, gcmspec); + } else if (mode.compareTo("CBC") == 0) { + c = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE"); + c.init(Cipher.ENCRYPT_MODE, key, iv); + } else { + return null; + } + + return c.doFinal(pt); + } + + /* Generic method to get a properly setup CipherInputStream */ + static CipherInputStream getStream(String mode, byte[] ct) throws Exception { + return getStream(mode, ct, ct.length); + } + + /* Generic method to get a properly setup CipherInputStream */ + static CipherInputStream getStream(String mode, byte[] ct, int length) + throws Exception { + Cipher c; + + if (mode.compareTo("GCM") == 0) { + c = Cipher.getInstance("AES/GCM/PKCS5Padding", "SunJCE"); + c.init(Cipher.DECRYPT_MODE, key, gcmspec); + } else if (mode.compareTo("CBC") == 0) { + c = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE"); + c.init(Cipher.DECRYPT_MODE, key, iv); + } else { + return null; + } + + return new CipherInputStream(new ByteArrayInputStream(ct, 0, length), c); + + } + + /* Generic method for corrupting a GCM message. Change the last + * byte on of the authentication tag + */ + static byte[] corruptGCM(byte[] ct) { + ct[ct.length - 1] = (byte) (ct[ct.length - 1] + 1); + return ct; + } + + public static void main(String[] args) throws Exception { + gcm_AEADBadTag(); + gcm_shortReadAEAD(); + gcm_suppressUnreadCorrupt(); + gcm_oneReadByte(); + gcm_oneReadByteCorrupt(); + cbc_shortStream(); + cbc_shortRead400(); + cbc_shortRead600(); + cbc_readAllIllegalBlockSize(); + } +} diff --git a/jdk/test/javax/crypto/CipherSpi/DirectBBRemaining.java b/jdk/test/javax/crypto/CipherSpi/DirectBBRemaining.java index 9cc840664c0..9e03c908660 100644 --- a/jdk/test/javax/crypto/CipherSpi/DirectBBRemaining.java +++ b/jdk/test/javax/crypto/CipherSpi/DirectBBRemaining.java @@ -26,6 +26,7 @@ * @bug 7142509 * @summary Cipher.doFinal(ByteBuffer,ByteBuffer) fails to * process when in.remaining() == 0 + * @key randomness */ import java.nio.ByteBuffer; diff --git a/jdk/test/javax/crypto/CryptoPermission/AllPermCheck.java b/jdk/test/javax/crypto/CryptoPermission/AllPermCheck.java index 3359fcd88e2..d7a1ad40e39 100644 --- a/jdk/test/javax/crypto/CryptoPermission/AllPermCheck.java +++ b/jdk/test/javax/crypto/CryptoPermission/AllPermCheck.java @@ -28,6 +28,7 @@ * InvalidKeyException is thrown instead of SecurityException when * crypto permssion checks failed. * @author Valerie Peng + * @key randomness */ import java.io.*; diff --git a/jdk/test/javax/crypto/CryptoPermission/RC2PermCheck.java b/jdk/test/javax/crypto/CryptoPermission/RC2PermCheck.java index a4270802fe5..fc49baec11e 100644 --- a/jdk/test/javax/crypto/CryptoPermission/RC2PermCheck.java +++ b/jdk/test/javax/crypto/CryptoPermission/RC2PermCheck.java @@ -27,6 +27,7 @@ * @summary Ensure the crypto permission check on cipher algorithms * with restricted parameter values are correctly enforced. * @author Valerie Peng + * @key randomness */ import java.io.*; diff --git a/jdk/test/javax/crypto/JceSecurity/SunJCE_BC_LoadOrdering.java b/jdk/test/javax/crypto/JceSecurity/SunJCE_BC_LoadOrdering.java index c2991bbcc07..50a1c188d0f 100644 --- a/jdk/test/javax/crypto/JceSecurity/SunJCE_BC_LoadOrdering.java +++ b/jdk/test/javax/crypto/JceSecurity/SunJCE_BC_LoadOrdering.java @@ -28,6 +28,7 @@ * @summary SunJCE depends on sun.security.provider.SignatureImpl * behaviour, BC can't load into 1st slot. * @author Brad R. Wetmore + * @key randomness */ import java.security.*; diff --git a/jdk/test/javax/crypto/KeyGenerator/TestKGParity.java b/jdk/test/javax/crypto/KeyGenerator/TestKGParity.java index 40752152c56..cb512274bf8 100644 --- a/jdk/test/javax/crypto/KeyGenerator/TestKGParity.java +++ b/jdk/test/javax/crypto/KeyGenerator/TestKGParity.java @@ -35,6 +35,7 @@ import static java.lang.System.out; * @bug 8048607 * @compile ../../../com/sun/crypto/provider/Cipher/DES/TestUtility.java * @summary Test key generation of DES and DESEDE + * @key randomness */ public class TestKGParity { diff --git a/jdk/test/javax/crypto/Mac/ByteBuffers.java b/jdk/test/javax/crypto/Mac/ByteBuffers.java index 96070881715..a00e5a43cd6 100644 --- a/jdk/test/javax/crypto/Mac/ByteBuffers.java +++ b/jdk/test/javax/crypto/Mac/ByteBuffers.java @@ -26,6 +26,7 @@ * @bug 4844847 * @summary Test the Mac.update(ByteBuffer) method * @author Andreas Sterbenz + * @key randomness */ import java.util.*; diff --git a/jdk/test/javax/crypto/NullCipher/TestNPE.java b/jdk/test/javax/crypto/NullCipher/TestNPE.java index 45aa81ac78e..0e216d0226d 100644 --- a/jdk/test/javax/crypto/NullCipher/TestNPE.java +++ b/jdk/test/javax/crypto/NullCipher/TestNPE.java @@ -26,6 +26,7 @@ * @bug 4937853 * @summary Make sure normal calls of NullCipher does not throw NPE. * @author Valerie Peng + * @key randomness */ import java.util.Arrays; import java.security.AlgorithmParameters; diff --git a/jdk/test/javax/imageio/stream/ShortStreamTest.java b/jdk/test/javax/imageio/stream/ShortStreamTest.java new file mode 100644 index 00000000000..2b133a57a7c --- /dev/null +++ b/jdk/test/javax/imageio/stream/ShortStreamTest.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 8074954 + * @summary Test verifies that an IOException is triggered if input stream + * does not contain enough data to read a multi-byte type. + * + * @run main ShortStreamTest + */ + +import javax.imageio.ImageIO; +import javax.imageio.stream.ImageInputStream; +import java.io.ByteArrayInputStream; +import java.io.IOException; + +public class ShortStreamTest { + public static void main(String[] args) throws IOException { + TestCase[] tests = createTests(); + + for (TestCase t : tests) { + t.test(); + } + } + + private static abstract class TestCase { + abstract void testRead(ImageInputStream iis) throws IOException; + + public void test() { + boolean gotException = false; + + ImageInputStream iis = createShortStream(); + + try { + testRead(iis); + } catch (IOException e) { + e.printStackTrace(System.out); + gotException = true; + } + + if (!gotException) { + throw new RuntimeException("Test failed."); + } + System.out.println("Test PASSED"); + } + } + + + private static ImageInputStream createShortStream() { + try { + byte[] integerTestArray = new byte[] { 80 }; + ByteArrayInputStream bais = new ByteArrayInputStream(integerTestArray); + + return ImageIO.createImageInputStream(bais); + } catch (IOException e) { + return null; + } + } + + private static TestCase[] createTests() { + return new TestCase[]{ + new TestCase() { + @Override + void testRead(ImageInputStream iis) throws IOException { + iis.readInt(); + } + }, + new TestCase() { + @Override + void testRead(ImageInputStream iis) throws IOException { + iis.readShort(); + } + }, + new TestCase() { + @Override + void testRead(ImageInputStream iis) throws IOException { + iis.readDouble(); + } + }, + new TestCase() { + @Override + void testRead(ImageInputStream iis) throws IOException { + iis.readFloat(); + } + }, + new TestCase() { + @Override + void testRead(ImageInputStream iis) throws IOException { + iis.readLong(); + } + }, + new TestCase() { + @Override + void testRead(ImageInputStream iis) throws IOException { + iis.readUnsignedInt(); + } + }, + new TestCase() { + @Override + void testRead(ImageInputStream iis) throws IOException { + iis.readUnsignedShort(); + } + } + }; + } +} diff --git a/jdk/test/javax/management/monitor/MultiMonitorTest.java b/jdk/test/javax/management/monitor/MultiMonitorTest.java index 93bba22553f..fe40f63d8ff 100644 --- a/jdk/test/javax/management/monitor/MultiMonitorTest.java +++ b/jdk/test/javax/management/monitor/MultiMonitorTest.java @@ -29,6 +29,7 @@ * @run clean MultiMonitorTest * @run build MultiMonitorTest * @run main MultiMonitorTest + * @key randomness */ import java.util.*; diff --git a/jdk/test/javax/management/mxbean/ThreadMXBeanTest.java b/jdk/test/javax/management/mxbean/ThreadMXBeanTest.java index f533f340b50..d2ca6a90102 100644 --- a/jdk/test/javax/management/mxbean/ThreadMXBeanTest.java +++ b/jdk/test/javax/management/mxbean/ThreadMXBeanTest.java @@ -29,6 +29,7 @@ * @run clean ThreadMXBeanTest * @run build ThreadMXBeanTest * @run main ThreadMXBeanTest + * @key randomness */ import java.lang.management.*; diff --git a/jdk/test/javax/management/remote/mandatory/loading/MissingClassTest.java b/jdk/test/javax/management/remote/mandatory/loading/MissingClassTest.java index 341bbfc5249..c6e212cf924 100644 --- a/jdk/test/javax/management/remote/mandatory/loading/MissingClassTest.java +++ b/jdk/test/javax/management/remote/mandatory/loading/MissingClassTest.java @@ -29,6 +29,7 @@ * @run clean MissingClassTest SingleClassLoader * @run build MissingClassTest SingleClassLoader * @run main MissingClassTest + * @key randomness */ /* diff --git a/jdk/test/javax/management/remote/mandatory/notif/NotSerializableNotifTest.java b/jdk/test/javax/management/remote/mandatory/notif/NotSerializableNotifTest.java index 24bf863dc88..538658f7b06 100644 --- a/jdk/test/javax/management/remote/mandatory/notif/NotSerializableNotifTest.java +++ b/jdk/test/javax/management/remote/mandatory/notif/NotSerializableNotifTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,37 +34,31 @@ // java imports // import java.net.MalformedURLException; -import java.util.Map; - -// JMX imports -// -import javax.management.* ; - -import javax.management.remote.*; +import javax.management.MBeanNotificationInfo; +import javax.management.MBeanServer; +import javax.management.MBeanServerConnection; +import javax.management.MBeanServerFactory; +import javax.management.Notification; +import javax.management.NotificationBroadcasterSupport; +import javax.management.NotificationListener; +import javax.management.ObjectName; +import javax.management.remote.JMXConnector; +import javax.management.remote.JMXConnectorFactory; +import javax.management.remote.JMXConnectorServer; +import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; public class NotSerializableNotifTest { private static final MBeanServer mbeanServer = MBeanServerFactory.createMBeanServer(); private static ObjectName emitter; - private static int port = 2468; private static String[] protocols; private static final int sentNotifs = 10; - private static double timeoutFactor = 1.0; - private static final double defaultTimeout = 10; - public static void main(String[] args) throws Exception { System.out.println(">>> Test to send a not serializable notification"); - String timeoutVal = System.getProperty("test.timeout.factor"); - if (timeoutVal != null) { - timeoutFactor = Double.parseDouble( - System.getProperty("test.timeout.factor") - ); - } - // IIOP fails on JDK1.4, see 5034318 final String v = System.getProperty("java.version"); float f = Float.parseFloat(v.substring(0, 3)); @@ -77,35 +71,18 @@ public class NotSerializableNotifTest { emitter = new ObjectName("Default:name=NotificationEmitter"); mbeanServer.registerMBean(new NotificationEmitter(), emitter); - boolean ok = true; for (int i = 0; i < protocols.length; i++) { - try { - if (!test(protocols[i])) { - System.out.println(">>> Test failed for " + protocols[i]); - ok = false; - } else { - System.out.println(">>> Test successed for " + protocols[i]); - } - } catch (Exception e) { - System.out.println(">>> Test failed for " + protocols[i]); - e.printStackTrace(System.out); - ok = false; - } + test(protocols[i]); } - if (ok) { - System.out.println(">>> Test passed"); - } else { - System.out.println(">>> TEST FAILED"); - System.exit(1); - } + System.out.println(">>> Test passed"); } - private static boolean test(String proto) throws Exception { + private static void test(String proto) throws Exception { System.out.println("\n>>> Test for protocol " + proto); - JMXServiceURL url = new JMXServiceURL(proto, null, port++); + JMXServiceURL url = new JMXServiceURL(proto, null, 0); System.out.println(">>> Create a server: "+url); @@ -115,7 +92,7 @@ public class NotSerializableNotifTest { } catch (MalformedURLException e) { System.out.println("System does not recognize URL: " + url + "; ignoring"); - return true; + return; } server.start(); @@ -146,34 +123,17 @@ public class NotSerializableNotifTest { // waiting ... synchronized (listener) { - int top = (int)Math.ceil(timeoutFactor * defaultTimeout); - for (int i=0; i commands = new ArrayList<>(); + commands.add(ConcurrentHashMapTest.JAVA); + commands.add("-Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory"); + commands.add("-Djava.naming.provider.url=iiop://localhost:1050"); + commands.add("-cp"); + commands.add(ConcurrentHashMapTest.CLASSPATH); + commands.add("HelloServer"); + + System.out.println("ConcurrentHashMapTest: Executing: " + commands); + ProcessBuilder pb = new ProcessBuilder(commands); + pb.redirectError(ProcessBuilder.Redirect.INHERIT); + rmiServerProcess = pb.start(); + } + + static boolean isResponseReceived() { + return HelloClient.isResponseReceived(); + } + + static void stopRmiIiopServer() throws Exception { + rmiServerProcess.destroy(); + rmiServerProcess.waitFor(); + //rmiServerProcess.waitFor(30, TimeUnit.SECONDS); + System.out.println("serverProcess exitCode:" + + rmiServerProcess.exitValue()); + } + + static void stopOrbd() throws Exception { + orbdProcess.destroy(); + orbdProcess.waitFor(); + //orbdProcess.waitFor(30, TimeUnit.SECONDS); + System.out.println("orbd exitCode:" + + orbdProcess.exitValue()); + } + + static void executeRmiIiopClient() throws Exception { + try { + HelloClient.executeRmiClientCall(); + } catch (Exception ex) { + clientException = ex; + exceptionInClient = true; + } + } +} diff --git a/jdk/test/javax/rmi/PortableRemoteObject/HelloClient.java b/jdk/test/javax/rmi/PortableRemoteObject/HelloClient.java new file mode 100644 index 00000000000..d3baa64e56b --- /dev/null +++ b/jdk/test/javax/rmi/PortableRemoteObject/HelloClient.java @@ -0,0 +1,98 @@ +import java.rmi.RemoteException; +import java.net.InetAddress; +import java.net.MalformedURLException; +import java.rmi.NotBoundException; +import java.util.HashMap; +import java.util.Vector; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantLock; + +import javax.naming.NamingException; +import javax.naming.InitialContext; +import javax.naming.Context; +import javax.naming.NameNotFoundException; +import javax.naming.NamingException; +import javax.rmi.PortableRemoteObject; + +import org.omg.CORBA.Any; +import org.omg.CORBA.ORB; + +public class HelloClient implements Runnable { + static final int MAX_RETRY = 10; + static final int ONE_SECOND = 1000; + private static boolean responseReceived; + + public static void main(String args[]) throws Exception { + executeRmiClientCall(); + } + + @Override + public void run() { + try { + executeRmiClientCall(); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + + public static boolean isResponseReceived () { + return responseReceived; + } + + public static void executeRmiClientCall() throws Exception { + Context ic; + Object objref; + HelloInterface helloSvc; + String response; + int retryCount = 0; + + Test test = new Test(); + System.out.println("HelloClient.main: enter ..."); + while (retryCount < MAX_RETRY) { + try { + ic = new InitialContext(); + System.out.println("HelloClient.main: HelloService lookup ..."); + // STEP 1: Get the Object reference from the Name Service + // using JNDI call. + objref = ic.lookup("HelloService"); + System.out.println("HelloClient: Obtained a ref. to Hello server."); + + // STEP 2: Narrow the object reference to the concrete type and + // invoke the method. + helloSvc = (HelloInterface) PortableRemoteObject.narrow(objref, + HelloInterface.class); + System.out.println("HelloClient: Invoking on remote server with ConcurrentHashMap parameter"); + ConcurrentHashMap testConcurrentHashMap = new ConcurrentHashMap(); + response = helloSvc.sayHelloWithHashMap(testConcurrentHashMap); + System.out.println("HelloClient: Server says: " + response); + if (!response.contains("Hello with hashMapSize ==")) { + System.out.println("HelloClient: expected response not received"); + throw new RuntimeException("Expected Response Hello with hashMapSize == 0 not received"); + } + responseReceived = true; + break; + } catch (NameNotFoundException nnfEx) { + System.err.println("NameNotFoundException Caught .... try again"); + retryCount++; + try { + Thread.sleep(ONE_SECOND); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } catch (Exception e) { + System.err.println("Exception " + e + "Caught"); + e.printStackTrace(); + throw new RuntimeException(e); + } + } + System.err.println("HelloClient terminating "); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/jdk/test/javax/rmi/PortableRemoteObject/HelloImpl.java b/jdk/test/javax/rmi/PortableRemoteObject/HelloImpl.java new file mode 100644 index 00000000000..e6b24948852 --- /dev/null +++ b/jdk/test/javax/rmi/PortableRemoteObject/HelloImpl.java @@ -0,0 +1,60 @@ +import java.net.InetAddress; +import java.rmi.RemoteException; +import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantLock; + +import javax.rmi.PortableRemoteObject; + +public class HelloImpl extends PortableRemoteObject implements HelloInterface { + public HelloImpl() throws java.rmi.RemoteException { + super(); // invoke rmi linking and remote object initialization + } + + public String sayHello(String from) throws java.rmi.RemoteException { + System.out.println("Hello from " + from + "!!"); + System.out.flush(); + String reply = "Hello from us to you " + from; + return reply; + } + + @Override + public String sayHelloToTest(Test test) throws RemoteException { + return "Test says Hello"; + } + + @Override + public String sayHelloWithInetAddress(InetAddress ipAddr) + throws RemoteException { + String response = "Hello with InetAddress " + ipAddr.toString(); + return response; + } + + @Override + public String sayHelloWithHashMap(ConcurrentHashMap receivedHashMap) + throws RemoteException { + int hashMapSize = 0; + + hashMapSize = receivedHashMap.size(); + String response = "Hello with hashMapSize == " + hashMapSize; + return response; + } + + @Override + public String sayHelloWithHashMap2(HashMap receivedHashMap) + throws RemoteException { + int hashMapSize = 0; + + hashMapSize = receivedHashMap.size(); + String response = "Hello with hashMapSize == " + hashMapSize; + return response; + } + + @Override + public String sayHelloWithReentrantLock(ReentrantLock receivedLock) + throws RemoteException { + + String response = "Hello with lock == " + receivedLock.isLocked(); + return response; + } +} diff --git a/jdk/test/javax/rmi/PortableRemoteObject/HelloInterface.java b/jdk/test/javax/rmi/PortableRemoteObject/HelloInterface.java new file mode 100644 index 00000000000..0c1a1635b0f --- /dev/null +++ b/jdk/test/javax/rmi/PortableRemoteObject/HelloInterface.java @@ -0,0 +1,14 @@ +import java.net.InetAddress; +import java.rmi.Remote; +import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantLock; + +public interface HelloInterface extends Remote { + public String sayHello( String from ) throws java.rmi.RemoteException; + public String sayHelloToTest( Test test ) throws java.rmi.RemoteException; + public String sayHelloWithInetAddress( InetAddress ipAddr ) throws java.rmi.RemoteException; + public String sayHelloWithHashMap(ConcurrentHashMap hashMap ) throws java.rmi.RemoteException; + public String sayHelloWithHashMap2(HashMap hashMap ) throws java.rmi.RemoteException; + public String sayHelloWithReentrantLock(ReentrantLock lock ) throws java.rmi.RemoteException; +} diff --git a/jdk/test/javax/rmi/PortableRemoteObject/HelloServer.java b/jdk/test/javax/rmi/PortableRemoteObject/HelloServer.java new file mode 100644 index 00000000000..f3ec3991531 --- /dev/null +++ b/jdk/test/javax/rmi/PortableRemoteObject/HelloServer.java @@ -0,0 +1,36 @@ +import javax.naming.InitialContext; +import javax.naming.Context; + +public class HelloServer { + + static final int MAX_RETRY = 10; + static final int ONE_SECOND = 1000; + + public static void main(String[] args) { + int retryCount = 0; + while (retryCount < MAX_RETRY) { + try { + //HelloServer.set("SETTING TEST ITL"); + // Step 1: Instantiate the Hello servant + HelloImpl helloRef = new HelloImpl(); + + // Step 2: Publish the reference in the Naming Service + // using JNDI API + Context initialNamingContext = new InitialContext(); + initialNamingContext.rebind("HelloService", helloRef); + + System.out.println("Hello Server: Ready..."); + break; + } catch (Exception e) { + System.out.println("Server initialization problem: " + e); + e.printStackTrace(); + retryCount++; + try { + Thread.sleep(ONE_SECOND); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + } + } + } +} diff --git a/jdk/test/javax/rmi/PortableRemoteObject/Test.java b/jdk/test/javax/rmi/PortableRemoteObject/Test.java new file mode 100644 index 00000000000..1fc3ecf939f --- /dev/null +++ b/jdk/test/javax/rmi/PortableRemoteObject/Test.java @@ -0,0 +1,6 @@ +import java.io.Serializable; + + +public class Test implements Serializable { + +} diff --git a/jdk/test/javax/rmi/PortableRemoteObject/_HelloImpl_Tie.java b/jdk/test/javax/rmi/PortableRemoteObject/_HelloImpl_Tie.java new file mode 100644 index 00000000000..040500d8aeb --- /dev/null +++ b/jdk/test/javax/rmi/PortableRemoteObject/_HelloImpl_Tie.java @@ -0,0 +1,128 @@ +// Tie class generated by rmic, do not edit. +// Contents subject to change without notice. + +import java.io.Serializable; +import java.net.InetAddress; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantLock; +import javax.rmi.CORBA.Tie; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.CORBA_2_3.portable.ObjectImpl; + + +public class _HelloImpl_Tie extends ObjectImpl implements Tie { + + private HelloImpl target = null; + + private static final String[] _type_ids = { + "RMI:HelloInterface:0000000000000000" + }; + + public void setTarget(Remote target) { + this.target = (HelloImpl) target; + } + + public Remote getTarget() { + return target; + } + + public org.omg.CORBA.Object thisObject() { + return this; + } + + public void deactivate() { + _orb().disconnect(this); + _set_delegate(null); + target = null; + } + + public ORB orb() { + return _orb(); + } + + public void orb(ORB orb) { + orb.connect(this); + } + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public OutputStream _invoke(String method, InputStream _in, ResponseHandler reply) throws SystemException { + try { + org.omg.CORBA_2_3.portable.InputStream in = + (org.omg.CORBA_2_3.portable.InputStream) _in; + switch (method.length()) { + case 8: + if (method.equals("sayHello")) { + String arg0 = (String) in.read_value(String.class); + String result = target.sayHello(arg0); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + case 14: + if (method.equals("sayHelloToTest")) { + Test arg0 = (Test) in.read_value(Test.class); + String result = target.sayHelloToTest(arg0); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + case 19: + if (method.equals("sayHelloWithHashMap")) { + ConcurrentHashMap arg0 = (ConcurrentHashMap) in.read_value(ConcurrentHashMap.class); + String result = target.sayHelloWithHashMap(arg0); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + case 20: + if (method.equals("sayHelloWithHashMap2")) { + HashMap arg0 = (HashMap) in.read_value(HashMap.class); + String result = target.sayHelloWithHashMap2(arg0); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + case 23: + if (method.equals("sayHelloWithInetAddress")) { + InetAddress arg0 = (InetAddress) in.read_value(InetAddress.class); + String result = target.sayHelloWithInetAddress(arg0); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + case 25: + if (method.equals("sayHelloWithReentrantLock")) { + ReentrantLock arg0 = (ReentrantLock) in.read_value(ReentrantLock.class); + String result = target.sayHelloWithReentrantLock(arg0); + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) reply.createReply(); + out.write_value(result,String.class); + return out; + } + } + throw new BAD_OPERATION(); + } catch (SystemException ex) { + throw ex; + } catch (Throwable ex) { + throw new UnknownException(ex); + } + } +} diff --git a/jdk/test/javax/rmi/PortableRemoteObject/_HelloInterface_Stub.java b/jdk/test/javax/rmi/PortableRemoteObject/_HelloInterface_Stub.java new file mode 100644 index 00000000000..4098143151f --- /dev/null +++ b/jdk/test/javax/rmi/PortableRemoteObject/_HelloInterface_Stub.java @@ -0,0 +1,272 @@ +// Stub class generated by rmic, do not edit. +// Contents subject to change without notice. + +import java.io.Serializable; +import java.net.InetAddress; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantLock; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.ServantObject; + + +public class _HelloInterface_Stub extends Stub implements HelloInterface { + + private static final String[] _type_ids = { + "RMI:HelloInterface:0000000000000000" + }; + + public String[] _ids() { + return (String[]) _type_ids.clone(); + } + + public String sayHello(String arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("sayHello", true); + out.write_value(arg0,String.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sayHello(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sayHello",HelloInterface.class); + if (so == null) { + return sayHello(arg0); + } + try { + return ((HelloInterface)so.servant).sayHello(arg0); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String sayHelloToTest(Test arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("sayHelloToTest", true); + out.write_value(arg0,Test.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sayHelloToTest(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sayHelloToTest",HelloInterface.class); + if (so == null) { + return sayHelloToTest(arg0); + } + try { + Test arg0Copy = (Test) Util.copyObject(arg0,_orb()); + return ((HelloInterface)so.servant).sayHelloToTest(arg0Copy); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String sayHelloWithInetAddress(InetAddress arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("sayHelloWithInetAddress", true); + out.write_value(arg0,InetAddress.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sayHelloWithInetAddress(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sayHelloWithInetAddress",HelloInterface.class); + if (so == null) { + return sayHelloWithInetAddress(arg0); + } + try { + InetAddress arg0Copy = (InetAddress) Util.copyObject(arg0,_orb()); + return ((HelloInterface)so.servant).sayHelloWithInetAddress(arg0Copy); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String sayHelloWithHashMap(ConcurrentHashMap arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("sayHelloWithHashMap", true); + out.write_value(arg0,ConcurrentHashMap.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sayHelloWithHashMap(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sayHelloWithHashMap",HelloInterface.class); + if (so == null) { + return sayHelloWithHashMap(arg0); + } + try { + ConcurrentHashMap arg0Copy = (ConcurrentHashMap) Util.copyObject(arg0,_orb()); + return ((HelloInterface)so.servant).sayHelloWithHashMap(arg0Copy); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String sayHelloWithHashMap2(HashMap arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("sayHelloWithHashMap2", true); + out.write_value(arg0,HashMap.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sayHelloWithHashMap2(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sayHelloWithHashMap2",HelloInterface.class); + if (so == null) { + return sayHelloWithHashMap2(arg0); + } + try { + HashMap arg0Copy = (HashMap) Util.copyObject(arg0,_orb()); + return ((HelloInterface)so.servant).sayHelloWithHashMap2(arg0Copy); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } + + public String sayHelloWithReentrantLock(ReentrantLock arg0) throws java.rmi.RemoteException { + if (!Util.isLocal(this)) { + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA_2_3.portable.OutputStream out = + (org.omg.CORBA_2_3.portable.OutputStream) + _request("sayHelloWithReentrantLock", true); + out.write_value(arg0,ReentrantLock.class); + in = (org.omg.CORBA_2_3.portable.InputStream)_invoke(out); + return (String) in.read_value(String.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream) ex.getInputStream(); + String $_id = in.read_string(); + throw new UnexpectedException($_id); + } catch (RemarshalException ex) { + return sayHelloWithReentrantLock(arg0); + } finally { + _releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } else { + ServantObject so = _servant_preinvoke("sayHelloWithReentrantLock",HelloInterface.class); + if (so == null) { + return sayHelloWithReentrantLock(arg0); + } + try { + ReentrantLock arg0Copy = (ReentrantLock) Util.copyObject(arg0,_orb()); + return ((HelloInterface)so.servant).sayHelloWithReentrantLock(arg0Copy); + } catch (Throwable ex) { + Throwable exCopy = (Throwable)Util.copyObject(ex,_orb()); + throw Util.wrapException(exCopy); + } finally { + _servant_postinvoke(so); + } + } + } +} diff --git a/jdk/test/javax/security/auth/login/LoginContext/CustomLoginModule.java b/jdk/test/javax/security/auth/login/LoginContext/CustomLoginModule.java new file mode 100644 index 00000000000..e47f3de56e7 --- /dev/null +++ b/jdk/test/javax/security/auth/login/LoginContext/CustomLoginModule.java @@ -0,0 +1,275 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.IOException; +import java.security.Principal; +import java.util.Arrays; +import java.util.Locale; +import java.util.Map; +import javax.security.auth.Subject; +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.ChoiceCallback; +import javax.security.auth.callback.ConfirmationCallback; +import javax.security.auth.callback.LanguageCallback; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.TextInputCallback; +import javax.security.auth.callback.TextOutputCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import javax.security.auth.login.FailedLoginException; +import javax.security.auth.login.LoginException; +import javax.security.auth.spi.LoginModule; + +public class CustomLoginModule implements LoginModule { + + static final String HELLO = "Hello"; + + private Subject subject; + private CallbackHandler callbackHandler; + private boolean loginSucceeded = false; + private String username; + private char[] password; + + /* + * Initialize this LoginModule. + */ + @Override + public void initialize(Subject subject, CallbackHandler callbackHandler, + Map sharedState, Map options) { + this.subject = subject; + this.callbackHandler = callbackHandler; + + // check if custom parameter is passed from comfiguration + if (options == null) { + throw new RuntimeException("options is null"); + } + + // read username/password from configuration + Object o = options.get("username"); + if (o == null) { + throw new RuntimeException("Custom parameter not passed"); + } + if (!(o instanceof String)) { + throw new RuntimeException("Password is not a string"); + } + username = (String) o; + + o = options.get("password"); + if (o == null) { + throw new RuntimeException("Custom parameter not passed"); + } + if (!(o instanceof String)) { + throw new RuntimeException("Password is not a string"); + } + password = ((String) o).toCharArray(); + } + + /* + * Authenticate the user. + */ + @Override + public boolean login() throws LoginException { + // prompt for a user name and password + if (callbackHandler == null) { + throw new LoginException("No CallbackHandler available"); + } + + // standard callbacks + NameCallback name = new NameCallback("username: ", "default"); + PasswordCallback passwd = new PasswordCallback("password: ", false); + + LanguageCallback language = new LanguageCallback(); + + TextOutputCallback error = new TextOutputCallback( + TextOutputCallback.ERROR, "This is an error"); + TextOutputCallback warning = new TextOutputCallback( + TextOutputCallback.WARNING, "This is a warning"); + TextOutputCallback info = new TextOutputCallback( + TextOutputCallback.INFORMATION, "This is a FYI"); + + TextInputCallback text = new TextInputCallback("Please type " + HELLO, + "Bye"); + + ChoiceCallback choice = new ChoiceCallback("Choice: ", + new String[] { "pass", "fail" }, 1, true); + + ConfirmationCallback confirmation = new ConfirmationCallback( + "confirmation: ", ConfirmationCallback.INFORMATION, + ConfirmationCallback.YES_NO_OPTION, ConfirmationCallback.NO); + + CustomCallback custom = new CustomCallback(); + + Callback[] callbacks = new Callback[] { + choice, info, warning, error, name, passwd, text, language, + confirmation, custom + }; + + boolean uce = false; + try { + callbackHandler.handle(callbacks); + } catch (UnsupportedCallbackException e) { + Callback callback = e.getCallback(); + if (custom.equals(callback)) { + uce = true; + System.out.println("CustomLoginModule: " + + "custom callback not supported as expected"); + } else { + throw new LoginException("Unsupported callback: " + callback); + } + } catch (IOException ioe) { + throw new LoginException(ioe.toString()); + } + + if (!uce) { + throw new RuntimeException("UnsupportedCallbackException " + + "not thrown"); + } + + if (!HELLO.equals(text.getText())) { + System.out.println("Text: " + text.getText()); + throw new FailedLoginException("No hello"); + } + + if (!Locale.GERMANY.equals(language.getLocale())) { + System.out.println("Selected locale: " + language.getLocale()); + throw new FailedLoginException("Achtung bitte"); + } + + String readUsername = name.getName(); + char[] readPassword = passwd.getPassword(); + if (readPassword == null) { + // treat a NULL password as an empty password + readPassword = new char[0]; + } + passwd.clearPassword(); + + // verify the username/password + if (!username.equals(readUsername) + || !Arrays.equals(password, readPassword)) { + loginSucceeded = false; + throw new FailedLoginException("Username/password is not correct"); + } + + // check chosen option + int[] selected = choice.getSelectedIndexes(); + if (selected == null || selected.length == 0) { + throw new FailedLoginException("Nothing selected"); + } + + if (selected[0] != 0) { + throw new FailedLoginException("Wrong choice: " + selected[0]); + } + + // check confirmation + if (confirmation.getSelectedIndex() != ConfirmationCallback.YES) { + throw new FailedLoginException("Not confirmed: " + + confirmation.getSelectedIndex()); + } + + loginSucceeded = true; + System.out.println("CustomLoginModule: authentication succeeded"); + return true; + } + + /* + * This method is called if the LoginContext's overall authentication + * succeeded. + */ + @Override + public boolean commit() throws LoginException { + if (loginSucceeded) { + // add a Principal to the Subject + Principal principal = new TestPrincipal(username); + if (!subject.getPrincipals().contains(principal)) { + subject.getPrincipals().add(principal); + } + return true; + } + + return false; + } + + /* + * This method is called if the LoginContext's overall authentication + * failed. + */ + @Override + public boolean abort() throws LoginException { + loginSucceeded = false; + return true; + } + + /* + * Logout the user. + */ + @Override + public boolean logout() throws LoginException { + loginSucceeded = false; + boolean removed = subject.getPrincipals().remove( + new TestPrincipal(username)); + if (!removed) { + throw new LoginException("Coundn't remove a principal: " + + username); + } + return true; + } + + static class TestPrincipal implements Principal { + + private final String name; + + public TestPrincipal(String name) { + this.name = name; + } + + @Override + public String getName() { + return name; + } + + @Override + public String toString() { + return("TestPrincipal [name =" + name + "]"); + } + + @Override + public int hashCode() { + return name.hashCode(); + } + + @Override + public boolean equals(Object o) { + if (o == null) { + return false; + } + if (!(o instanceof TestPrincipal)) { + return false; + } + TestPrincipal other = (TestPrincipal) o; + return name != null ? name.equals(other.name) : other.name == null; + } + } + + static class CustomCallback implements Callback {} +} diff --git a/jdk/test/javax/security/auth/login/LoginContext/SharedState.java b/jdk/test/javax/security/auth/login/LoginContext/SharedState.java new file mode 100644 index 00000000000..d944e5a46db --- /dev/null +++ b/jdk/test/javax/security/auth/login/LoginContext/SharedState.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.util.Map; +import javax.security.auth.Subject; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.login.LoginContext; +import javax.security.auth.login.LoginException; +import javax.security.auth.spi.LoginModule; + +/** + * @test + * @bug 8048138 + * @summary Check if shared state is passed to login module + * @run main/othervm SharedState + */ +public class SharedState { + + static final String NAME = "name"; + static final String VALUE = "shared"; + + public static void main(String[] args) throws LoginException { + System.setProperty("java.security.auth.login.config", + System.getProperty("test.src") + + System.getProperty("file.separator") + + "shared.config"); + + new LoginContext("SharedState").login(); + } + + public static abstract class Module implements LoginModule { + + @Override + public boolean login() throws LoginException { + return true; + } + + @Override + public boolean commit() throws LoginException { + return true; + } + + @Override + public boolean abort() throws LoginException { + return true; + } + + @Override + public boolean logout() throws LoginException { + return true; + } + } + + public static class FirstModule extends Module { + + @Override + public void initialize(Subject subject, CallbackHandler callbackHandler, + Map sharedState, Map options) { + ((Map)sharedState).put(NAME, VALUE); + } + + } + + public static class SecondModule extends Module { + + @Override + public void initialize(Subject subject, CallbackHandler callbackHandler, + Map sharedState, Map options) { + // check shared object + Object shared = sharedState.get(NAME); + if (!VALUE.equals(shared)) { + throw new RuntimeException("Unexpected shared object: " + + shared); + } + } + + } +} diff --git a/jdk/test/javax/security/auth/login/LoginContext/StandardCallbacks.java b/jdk/test/javax/security/auth/login/LoginContext/StandardCallbacks.java new file mode 100644 index 00000000000..4b69f84cdbf --- /dev/null +++ b/jdk/test/javax/security/auth/login/LoginContext/StandardCallbacks.java @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.security.Principal; +import java.util.Arrays; +import java.util.Locale; +import javax.security.auth.Subject; +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.ChoiceCallback; +import javax.security.auth.callback.ConfirmationCallback; +import javax.security.auth.callback.LanguageCallback; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.TextInputCallback; +import javax.security.auth.callback.TextOutputCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import javax.security.auth.login.LoginContext; +import javax.security.auth.login.LoginException; + +/* + * @test + * @bug 8048138 + * @summary Checks if JAAS login works fine with standard callbacks + * @compile DefaultHandlerModule.java + * @run main/othervm StandardCallbacks + */ +public class StandardCallbacks { + + private static final String USERNAME = "username"; + private static final char[] PASSWORD = "password".toCharArray(); + + public static void main(String[] args) throws LoginException { + System.setProperty("java.security.auth.login.config", + System.getProperty("test.src") + + System.getProperty("file.separator") + + "custom.config"); + + CustomCallbackHandler handler = new CustomCallbackHandler(USERNAME); + LoginContext context = new LoginContext("StandardCallbacks", handler); + + handler.setPassword(PASSWORD); + System.out.println("Try to login with correct password, " + + "successful authentication is expected"); + context.login(); + System.out.println("Authentication succeeded!"); + + Subject subject = context.getSubject(); + System.out.println("Authenticated user has the following principals [" + + subject.getPrincipals().size() + " ]:"); + boolean found = true; + for (Principal principal : subject.getPrincipals()) { + System.out.println("principal: " + principal); + if (principal instanceof CustomLoginModule.TestPrincipal) { + CustomLoginModule.TestPrincipal testPrincipal = + (CustomLoginModule.TestPrincipal) principal; + if (USERNAME.equals(testPrincipal.getName())) { + System.out.println("Found test principal: " + + testPrincipal); + found = true; + break; + } + } + } + + if (!found) { + throw new RuntimeException("TestPrincipal not found"); + } + + // check if all expected text output callbacks have been called + if (!handler.info) { + throw new RuntimeException("TextOutputCallback.INFO not called"); + } + + if (!handler.warning) { + throw new RuntimeException("TextOutputCallback.WARNING not called"); + } + + if (!handler.error) { + throw new RuntimeException("TextOutputCallback.ERROR not called"); + } + + System.out.println("Authenticated user has the following public " + + "credentials [" + subject.getPublicCredentials().size() + + "]:"); + subject.getPublicCredentials().stream(). + forEach((o) -> { + System.out.println("public credential: " + o); + }); + + context.logout(); + + System.out.println("Test passed"); + } + + private static class CustomCallbackHandler implements CallbackHandler { + + private final String username; + private char[] password; + private boolean info = false; + private boolean warning = false; + private boolean error = false; + + CustomCallbackHandler(String username) { + this.username = username; + } + + void setPassword(char[] password) { + this.password = password; + } + + @Override + public void handle(Callback[] callbacks) + throws UnsupportedCallbackException { + for (Callback callback : callbacks) { + if (callback instanceof TextOutputCallback) { + TextOutputCallback toc = (TextOutputCallback) callback; + switch (toc.getMessageType()) { + case TextOutputCallback.INFORMATION: + System.out.println("INFO: " + toc.getMessage()); + info = true; + break; + case TextOutputCallback.ERROR: + System.out.println("ERROR: " + toc.getMessage()); + error = true; + break; + case TextOutputCallback.WARNING: + System.out.println("WARNING: " + toc.getMessage()); + warning = true; + break; + default: + throw new UnsupportedCallbackException(toc, + "Unsupported message type: " + + toc.getMessageType()); + } + } else if (callback instanceof TextInputCallback) { + TextInputCallback tic = (TextInputCallback) callback; + System.out.println(tic.getPrompt()); + tic.setText(CustomLoginModule.HELLO); + } else if (callback instanceof LanguageCallback) { + LanguageCallback lc = (LanguageCallback) callback; + lc.setLocale(Locale.GERMANY); + } else if (callback instanceof ConfirmationCallback) { + ConfirmationCallback cc = (ConfirmationCallback) callback; + System.out.println(cc.getPrompt()); + cc.setSelectedIndex(ConfirmationCallback.YES); + } else if (callback instanceof ChoiceCallback) { + ChoiceCallback cc = (ChoiceCallback) callback; + System.out.println(cc.getPrompt() + + Arrays.toString(cc.getChoices())); + cc.setSelectedIndex(0); + } else if (callback instanceof NameCallback) { + NameCallback nc = (NameCallback) callback; + System.out.println(nc.getPrompt()); + nc.setName(username); + } else if (callback instanceof PasswordCallback) { + PasswordCallback pc = (PasswordCallback) callback; + System.out.println(pc.getPrompt()); + pc.setPassword(password); + } else { + throw new UnsupportedCallbackException(callback, + "Unknown callback"); + } + } + } + + } + +} diff --git a/jdk/test/javax/security/auth/login/LoginContext/custom.config b/jdk/test/javax/security/auth/login/LoginContext/custom.config new file mode 100644 index 00000000000..6ecdc56e928 --- /dev/null +++ b/jdk/test/javax/security/auth/login/LoginContext/custom.config @@ -0,0 +1,4 @@ +StandardCallbacks { + DefaultHandlerModule required; + CustomLoginModule required username="username" password="password"; +}; diff --git a/jdk/test/javax/security/auth/login/LoginContext/shared.config b/jdk/test/javax/security/auth/login/LoginContext/shared.config new file mode 100644 index 00000000000..86201e22435 --- /dev/null +++ b/jdk/test/javax/security/auth/login/LoginContext/shared.config @@ -0,0 +1,4 @@ +SharedState { + SharedState$FirstModule required; + SharedState$SecondModule required; +}; \ No newline at end of file diff --git a/jdk/test/javax/security/auth/spi/FirstLoginModule.java b/jdk/test/javax/security/auth/spi/FirstLoginModule.java new file mode 100644 index 00000000000..60112aeb090 --- /dev/null +++ b/jdk/test/javax/security/auth/spi/FirstLoginModule.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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.security.auth.Subject; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.login.LoginException; +import javax.security.auth.spi.LoginModule; +import java.util.Map; + +public class FirstLoginModule implements LoginModule { + + @Override + public void initialize(Subject subject, CallbackHandler callbackHandler, + Map sharedState, Map options) { + // Nothing + } + + @Override + public boolean login() throws LoginException { + return true; + } + + @Override + public boolean commit() throws LoginException { + return true; + } + + @Override + public boolean abort() throws LoginException { + return true; + } + + @Override + public boolean logout() throws LoginException { + return true; + } +} diff --git a/jdk/test/javax/security/auth/spi/Loader.java b/jdk/test/javax/security/auth/spi/Loader.java new file mode 100644 index 00000000000..e2bac97de09 --- /dev/null +++ b/jdk/test/javax/security/auth/spi/Loader.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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.security.auth.login.LoginContext; +import java.io.File; + +/* + * @test + * @bug 8047789 + * @summary auth.login.LoginContext needs to be updated to work with modules + * @build FirstLoginModule SecondLoginModule + * @run main/othervm Loader + */ +public class Loader { + + public static void main(String[] args) throws Exception { + + System.setProperty("java.security.auth.login.config", + new File(System.getProperty("test.src"), "sl.conf").toString()); + LoginContext lc = new LoginContext("me"); + + if (SecondLoginModule.isLoaded) { + throw new Exception(); + } + + lc.login(); + + // Although only FirstLoginModule is specified in the JAAS login + // config file, LoginContext will first create all LoginModule + // implementations that are registered as services, which include + // SecondLoginModule. + if (!SecondLoginModule.isLoaded) { + throw new Exception(); + } + } +} diff --git a/jdk/test/javax/security/auth/spi/META-INF/services/javax.security.auth.spi.LoginModule b/jdk/test/javax/security/auth/spi/META-INF/services/javax.security.auth.spi.LoginModule new file mode 100644 index 00000000000..b6189241649 --- /dev/null +++ b/jdk/test/javax/security/auth/spi/META-INF/services/javax.security.auth.spi.LoginModule @@ -0,0 +1 @@ +SecondLoginModule diff --git a/jdk/test/javax/security/auth/spi/SecondLoginModule.java b/jdk/test/javax/security/auth/spi/SecondLoginModule.java new file mode 100644 index 00000000000..c6c85872fa5 --- /dev/null +++ b/jdk/test/javax/security/auth/spi/SecondLoginModule.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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.security.auth.Subject; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.login.LoginException; +import javax.security.auth.spi.LoginModule; +import java.util.Map; + +public class SecondLoginModule implements LoginModule { + + public static boolean isLoaded; + + public SecondLoginModule() { + isLoaded = true; + } + + @Override + public void initialize(Subject subject, CallbackHandler callbackHandler, + Map sharedState, Map options) { + // Nothing + } + + @Override + public boolean login() throws LoginException { + return true; + } + + @Override + public boolean commit() throws LoginException { + return true; + } + + @Override + public boolean abort() throws LoginException { + return true; + } + + @Override + public boolean logout() throws LoginException { + return true; + } +} diff --git a/jdk/test/javax/security/auth/spi/sl.conf b/jdk/test/javax/security/auth/spi/sl.conf new file mode 100644 index 00000000000..e14400eed1a --- /dev/null +++ b/jdk/test/javax/security/auth/spi/sl.conf @@ -0,0 +1,3 @@ +me { + FirstLoginModule required; +}; diff --git a/jdk/test/javax/smartcardio/TestCommandAPDU.java b/jdk/test/javax/smartcardio/TestCommandAPDU.java index 93517ea79de..543fcea2487 100644 --- a/jdk/test/javax/smartcardio/TestCommandAPDU.java +++ b/jdk/test/javax/smartcardio/TestCommandAPDU.java @@ -26,6 +26,7 @@ * @bug 6293767 * @summary Test for the CommandAPDU class * @author Andreas Sterbenz + * @key randomness */ import java.util.*; diff --git a/jdk/test/javax/swing/GroupLayout/8013566/bug8013566.java b/jdk/test/javax/swing/GroupLayout/8013566/bug8013566.java new file mode 100644 index 00000000000..886da012d8a --- /dev/null +++ b/jdk/test/javax/swing/GroupLayout/8013566/bug8013566.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 8013566 + @summary Failure of GroupLayout in combination of addPreferredGap and addGroup's + last row + @author Semyon Sadetsky +*/ + +import javax.swing.*; + +public class bug8013566 { + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + final JFrame frame = new JFrame(); + try { + frame.setUndecorated(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + test(frame); + + + } finally { + frame.dispose(); + } + } + }); + + System.out.println("ok"); + } + + static void test(JFrame frame) { + JComponent c1 = new JButton("Label1"); + JComponent c2 = new JButton("Label22"); + JComponent c3 = new JButton("Label333"); + + JPanel panel = new JPanel(); + GroupLayout layout = new GroupLayout(panel); + layout.setAutoCreateContainerGaps(true); + layout.setAutoCreateGaps(true); + panel.setLayout(layout); + + layout.setHorizontalGroup(layout.createSequentialGroup().addGroup( + layout.createParallelGroup().addGroup( + layout.createSequentialGroup().addComponent(c1) + .addPreferredGap( + LayoutStyle.ComponentPlacement.RELATED, + 50, 200)) + .addComponent(c2)).addComponent(c3)); + + layout.setVerticalGroup(layout.createSequentialGroup() + .addComponent(c1).addComponent(c2).addComponent(c3) + ); + + frame.setContentPane(panel); + frame.pack(); + frame.setVisible(true); + + if (c3.getX() != c1.getX() + c1.getWidth() + 50) { + throw new RuntimeException( + "Gap between 1st and 3rd component is wrong"); + } + + } +} diff --git a/jdk/test/javax/swing/JInternalFrame/8075314/bug8075314.java b/jdk/test/javax/swing/JInternalFrame/8075314/bug8075314.java new file mode 100644 index 00000000000..a57e787f300 --- /dev/null +++ b/jdk/test/javax/swing/JInternalFrame/8075314/bug8075314.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 8075314 + @summary All the InternalFrames will be maximized after maximizing only one + of the InternalFrame with the special options "-client -Xmixed + -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel". + @author Semyon Sadetsky + */ + + +import javax.swing.*; +import java.beans.PropertyVetoException; + +public class bug8075314 { + + + private static JFrame frame; + private static JInternalFrame frame1; + private static JInternalFrame frame2; + + public static void main(String[] args) throws Exception { + for (UIManager.LookAndFeelInfo lookAndFeelInfo : UIManager + .getInstalledLookAndFeels()) { + UIManager.setLookAndFeel(lookAndFeelInfo.getClassName()); + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame = new JFrame(); + frame.setUndecorated(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setup(frame); + } + }); + + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + try { + frame1.setMaximum(true); + frame1.setClosed(true); + if (frame2.isMaximum()) { + throw new RuntimeException( + "Frame2 is maximized!"); + } + } catch (PropertyVetoException e) { + throw new RuntimeException(e); + } + + } + }); + } finally { + frame.dispose(); + } + } + System.out.println("ok"); + } + + private static void setup(JFrame frame) { + JDesktopPane desktop = new JDesktopPane(); + frame.setContentPane(desktop); + + frame1 = new JInternalFrame("1", true, true, true, true); + frame1.setBounds(40, 40, 300, 200); + frame1.setVisible(true); + desktop.add(frame1); + frame2 = new JInternalFrame("2", true, true, true, true); + frame2.setBounds(20, 20, 300, 200); + frame2.setVisible(true); + desktop.add(frame2); + + frame.setSize(500, 400); + frame.setVisible(true); + } +} diff --git a/jdk/test/javax/swing/JScrollPane/8033000/bug8033000.java b/jdk/test/javax/swing/JScrollPane/8033000/bug8033000.java new file mode 100644 index 00000000000..4e5d23149ab --- /dev/null +++ b/jdk/test/javax/swing/JScrollPane/8033000/bug8033000.java @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.awt.BorderLayout; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.KeyEvent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import jdk.testlibrary.OSInfo; + +/** + * @test + * @bug 8033000 + * @author Alexander Scherbatiy + * @summary No Horizontal Mouse Wheel Support In BasicScrollPaneUI + * @library ../../../../lib/testlibrary + * @build jdk.testlibrary.OSInfo + * @run main bug8033000 + */ +public class bug8033000 { + + private static JScrollPane scrollPane; + private static JTextArea textArea; + private static Point point; + private static final int delta; + + static { + delta = OSInfo.getOSType().equals(OSInfo.OSType.MACOSX) ? -30 : 30; + } + + public static void main(String[] args) throws Exception { + + Robot robot = new Robot(); + robot.setAutoDelay(50); + + SwingUtilities.invokeAndWait(bug8033000::createAndShowGUI); + robot.waitForIdle(); + + SwingUtilities.invokeAndWait(() -> { + Point locationOnScreen = scrollPane.getLocationOnScreen(); + point = new Point( + locationOnScreen.x + scrollPane.getWidth() / 2, + locationOnScreen.y + scrollPane.getHeight() / 2); + }); + + robot.mouseMove(point.x, point.y); + robot.waitForIdle(); + + // vertical scroll bar is enabled + initScrollPane(true, false); + robot.waitForIdle(); + robot.mouseWheel(delta); + robot.waitForIdle(); + checkScrollPane(true); + + // vertical scroll bar is enabled + shift + initScrollPane(true, false); + robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_SHIFT); + robot.mouseWheel(delta); + robot.keyRelease(KeyEvent.VK_SHIFT); + robot.waitForIdle(); + checkScrollPane(true); + + // horizontal scroll bar is enabled + initScrollPane(false, true); + robot.waitForIdle(); + robot.mouseWheel(delta); + robot.waitForIdle(); + checkScrollPane(false); + + // horizontal scroll bar is enabled + shift + initScrollPane(false, true); + robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_SHIFT); + robot.mouseWheel(delta); + robot.keyRelease(KeyEvent.VK_SHIFT); + robot.waitForIdle(); + checkScrollPane(false); + + // both scroll bars are enabled + initScrollPane(true, true); + robot.waitForIdle(); + robot.mouseWheel(delta); + robot.waitForIdle(); + checkScrollPane(true); + + // both scroll bars are enabled + shift + initScrollPane(true, true); + robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_SHIFT); + robot.mouseWheel(delta); + robot.keyRelease(KeyEvent.VK_SHIFT); + robot.waitForIdle(); + checkScrollPane(false); + } + + static void initScrollPane(boolean vVisible, boolean hVisible) throws Exception { + SwingUtilities.invokeAndWait(() -> { + scrollPane.getVerticalScrollBar().setValue(0); + scrollPane.getHorizontalScrollBar().setValue(0); + + textArea.setRows(vVisible ? 100 : 1); + textArea.setColumns(hVisible ? 100 : 1); + scrollPane.getVerticalScrollBar().setVisible(vVisible); + scrollPane.getHorizontalScrollBar().setVisible(hVisible); + }); + } + + static void checkScrollPane(boolean verticalScrolled) throws Exception { + SwingUtilities.invokeAndWait(() -> { + + if (verticalScrolled) { + if (scrollPane.getVerticalScrollBar().getValue() == 0 + || scrollPane.getHorizontalScrollBar().getValue() != 0) { + throw new RuntimeException("Wrong vertical scrolling!"); + } + } else { + if (scrollPane.getVerticalScrollBar().getValue() != 0 + || scrollPane.getHorizontalScrollBar().getValue() == 0) { + throw new RuntimeException("Wrong horizontal scrolling!"); + } + } + }); + } + + static void createAndShowGUI() { + JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setSize(300, 300); + textArea = new JTextArea("Hello World!"); + scrollPane = new JScrollPane(textArea); + JPanel panel = new JPanel(new BorderLayout()); + panel.add(scrollPane, BorderLayout.CENTER); + frame.getContentPane().add(panel); + frame.setVisible(true); + } +} diff --git a/jdk/test/javax/swing/JTable/6894632/bug6894632.java b/jdk/test/javax/swing/JTable/6894632/bug6894632.java new file mode 100644 index 00000000000..07cf5960605 --- /dev/null +++ b/jdk/test/javax/swing/JTable/6894632/bug6894632.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 6894632 + @summary Removing rows from a DefaultTableModel with a RowSorter deselectes + last row + @author Semyon Sadetsky +*/ + +import javax.swing.*; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableModel; +import javax.swing.table.TableRowSorter; +import java.util.ArrayList; +import java.util.List; + +public class bug6894632 { + private static JTable table; + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + + //init table with empty sort order + test(new ArrayList()); + + //init table as unsorted + List sortKeys = new ArrayList<>(); + sortKeys.add(0, new RowSorter.SortKey(0, SortOrder.UNSORTED)); + test(sortKeys); + } + }); + + System.out.println("ok"); + } + + static void test(final List sortKeys) { + final JFrame frame = new JFrame(); + try { + frame.setUndecorated(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + table = new JTable(); + DefaultTableModel tableModel = + new DefaultTableModel(10, 1) { + public Object getValueAt(int row, int column) { + return row == getRowCount() - 1 ? row + "==last" : + row; + } + }; + table.setModel(tableModel); + TableRowSorter sorter = + new TableRowSorter(tableModel); + sorter.setSortKeys(sortKeys); + table.setRowSorter(sorter); + + frame.setContentPane(table); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + + int lastRow = table.getRowCount() - 1; + + //select last row + table.setRowSelectionInterval(lastRow, lastRow); + + //remove row above the last + tableModel.removeRow(lastRow - 1); + lastRow = table.getRowCount() - 1; + if (lastRow != table.getSelectedRow()) { + throw new RuntimeException("last row must be still selected"); + } + + //sort table + sortKeys.clear(); + sortKeys.add(0, new RowSorter.SortKey(0, SortOrder.ASCENDING)); + sorter.setSortKeys(sortKeys); + //remove row above the last + lastRow = table.getRowCount() - 1; + tableModel.removeRow(lastRow - 1); + + if (!table.getValueAt(table.getSelectedRow(), 0).toString() + .endsWith("==last")) { + throw new RuntimeException( + "row ends with \"==last\" row must be still selected"); + } + + //make table unsorted again + sortKeys.clear(); + sortKeys.add(0, new RowSorter.SortKey(0, SortOrder.UNSORTED)); + sorter.setSortKeys(sortKeys); + //remove row above the last + lastRow = table.getRowCount() - 1; + tableModel.removeRow(lastRow - 1); + + lastRow = table.getRowCount() - 1; + if (lastRow != table.getSelectedRow()) { + throw new RuntimeException( + "last row must be still selected"); + } + } finally { + frame.dispose(); + } + } + + +} diff --git a/jdk/test/javax/swing/JTableHeader/4473075/bug4473075.java b/jdk/test/javax/swing/JTableHeader/4473075/bug4473075.java new file mode 100644 index 00000000000..a45cd16a56a --- /dev/null +++ b/jdk/test/javax/swing/JTableHeader/4473075/bug4473075.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 4473075 + @summary JTable header rendering problem (after setting preferred size) + @author Semyon Sadetsky +*/ + +import javax.swing.*; +import javax.swing.table.DefaultTableModel; +import java.awt.*; +import java.awt.event.InputEvent; + +public class bug4473075 { + public static final int USER_HEADER_HEIGHT = 40; + private static JTable table; + private static JScrollPane scpScroll; + private static Point point; + private static JFrame frame; + + public static void main(String[] args) throws Exception { + Robot robot = new Robot(); + robot.setAutoDelay(20); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame = new JFrame(); + frame.setUndecorated(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + table = new JTable(); + String t = "a cell text"; + table.setModel(new DefaultTableModel( + new Object[][]{new Object[]{t, t, t, t, t}}, + new Object[]{t, t, t, t, t})); + table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + scpScroll = new JScrollPane(table); + + // Manually set preferred size of header... + Dimension preferredSize = new Dimension(table.getSize().width, + USER_HEADER_HEIGHT); + table.getTableHeader().setPreferredSize(preferredSize); + + frame.setContentPane(scpScroll); + frame.setSize(250, 480); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + point = scpScroll.getHorizontalScrollBar() + .getLocationOnScreen(); + } + }); + robot.waitForIdle(); + + robot.mouseMove(point.x + 100, point.y + 5); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseMove(point.x + 150, point.y + 5); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + int headerH = table.getTableHeader().getHeight(); + if (headerH != USER_HEADER_HEIGHT) { + throw new RuntimeException("TableHeader height was not set: " + + headerH + " !=" + USER_HEADER_HEIGHT); + } + + double tableX = table.getX(); + int headerX = table.getTableHeader().getX(); + if (tableX != headerX) { + throw new RuntimeException("TableHeader X position is wrong: " + + tableX + " !=" + headerX); + } + + double tableW = table.getWidth(); + int headerW = table.getTableHeader().getWidth(); + if (tableW != headerW) { + throw new RuntimeException("TableHeader width is wrong: " + + tableW + " !=" + headerW); + } + + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + frame.dispose(); + } + }); + System.out.println("ok"); + } +} diff --git a/jdk/test/javax/swing/ToolTipManager/7123767/bug7123767.java b/jdk/test/javax/swing/ToolTipManager/7123767/bug7123767.java index 4c7402d3900..143503861a1 100644 --- a/jdk/test/javax/swing/ToolTipManager/7123767/bug7123767.java +++ b/jdk/test/javax/swing/ToolTipManager/7123767/bug7123767.java @@ -28,8 +28,6 @@ @run main bug7123767 */ -import sun.awt.SunToolkit; - import javax.swing.*; import javax.swing.plaf.metal.MetalLookAndFeel; import java.awt.*; @@ -160,8 +158,10 @@ public class bug7123767 extends JFrame { // Moves mouse pointer to the corners of every GraphicsConfiguration private static void testToolTip() throws AWTException { - SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); - toolkit.realSync(); + + robot = new Robot(); + robot.setAutoDelay(20); + robot.waitForIdle(); GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] devices = environment.getScreenDevices(); @@ -169,28 +169,28 @@ public class bug7123767 extends JFrame { GraphicsConfiguration[] configs = device.getConfigurations(); for (GraphicsConfiguration config : configs) { Rectangle rect = config.getBounds(); - Insets insets = toolkit.getScreenInsets(config); + Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(config); adjustInsets(rect, insets); // Upper left glide(rect.x + rect.width / 2, rect.y + rect.height / 2, rect.x + MARGIN, rect.y + MARGIN); - toolkit.realSync(); + robot.waitForIdle(); // Lower left glide(rect.x + rect.width / 2, rect.y + rect.height / 2, rect.x + MARGIN, rect.y + rect.height - MARGIN); - toolkit.realSync(); + robot.waitForIdle(); // Upper right glide(rect.x + rect.width / 2, rect.y + rect.height / 2, rect.x + rect.width - MARGIN, rect.y + MARGIN); - toolkit.realSync(); + robot.waitForIdle(); // Lower right glide(rect.x + rect.width / 2, rect.y + rect.height / 2, rect.x + rect.width - MARGIN, rect.y + rect.height - MARGIN); - toolkit.realSync(); + robot.waitForIdle(); } } } diff --git a/jdk/test/javax/swing/plaf/nimbus/8041642/bug8041642.java b/jdk/test/javax/swing/plaf/nimbus/8041642/bug8041642.java new file mode 100644 index 00000000000..4ed00df642d --- /dev/null +++ b/jdk/test/javax/swing/plaf/nimbus/8041642/bug8041642.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 8041642 + @summary Incorrect paint of JProgressBar in Nimbus LF + @author Semyon Sadetsky +*/ + +import javax.swing.*; +import java.awt.*; + +public class bug8041642 { + + private static JFrame frame; + private static Point point; + private static JProgressBar bar; + + public static void main(String[] args) throws Exception { + for (UIManager.LookAndFeelInfo info : UIManager + .getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + try { + UIManager.setLookAndFeel(info.getClassName()); + } catch (Exception ex) { + } + break; + } + } + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame = new JFrame(); + frame.setUndecorated(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setup(frame); + } + }); + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + point = bar.getLocationOnScreen(); + } + }); + final Robot robot = new Robot(); + Color color = robot.getPixelColor(point.x + 1, point.y + 7); + System.out.println(color); + if (color.getGreen() < 150 || color.getBlue() > 30 || + color.getRed() > 200) { + throw new RuntimeException("Bar padding color should be green"); + } + + } finally { + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + //frame.dispose(); + } + }); + } + + System.out.println("ok"); + } + + static void setup(JFrame frame) { + bar = new JProgressBar(); + bar.setBackground(Color.WHITE); + bar.setValue(2); + frame.getContentPane().add(bar, BorderLayout.NORTH); + frame.getContentPane().setBackground(Color.GREEN); + frame.setSize(200, 150); + frame.setLocation(100, 100); + frame.setVisible(true); + } +} diff --git a/jdk/test/javax/swing/plaf/synth/8040328/bug8040328.java b/jdk/test/javax/swing/plaf/synth/8040328/bug8040328.java new file mode 100644 index 00000000000..72a0e46885f --- /dev/null +++ b/jdk/test/javax/swing/plaf/synth/8040328/bug8040328.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 8040328 + @summary JSlider has wrong preferred size with Synth LAF + @author Semyon Sadetsky +*/ + +import javax.swing.*; +import javax.swing.plaf.synth.SynthLookAndFeel; +import java.awt.*; +import java.io.ByteArrayInputStream; + +public class bug8040328 { + private static String synthXml = "" + + " " + + " " + + " " + + " " + + ""; + + public static void main(String[] args) throws Exception { + SynthLookAndFeel lookAndFeel = new SynthLookAndFeel(); + lookAndFeel.load(new ByteArrayInputStream(synthXml.getBytes("UTF8")), + bug8040328.class); + UIManager.setLookAndFeel(lookAndFeel); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + final JFrame frame = new JFrame(); + try { + frame.setUndecorated(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + test(frame); + } finally { + frame.dispose(); + } + } + }); + System.out.println("ok"); + } + + static void test(JFrame frame) { + JSlider hslider = new JSlider(JSlider.HORIZONTAL); + hslider.setBackground(Color.DARK_GRAY); + frame.getContentPane().add(hslider, BorderLayout.CENTER); + frame.getContentPane().setBackground(Color.CYAN); + frame.pack(); + Insets insets = hslider.getInsets(); + if (hslider.getWidth() != 200 + insets.left + insets.right) { + throw new RuntimeException( + "Horizontal slider width is wrong " + hslider.getWidth()); + } + if (hslider.getHeight() != hslider.getMinimumSize().height) { + throw new RuntimeException( + "Horizontal slider height is wrong " + hslider.getHeight()); + } + frame.getContentPane().remove(hslider); + + JSlider vslider = new JSlider(JSlider.VERTICAL); + frame.getContentPane().add(vslider); + frame.pack(); + insets = vslider.getInsets(); + if (vslider.getWidth() != vslider.getMinimumSize().width) { + throw new RuntimeException( + "Verical slider width is wrong " + vslider.getWidth()); + } + if (vslider.getHeight() != 200 + insets.top + insets.bottom) { + throw new RuntimeException( + "Verical slider height is wrong " + vslider.getHeight()); + } + } +} diff --git a/jdk/test/javax/swing/plaf/windows/6921687/bug6921687.java b/jdk/test/javax/swing/plaf/windows/6921687/bug6921687.java new file mode 100644 index 00000000000..d8ad4069bbf --- /dev/null +++ b/jdk/test/javax/swing/plaf/windows/6921687/bug6921687.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 6921687 + @summary Mnemonic disappears after repeated attempts to open menu items using + mnemonics + @author Semyon Sadetsky + @library /lib/testlibrary + @build jdk.testlibrary.OSInfo + */ + + +import jdk.testlibrary.OSInfo; +import javax.swing.*; +import java.awt.*; +import java.awt.event.KeyEvent; + + +public class bug6921687 { + + private static Class lafClass; + private static JFrame frame; + + public static void main(String[] args) throws Exception { + if (OSInfo.getOSType() != OSInfo.OSType.WINDOWS) { + System.out.println("Only Windows platform test. Test is skipped."); + System.out.println("ok"); + return; + } + lafClass = Class.forName(UIManager.getSystemLookAndFeelClassName()); + UIManager.setLookAndFeel((LookAndFeel) lafClass.newInstance()); + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + frame = new JFrame(); + frame.setUndecorated(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setup(frame); + } + }); + + final Robot robot = new Robot(); + robot.setAutoDelay(20); + robot.keyPress(KeyEvent.VK_ALT); + robot.keyPress(KeyEvent.VK_F); + robot.keyRelease(KeyEvent.VK_F); + robot.keyRelease(KeyEvent.VK_ALT); + robot.waitForIdle(); + checkMnemonics(); + + robot.keyPress(KeyEvent.VK_ALT); + robot.keyPress(KeyEvent.VK_S); + robot.keyRelease(KeyEvent.VK_S); + robot.keyRelease(KeyEvent.VK_ALT); + robot.waitForIdle(); + checkMnemonics(); + System.out.println("ok"); + } finally { + frame.dispose(); + } + + } + + private static void checkMnemonics() throws Exception { + if ((Boolean) lafClass.getMethod("isMnemonicHidden").invoke(lafClass)) { + throw new RuntimeException("Mnemonics are hidden"); + } + } + + private static void setup(JFrame frame) { + JMenuBar menuBar = new JMenuBar(); + frame.setJMenuBar(menuBar); + + // First Menu, F - Mnemonic + JMenu firstMenu = new JMenu("First Menu"); + firstMenu.setMnemonic(KeyEvent.VK_F); + firstMenu.add(new JMenuItem("One", KeyEvent.VK_O)); + firstMenu.add(new JMenuItem("Two", KeyEvent.VK_T)); + menuBar.add(firstMenu); + + // Second Menu, S - Mnemonic + JMenu secondMenu = new JMenu("Second Menu"); + secondMenu.setMnemonic(KeyEvent.VK_S); + secondMenu.add(new JMenuItem("A Menu Item", KeyEvent.VK_A)); + menuBar.add(secondMenu); + + frame.setSize(350, 250); + frame.setVisible(true); + + } +} \ No newline at end of file diff --git a/jdk/test/javax/xml/jaxp/transform/8062923/XslSubstringTest.java b/jdk/test/javax/xml/jaxp/transform/8062923/XslSubstringTest.java index fcc36aefc0c..cb3594bf9dd 100644 --- a/jdk/test/javax/xml/jaxp/transform/8062923/XslSubstringTest.java +++ b/jdk/test/javax/xml/jaxp/transform/8062923/XslSubstringTest.java @@ -23,10 +23,11 @@ /** * @test - * @bug 8062923 8062924 + * @bug 8062923 8062924 8074297 8076290 * @run testng XslSubstringTest * @summary Test xsl substring function with negative, Inf and - * NaN length and few other use cases + * NaN length and few other use cases. Also test proper + * processing of supplementary characters by substring function. */ import java.io.StringReader; @@ -39,6 +40,7 @@ import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import static org.testng.Assert.assertEquals; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class XslSubstringTest { @@ -50,6 +52,36 @@ public class XslSubstringTest { + ""; final String xslPost = ""; + @DataProvider(name = "GeneralTestsData") + private Object[][] xmls() { + return new Object[][] { + { "||", "|s|"}, + { "||", "|sdf|"}, + { "||", "||" }, + { "||", "|sdf|" }, + // 8076290 bug test case + { "||", "|12|"}, + }; + } + + @DataProvider(name = "SupplementaryCharactersTestData") + private Object[][] dataSupplementaryCharacters() { + return new Object[][] { + // 8074297 bug test cases + { "||", "|BC|"}, + { "||", "|B|" }, + { "||", "|AB|"}, + { "||", "|BC|"}, + { "||", "|BC|"}, + { "||", "|𠀋|"}, + { "||", "|A|"}, + { "||", "|𠀋ABC|"}, + { "||", "|𠀋ABC|"}, + // 8076290 bug test case + { "||", "|𠀋|"}, + }; + } + private String testTransform(String xsl) throws Exception { //Prepare sources for transormation Source src = new StreamSource(new StringReader(xml)); @@ -78,27 +110,14 @@ public class XslSubstringTest { "||"); } - @Test - public void testGeneral1() throws Exception { - assertEquals(testTransform("||"), - "|s|"); + @Test(dataProvider = "GeneralTestsData") + public void testGeneralAll(String xsl, String result) throws Exception { + assertEquals(testTransform(xsl), result); } - @Test - public void testGeneral2() throws Exception { - assertEquals(testTransform("||"), - "|sdf|"); + @Test(dataProvider = "SupplementaryCharactersTestData") + public void testSupplementCharacters(String xsl, String result) throws Exception { + assertEquals(testTransform(xsl), result); } - @Test - public void testGeneral3() throws Exception { - assertEquals(testTransform("||"), - "||"); - } - - @Test - public void testGeneral4() throws Exception { - assertEquals(testTransform("||"), - "||"); - } } diff --git a/jdk/test/javax/xml/ws/8046817/GenerateEnumSchema.java b/jdk/test/javax/xml/ws/8046817/GenerateEnumSchema.java index 1edd3c23907..7617cfd9def 100644 --- a/jdk/test/javax/xml/ws/8046817/GenerateEnumSchema.java +++ b/jdk/test/javax/xml/ws/8046817/GenerateEnumSchema.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. * 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,57 +23,83 @@ /* * @test - * @bug 8046817 - * @summary schemagen fails to generate xsd for enum types + * @bug 8046817 8073357 + * @summary schemagen fails to generate xsd for enum types. + * Check that order of Enum values is preserved. * @run main/othervm GenerateEnumSchema */ import java.io.BufferedReader; import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; +import java.nio.file.Files; import java.nio.file.Paths; -import java.util.Scanner; +import java.util.stream.Collectors; public class GenerateEnumSchema { private static final String SCHEMA_OUTPUT_FILENAME = "schema1.xsd"; private static final File schemaOutputFile = new File(SCHEMA_OUTPUT_FILENAME); + private static final String[] expectedEnums = { + "\"FIRST\"", "\"ONE\"", "\"TWO\"", "\"THREE\"", + "\"FOUR\"", "\"FIVE\"", "\"SIX\"", "\"LAST\""}; + private static String schemaContent = ""; + + public static void main(String[] args) throws Exception { - public static void main(String[] args) throws Exception, IOException { //Check schema generation for class type runSchemaGen("TestClassType.java"); checkIfSchemaGenerated(); + readSchemaContent(); checkSchemaContent(""); checkSchemaContent(""); - schemaOutputFile.delete(); + //Check schema generation for enum type runSchemaGen("TestEnumType.java"); checkIfSchemaGenerated(); + readSchemaContent(); + //Check if Enum type schema is generated checkSchemaContent(""); - checkSchemaContent(""); - checkSchemaContent(""); - checkSchemaContent(""); + //Check the sequence of enum values order + checkEnumOrder(); schemaOutputFile.delete(); } + // Check if schema file successfully generated by schemagen private static void checkIfSchemaGenerated() { if (!schemaOutputFile.exists()) { throw new RuntimeException("FAIL:" + SCHEMA_OUTPUT_FILENAME + " was not generated by schemagen tool"); } } - private static void checkSchemaContent(String exp_token) throws FileNotFoundException { - System.out.print("Check if generated schema contains '" + exp_token + "' string: "); - try (Scanner scanner = new Scanner(schemaOutputFile)) { - if (scanner.findWithinHorizon(exp_token, 0) != null) { - System.out.println("OK"); - return; - } + //Read schema content from file + private static void readSchemaContent() throws Exception { + schemaContent = Files.lines(schemaOutputFile.toPath()).collect(Collectors.joining("")); + } + + // Check if schema file contains specific string + private static void checkSchemaContent(String expContent) { + System.out.print("Check if generated schema contains '" + expContent + "' string: "); + if (schemaContent.contains(expContent)) { + System.out.println("OK"); + return; } System.out.println("FAIL"); - throw new RuntimeException("The '" + exp_token + "' is not found in generated schema"); + throw new RuntimeException("The '" + expContent + "' is not found in generated schema"); + } + // Check if the generated schema contains all enum constants + // and their order is preserved + private static void checkEnumOrder() throws Exception { + int prevElem = -1; + for (String elem : expectedEnums) { + int curElem = schemaContent.indexOf(elem); + System.out.println(elem + " position = " + curElem); + if (curElem < prevElem) { + throw new RuntimeException("FAIL: Enum values order is incorrect or " + elem + " element is not found"); + } + prevElem = curElem; + } } private static String getClassFilePath(String filename) { diff --git a/jdk/test/javax/xml/ws/8046817/TestEnumType.java b/jdk/test/javax/xml/ws/8046817/TestEnumType.java index 785fb191c02..728e1b7187f 100644 --- a/jdk/test/javax/xml/ws/8046817/TestEnumType.java +++ b/jdk/test/javax/xml/ws/8046817/TestEnumType.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. * 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,5 +25,5 @@ import javax.xml.bind.annotation.XmlEnum; @XmlEnum(String.class) public enum TestEnumType { - ONE, TWO, THREE + FIRST, ONE, TWO, THREE, FOUR, FIVE, SIX, LAST } diff --git a/jdk/test/jdk/internal/jimage/JImageTest.java b/jdk/test/jdk/internal/jimage/JImageTest.java new file mode 100644 index 00000000000..51c0bfdbf57 --- /dev/null +++ b/jdk/test/jdk/internal/jimage/JImageTest.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @library /lib/testlibrary + * @build jdk.testlibrary.* + * @summary Test to see if jimage tool extracts and recreates correctly. + * @run main/timeout=360 JImageTest + */ + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; + +import jdk.testlibrary.ProcessTools; + + +/** + * Basic test for jimage tool. + */ +public class JImageTest { + private static void jimage(String... jimageArgs) throws Exception { + ArrayList args = new ArrayList<>(); + args.add("-ms8m"); + args.add("jdk.tools.jimage.Main"); + args.addAll(Arrays.asList(jimageArgs)); + + ProcessBuilder builder = ProcessTools.createJavaProcessBuilder(args.toArray(new String[args.size()])); + int res = builder.inheritIO().start().waitFor(); + + if (res != 0) { + throw new RuntimeException("JImageTest tool FAILED"); + } + } + + public static void main(String[] args) throws Exception { + final String JAVA_HOME = System.getProperty("java.home"); + Path jimagePath = Paths.get(JAVA_HOME, "bin", "jimage"); + Path bootimagePath = Paths.get(JAVA_HOME, "lib", "modules", "bootmodules.jimage"); + + if (Files.exists(jimagePath) && Files.exists(bootimagePath)) { + String jimage = jimagePath.toAbsolutePath().toString(); + String bootimage = bootimagePath.toAbsolutePath().toString(); + String extractDir = Paths.get(".", "extract").toAbsolutePath().toString(); + String recreateImage = Paths.get(".", "recreate.jimage").toAbsolutePath().toString(); + + jimage("extract", "--dir", extractDir, bootimage); + jimage("recreate", "--dir", extractDir, recreateImage); + + System.out.println("Test successful"); + } else { + System.out.println("Test skipped, no module image"); + } + + } +} diff --git a/jdk/test/jdk/lambda/FDTest.java b/jdk/test/jdk/lambda/FDTest.java deleted file mode 100644 index c207a61c946..00000000000 --- a/jdk/test/jdk/lambda/FDTest.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 shapegen.*; - -import com.sun.source.util.JavacTask; -import com.sun.tools.javac.util.Pair; - -import java.net.URI; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.tools.Diagnostic; -import javax.tools.JavaCompiler; -import javax.tools.JavaFileObject; -import javax.tools.SimpleJavaFileObject; -import javax.tools.StandardJavaFileManager; -import javax.tools.ToolProvider; - -import org.testng.annotations.Test; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.DataProvider; -import static org.testng.Assert.*; - -public class FDTest { - - public enum TestKind { - POSITIVE, - NEGATIVE; - - Collection getHierarchy(HierarchyGenerator hg) { - return this == POSITIVE ? - hg.getOK() : hg.getErr(); - } - } - - public static JavaCompiler comp; - public static StandardJavaFileManager fm; - - @BeforeSuite - static void init() { - // create default shared JavaCompiler - reused across multiple - // compilations - - comp = ToolProvider.getSystemJavaCompiler(); - fm = comp.getStandardFileManager(null, null, null); - } - - public static void main(String[] args) throws Exception { - init(); - - for (Pair fdtest : generateCases()) { - runTest(fdtest.fst, fdtest.snd, comp, fm); - } - } - - @Test(dataProvider = "fdCases") - public void testOneCase(TestKind tk, Hierarchy hs) - throws Exception { - FDTest.runTest(tk, hs, comp, fm); - } - - @DataProvider(name = "fdCases") - public Object[][] caseGenerator() { - List> cases = generateCases(); - Object[][] fdCases = new Object[cases.size()][]; - for (int i = 0; i < cases.size(); ++i) { - fdCases[i] = new Object[2]; - fdCases[i][0] = cases.get(i).fst; - fdCases[i][1] = cases.get(i).snd; - } - return fdCases; - } - - public static List> generateCases() { - ArrayList> list = new ArrayList<>(); - HierarchyGenerator hg = new HierarchyGenerator(); - for (TestKind tk : TestKind.values()) { - for (Hierarchy hs : tk.getHierarchy(hg)) { - list.add(new Pair<>(tk, hs)); - } - } - return list; - } - - public static void runTest(TestKind tk, Hierarchy hs, - JavaCompiler comp, StandardJavaFileManager fm) throws Exception { - new FDTest(tk, hs).run(comp, fm); - } - - TestKind tk; - Hierarchy hs; - DefenderTestSource source; - DiagnosticChecker diagChecker; - - public FDTest() {} - - FDTest(TestKind tk, Hierarchy hs) { - this.tk = tk; - this.hs = hs; - this.source = new DefenderTestSource(); - this.diagChecker = new DiagnosticChecker(); - } - - void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception { - JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker, - null, null, Arrays.asList(source)); - try { - ct.analyze(); - } catch (Throwable ex) { - fail("Error thrown when analyzing the following source:\n" + source.getCharContent(true)); - } - check(); - } - - void check() { - boolean errorExpected = tk == TestKind.NEGATIVE; - if (errorExpected != diagChecker.errorFound) { - fail("problem in source: \n" + - "\nerror found = " + diagChecker.errorFound + - "\nerror expected = " + errorExpected + - "\n" + dumpHierarchy() + - "\n" + source.getCharContent(true)); - } - } - - String dumpHierarchy() { - StringBuilder buf = new StringBuilder(); - buf.append("root = " + hs.root + "\n"); - for (ClassCase cc : hs.all) { - buf.append(" class name = " + cc.getName() + "\n"); - buf.append(" class OK = " + cc.get_OK() + "\n"); - buf.append(" prov = " + cc.get_mprov() + "\n"); - - } - return buf.toString(); - } - - class DefenderTestSource extends SimpleJavaFileObject { - - String source; - - public DefenderTestSource() { - super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE); - StringBuilder buf = new StringBuilder(); - List defaultRef = new ArrayList<>(); - for (ClassCase cc : hs.all) { - Hierarchy.genClassDef(buf, cc, null, defaultRef); - } - source = buf.toString(); - } - - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) { - return source; - } - } - - static class DiagnosticChecker implements javax.tools.DiagnosticListener { - - boolean errorFound; - - public void report(Diagnostic diagnostic) { - if (diagnostic.getKind() == Diagnostic.Kind.ERROR) { - errorFound = true; - } - } - } -} diff --git a/jdk/test/jdk/lambda/MethodReferenceTestFDCCE.java b/jdk/test/jdk/lambda/MethodReferenceTestFDCCE.java deleted file mode 100644 index dd5b2c88925..00000000000 --- a/jdk/test/jdk/lambda/MethodReferenceTestFDCCE.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import org.testng.annotations.Test; -import java.lang.reflect.Array; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -/** - * Method references and raw types. - * @author Robert Field - */ - -@Test -@SuppressWarnings({"rawtypes", "unchecked"}) -public class MethodReferenceTestFDCCE { - - static void assertCCE(Throwable t) { - assertEquals(t.getClass().getName(), "java.lang.ClassCastException"); - } - - interface Pred { boolean accept(T x); } - - interface Ps { boolean accept(short x); } - - interface Oo { Object too(int x); } - - interface Reto { T m(); } - - class A {} - class B extends A {} - - static boolean isMinor(int x) { - return x < 18; - } - - static boolean tst(A x) { - return true; - } - - static Object otst(Object x) { - return x; - } - - static boolean stst(Short x) { - return x < 18; - } - - static short ritst() { - return 123; - } - - public void testMethodReferenceFDPrim1() { - Pred p = MethodReferenceTestFDCCE::isMinor; - Pred p2 = p; - assertTrue(p2.accept((Byte)(byte)15)); - } - - public void testMethodReferenceFDPrim2() { - Pred p = MethodReferenceTestFDCCE::isMinor; - Pred p2 = p; - assertTrue(p2.accept((byte)15)); - } - - public void testMethodReferenceFDPrimICCE() { - Pred p = MethodReferenceTestFDCCE::isMinor; - Pred p2 = p; - try { - p2.accept(15); // should throw CCE - fail("Exception should have been thrown"); - } catch (Throwable t) { - assertCCE(t); - } - } - - public void testMethodReferenceFDPrimOCCE() { - Pred p = MethodReferenceTestFDCCE::isMinor; - Pred p2 = p; - try { - p2.accept(new Object()); // should throw CCE - fail("Exception should have been thrown"); - } catch (Throwable t) { - assertCCE(t); - } - } - - public void testMethodReferenceFDRef() { - Pred p = MethodReferenceTestFDCCE::tst; - Pred p2 = p; - assertTrue(p2.accept(new B())); - } - - public void testMethodReferenceFDRefCCE() { - Pred p = MethodReferenceTestFDCCE::tst; - Pred p2 = p; - try { - p2.accept(new A()); // should throw CCE - fail("Exception should have been thrown"); - } catch (Throwable t) { - assertCCE(t); - } - } - - public void testMethodReferenceFDPrimPrim() { - Ps p = MethodReferenceTestFDCCE::isMinor; - assertTrue(p.accept((byte)15)); - } - - public void testMethodReferenceFDPrimBoxed() { - Ps p = MethodReferenceTestFDCCE::stst; - assertTrue(p.accept((byte)15)); - } - - public void testMethodReferenceFDPrimRef() { - Oo p = MethodReferenceTestFDCCE::otst; - assertEquals(p.too(15).getClass().getName(), "java.lang.Integer"); - } - - public void testMethodReferenceFDRet1() { - Reto p = MethodReferenceTestFDCCE::ritst; - assertEquals(p.m(), (Short)(short)123); - } - -} \ No newline at end of file diff --git a/jdk/test/jdk/lambda/MethodReferenceTestInnerDefault.java b/jdk/test/jdk/lambda/MethodReferenceTestInnerDefault.java deleted file mode 100644 index 1074bdb9040..00000000000 --- a/jdk/test/jdk/lambda/MethodReferenceTestInnerDefault.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; - -/** - * @author Robert Field - */ - -interface IDSs { String m(String a); } - -interface InDefA { - default String xsA__(String s) { - return "A__xsA:" + s; - } - - default String xsAB_(String s) { - return "AB_xsA:" + s; - } - -} - -interface InDefB extends InDefA { - - default String xsAB_(String s) { - return "AB_xsB:" + s; - } - - default String xs_B_(String s) { - return "_B_xsB:" + s; - } -} - -@Test -public class MethodReferenceTestInnerDefault implements InDefB { - - public void testMethodReferenceInnerDefault() { - (new In()).testMethodReferenceInnerDefault(); - } - - class In { - - public void testMethodReferenceInnerDefault() { - IDSs q; - - q = MethodReferenceTestInnerDefault.this::xsA__; - assertEquals(q.m("*"), "A__xsA:*"); - - q = MethodReferenceTestInnerDefault.this::xsAB_; - assertEquals(q.m("*"), "AB_xsB:*"); - - q = MethodReferenceTestInnerDefault.this::xs_B_; - assertEquals(q.m("*"), "_B_xsB:*"); - } - } - -} diff --git a/jdk/test/jdk/lambda/MethodReferenceTestInnerInstance.java b/jdk/test/jdk/lambda/MethodReferenceTestInnerInstance.java deleted file mode 100644 index 0f1a13841a5..00000000000 --- a/jdk/test/jdk/lambda/MethodReferenceTestInnerInstance.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; - -/** - * @author Robert Field - */ - -@Test -public class MethodReferenceTestInnerInstance { - - public void testMethodReferenceInnerInstance() { - cia().cib().testMethodReferenceInstance(); - } - - public void testMethodReferenceInnerExternal() { - cia().cib().testMethodReferenceExternal(); - } - - interface SI { - String m(Integer a); - } - - class CIA { - - String xI(Integer i) { - return "xI:" + i; - } - - public class CIB { - - public void testMethodReferenceInstance() { - SI q; - - q = CIA.this::xI; - assertEquals(q.m(55), "xI:55"); - } - - public void testMethodReferenceExternal() { - SI q; - - q = (new E())::xI; - assertEquals(q.m(77), "ExI:77"); - } - } - - CIB cib() { - return new CIB(); - } - - class E { - - String xI(Integer i) { - return "ExI:" + i; - } - } - - } - - CIA cia() { - return new CIA(); - } -} diff --git a/jdk/test/jdk/lambda/MethodReferenceTestInnerVarArgsThis.java b/jdk/test/jdk/lambda/MethodReferenceTestInnerVarArgsThis.java deleted file mode 100644 index beac6f5b8a7..00000000000 --- a/jdk/test/jdk/lambda/MethodReferenceTestInnerVarArgsThis.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 org.testng.annotations.Test; -import java.lang.reflect.Array; - -import static org.testng.Assert.assertEquals; - -/** - * @author Robert Field - */ - -@Test -public class MethodReferenceTestInnerVarArgsThis { - - interface NsII { - - String m(Integer a, Integer b); - } - - interface Nsiii { - - String m(int a, int b, int c); - } - - interface Nsi { - - String m(int a); - } - - interface NsaO { - - String m(Object[] a); - } - - interface Nsai { - - String m(int[] a); - } - - interface Nsvi { - - String m(int... va); - } - - class CIA { - - String xvI(Integer... vi) { - StringBuilder sb = new StringBuilder("xvI:"); - for (Integer i : vi) { - sb.append(i); - sb.append("-"); - } - return sb.toString(); - } - - String xIvI(Integer f, Integer... vi) { - StringBuilder sb = new StringBuilder("xIvI:"); - sb.append(f); - for (Integer i : vi) { - sb.append(i); - sb.append("-"); - } - return sb.toString(); - } - - String xvi(int... vi) { - int sum = 0; - for (int i : vi) { - sum += i; - } - return "xvi:" + sum; - } - - String xIvi(Integer f, int... vi) { - int sum = 0; - for (int i : vi) { - sum += i; - } - return "xIvi:(" + f + ")" + sum; - } - - String xvO(Object... vi) { - StringBuilder sb = new StringBuilder("xvO:"); - for (Object i : vi) { - if (i.getClass().isArray()) { - sb.append("["); - int len = Array.getLength(i); - for (int x = 0; x < len; ++x) { - sb.append(Array.get(i, x)); - sb.append(","); - } - sb.append("]"); - - } else { - sb.append(i); - } - sb.append("*"); - } - return sb.toString(); - } - - public class CIB { - - // These should be processed as var args - public void testVarArgsNsSuperclass() { - NsII q; - - q = CIA.this::xvO; - assertEquals(q.m(55, 66), "xvO:55*66*"); - } - - public void testVarArgsNsArray() { - Nsai q; - - q = CIA.this::xvO; - assertEquals(q.m(new int[]{55, 66}), "xvO:[55,66,]*"); - } - - public void testVarArgsNsII() { - NsII q; - - q = CIA.this::xvI; - assertEquals(q.m(33, 7), "xvI:33-7-"); - - q = CIA.this::xIvI; - assertEquals(q.m(50, 40), "xIvI:5040-"); - - q = CIA.this::xvi; - assertEquals(q.m(100, 23), "xvi:123"); - - q = CIA.this::xIvi; - assertEquals(q.m(9, 21), "xIvi:(9)21"); - } - - public void testVarArgsNsiii() { - Nsiii q; - - q = CIA.this::xvI; - assertEquals(q.m(3, 2, 1), "xvI:3-2-1-"); - - q = CIA.this::xIvI; - assertEquals(q.m(888, 99, 2), "xIvI:88899-2-"); - - q = CIA.this::xvi; - assertEquals(q.m(900, 80, 7), "xvi:987"); - - q = CIA.this::xIvi; - assertEquals(q.m(333, 27, 72), "xIvi:(333)99"); - } - - public void testVarArgsNsi() { - Nsi q; - - q = CIA.this::xvI; - assertEquals(q.m(3), "xvI:3-"); - - q = CIA.this::xIvI; - assertEquals(q.m(888), "xIvI:888"); - - q = CIA.this::xvi; - assertEquals(q.m(900), "xvi:900"); - - q = CIA.this::xIvi; - assertEquals(q.m(333), "xIvi:(333)0"); - } - - // These should NOT be processed as var args - public void testVarArgsNsaO() { - NsaO q; - - q = CIA.this::xvO; - assertEquals(q.m(new String[]{"yo", "there", "dude"}), "xvO:yo*there*dude*"); - } - } - - CIB cib() { - return new CIB(); - } - - class E { - - String xI(Integer i) { - return "ExI:" + i; - } - } - } - - CIA cia() { - return new CIA(); - } - - // These should be processed as var args - public void testVarArgsNsSuperclass() { - cia().cib().testVarArgsNsSuperclass(); - } - - public void testVarArgsNsArray() { - cia().cib().testVarArgsNsArray(); - } - - public void testVarArgsNsII() { - cia().cib().testVarArgsNsII(); - } - - public void testVarArgsNsiii() { - cia().cib().testVarArgsNsiii(); - } - - public void testVarArgsNsi() { - cia().cib().testVarArgsNsi(); - } - - // These should NOT be processed as var args - - public void testVarArgsNsaO() { - cia().cib().testVarArgsNsaO(); - } - - -} diff --git a/jdk/test/jdk/lambda/MethodReferenceTestKinds.java b/jdk/test/jdk/lambda/MethodReferenceTestKinds.java deleted file mode 100644 index dc457353e50..00000000000 --- a/jdk/test/jdk/lambda/MethodReferenceTestKinds.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; - -/** - * @author Robert Field - */ - -@Test -public class MethodReferenceTestKinds extends MethodReferenceTestKindsSup { - - interface S0 { String get(); } - interface S1 { String get(MethodReferenceTestKinds x); } - interface S2 { String get(MethodReferenceTestKinds x, MethodReferenceTestKinds y); } - - interface SXN0 { MethodReferenceTestKindsBase make(MethodReferenceTestKinds x); } - interface SXN1 { MethodReferenceTestKindsBase make(MethodReferenceTestKinds x, String str); } - - interface SN0 { MethodReferenceTestKindsBase make(); } - interface SN1 { MethodReferenceTestKindsBase make(String x); } - - class In extends MethodReferenceTestKindsBase { - In(String val) { - this.val = val; - } - - In() { - this("blank"); - } - } - - String instanceMethod0() { return "IM:0-" + this; } - String instanceMethod1(MethodReferenceTestKinds x) { return "IM:1-" + this + x; } - - static String staticMethod0() { return "SM:0"; } - static String staticMethod1(MethodReferenceTestKinds x) { return "SM:1-" + x; } - - MethodReferenceTestKinds(String val) { - super(val); - } - - MethodReferenceTestKinds() { - super("blank"); - } - - MethodReferenceTestKinds inst(String val) { - return new MethodReferenceTestKinds(val); - } - - public void testMRBound() { - S0 var = this::instanceMethod0; - assertEquals(var.get(), "IM:0-MethodReferenceTestKinds(blank)"); - } - - public void testMRBoundArg() { - S1 var = this::instanceMethod1; - assertEquals(var.get(inst("arg")), "IM:1-MethodReferenceTestKinds(blank)MethodReferenceTestKinds(arg)"); - } - - public void testMRUnbound() { - S1 var = MethodReferenceTestKinds::instanceMethod0; - assertEquals(var.get(inst("rcvr")), "IM:0-MethodReferenceTestKinds(rcvr)"); - } - - public void testMRUnboundArg() { - S2 var = MethodReferenceTestKinds::instanceMethod1; - assertEquals(var.get(inst("rcvr"), inst("arg")), "IM:1-MethodReferenceTestKinds(rcvr)MethodReferenceTestKinds(arg)"); - } - - public void testMRSuper() { - S0 var = super::instanceMethod0; - assertEquals(var.get(), "SIM:0-MethodReferenceTestKinds(blank)"); - } - - public void testMRSuperArg() { - S1 var = super::instanceMethod1; - assertEquals(var.get(inst("arg")), "SIM:1-MethodReferenceTestKinds(blank)MethodReferenceTestKinds(arg)"); - } - - public void testMRStatic() { - S0 var = MethodReferenceTestKinds::staticMethod0; - assertEquals(var.get(), "SM:0"); - } - - public void testMRStaticArg() { - S1 var = MethodReferenceTestKinds::staticMethod1; - assertEquals(var.get(inst("arg")), "SM:1-MethodReferenceTestKinds(arg)"); - } - - public void testMRTopLevel() { - SN0 var = MethodReferenceTestKindsBase::new; - assertEquals(var.make().toString(), "MethodReferenceTestKindsBase(blank)"); - } - - public void testMRTopLevelArg() { - SN1 var = MethodReferenceTestKindsBase::new; - assertEquals(var.make("name").toString(), "MethodReferenceTestKindsBase(name)"); - } -/* unbound inner case not supported anymore (dropped by EG) - public void testMRUnboundInner() { - SXN0 var = MethodReferenceTestKinds.In::new; - assertEquals(var.make(inst("out")).toString(), "In(blank)"); - } - - public void testMRUnboundInnerArg() { - SXN1 var = MethodReferenceTestKinds.In::new; - assertEquals(var.make(inst("out"), "name").toString(), "In(name)"); - } -*/ - public void testMRImplicitInner() { - SN0 var = MethodReferenceTestKinds.In::new; - assertEquals(var.make().toString(), "In(blank)"); - } - - public void testMRImplicitInnerArg() { - SN1 var = MethodReferenceTestKinds.In::new; - assertEquals(var.make("name").toString(), "In(name)"); - } - -} - - -class MethodReferenceTestKindsBase { - String val = "unset"; - - public String toString() { - return getClass().getSimpleName() + "(" + val + ")"; - } - - MethodReferenceTestKindsBase(String val) { - this.val = val; - } - - MethodReferenceTestKindsBase() { - this("blank"); - } - -} - -class MethodReferenceTestKindsSup extends MethodReferenceTestKindsBase { - String instanceMethod0() { return "SIM:0-" + this; } - String instanceMethod1(MethodReferenceTestKinds x) { return "SIM:1-" + this + x; } - - MethodReferenceTestKindsSup(String val) { - super(val); - } - -} - diff --git a/jdk/test/jdk/lambda/MethodReferenceTestNew.java b/jdk/test/jdk/lambda/MethodReferenceTestNew.java deleted file mode 100644 index baec244e7ff..00000000000 --- a/jdk/test/jdk/lambda/MethodReferenceTestNew.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; - -/** - * @author Robert Field - */ - -@Test -public class MethodReferenceTestNew { - - interface M0 { - - T m(); - } - - static class N0 { - - N0() { - } - } - - interface M1 { - - T m(Integer a); - } - - static class N1 { - - int i; - - N1(int i) { - this.i = i; - } - } - - interface M2 { - - T m(Integer n, String o); - } - - static class N2 { - - Number n; - Object o; - - N2(Number n, Object o) { - this.n = n; - this.o = o; - } - - public String toString() { - return "N2(" + n + "," + o + ")"; - } - } - - interface MV { - - NV m(Integer ai, int i); - } - - static class NV { - - int i; - - NV(int... v) { - i = 0; - for (int x : v) { - i += x; - } - } - - public String toString() { - return "NV(" + i + ")"; - } - } - - public void testConstructorReference0() { - M0 q; - - q = N0::new; - assertEquals(q.m().getClass().getSimpleName(), "N0"); - } - - public void testConstructorReference1() { - M1 q; - - q = N1::new; - assertEquals(q.m(14).getClass().getSimpleName(), "N1"); - } - - public void testConstructorReference2() { - M2 q; - - q = N2::new; - assertEquals(q.m(7, "hi").toString(), "N2(7,hi)"); - } - - public void testConstructorReferenceVarArgs() { - MV q; - - q = NV::new; - assertEquals(q.m(5, 45).toString(), "NV(50)"); - } - -} - diff --git a/jdk/test/jdk/lambda/MethodReferenceTestNewInner.java b/jdk/test/jdk/lambda/MethodReferenceTestNewInner.java deleted file mode 100644 index a4f17d0f67e..00000000000 --- a/jdk/test/jdk/lambda/MethodReferenceTestNewInner.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; - -/** - * @author Robert Field - */ - -@Test -public class MethodReferenceTestNewInner { - - String note = "NO NOTE"; - - interface M0 { - - T m(); - } - - interface MP { - - T m(MethodReferenceTestNewInner m); - } - - class N0 { - - N0() { - } - } - - interface M1 { - - T m(Integer a); - } - - class N1 { - - int i; - - N1(int i) { - this.i = i; - } - } - - interface M2 { - - T m(Integer n, String o); - } - - class N2 { - - Number n; - Object o; - - N2(Number n, Object o) { - this.n = n; - this.o = o; - } - - public String toString() { - return note + ":N2(" + n + "," + o + ")"; - } - } - - interface MV { - - NV m(Integer ai, int i); - } - - class NV { - - int i; - - NV(int... v) { - i = 0; - for (int x : v) { - i += x; - } - } - - public String toString() { - return note + ":NV(" + i + ")"; - } - } - -/* unbound constructor case not supported anymore (dropped by EG) - public static void testConstructorReferenceP() { - MP q; - - q = N0::new; - assertEquals(q.m(new MethodReferenceTestNewInner()).getClass().getSimpleName(), "N0"); - } -*/ - public void testConstructorReference0() { - M0 q; - - q = N0::new; - assertEquals(q.m().getClass().getSimpleName(), "N0"); - } - - public void testConstructorReference1() { - M1 q; - - q = N1::new; - assertEquals(q.m(14).getClass().getSimpleName(), "N1"); - } - - public void testConstructorReference2() { - M2 q; - - note = "T2"; - q = N2::new; - assertEquals(q.m(7, "hi").toString(), "T2:N2(7,hi)"); - } - - /*** - public void testConstructorReferenceVarArgs() { - MV q; - - note = "TVA"; - q = NV::new; - assertEquals(q.m(5, 45).toString(), "TNV:NV(50)"); - } - ***/ - -} - - diff --git a/jdk/test/jdk/lambda/MethodReferenceTestSuper.java b/jdk/test/jdk/lambda/MethodReferenceTestSuper.java deleted file mode 100644 index 211afb15317..00000000000 --- a/jdk/test/jdk/lambda/MethodReferenceTestSuper.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; - - - -/** - * @author Robert Field - */ - -interface SPRI { String m(String a); } - -class SPRA { - String xsA__(String s) { - return "A__xsA:" + s; - } - - String xsA_M(String s) { - return "A_MxsA:" + s; - } - - String xsAB_(String s) { - return "AB_xsA:" + s; - } - - String xsABM(String s) { - return "ABMxsA:" + s; - } - -} - -class SPRB extends SPRA { - - String xsAB_(String s) { - return "AB_xsB:" + s; - } - - String xsABM(String s) { - return "ABMxsB:" + s; - } - - String xs_B_(String s) { - return "_B_xsB:" + s; - } - - String xs_BM(String s) { - return "_BMxsB:" + s; - } - -} - -@Test -public class MethodReferenceTestSuper extends SPRB { - - String xsA_M(String s) { - return "A_MxsM:" + s; - } - - - String xsABM(String s) { - return "ABMxsM:" + s; - } - - String xs_BM(String s) { - return "_BMxsM:" + s; - } - - public void testMethodReferenceSuper() { - SPRI q; - - q = super::xsA__; - assertEquals(q.m("*"), "A__xsA:*"); - - q = super::xsA_M; - assertEquals(q.m("*"), "A_MxsA:*"); - - q = super::xsAB_; - assertEquals(q.m("*"), "AB_xsB:*"); - - q = super::xsABM; - assertEquals(q.m("*"), "ABMxsB:*"); - - q = super::xs_B_; - assertEquals(q.m("*"), "_B_xsB:*"); - - q = super::xs_BM; - assertEquals(q.m("*"), "_BMxsB:*"); - } - -} diff --git a/jdk/test/jdk/lambda/MethodReferenceTestVarArgs.java b/jdk/test/jdk/lambda/MethodReferenceTestVarArgs.java deleted file mode 100644 index d2926f00ceb..00000000000 --- a/jdk/test/jdk/lambda/MethodReferenceTestVarArgs.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 org.testng.annotations.Test; -import java.lang.reflect.Array; - -import static org.testng.Assert.assertEquals; - -/** - * @author Robert Field - */ - -@Test -public class MethodReferenceTestVarArgs { - - interface SII { - - String m(Integer a, Integer b); - } - - interface Siii { - - String m(int a, int b, int c); - } - - interface Si { - - String m(int a); - } - - interface SaO { - - String m(Object[] a); - } - - interface Sai { - - String m(int[] a); - } - - interface Svi { - - String m(int... va); - } - - // These should be processed as var args - - static String xvI(Integer... vi) { - StringBuilder sb = new StringBuilder("xvI:"); - for (Integer i : vi) { - sb.append(i); - sb.append("-"); - } - return sb.toString(); - } - - static String xIvI(Integer f, Integer... vi) { - StringBuilder sb = new StringBuilder("xIvI:"); - sb.append(f); - for (Integer i : vi) { - sb.append(i); - sb.append("-"); - } - return sb.toString(); - } - - static String xvi(int... vi) { - int sum = 0; - for (int i : vi) { - sum += i; - } - return "xvi:" + sum; - } - - static String xIvi(Integer f, int... vi) { - int sum = 0; - for (int i : vi) { - sum += i; - } - return "xIvi:(" + f + ")" + sum; - } - - static String xvO(Object... vi) { - StringBuilder sb = new StringBuilder("xvO:"); - for (Object i : vi) { - if (i.getClass().isArray()) { - sb.append("["); - int len = Array.getLength(i); - for (int x = 0; x < len; ++x) { - sb.append(Array.get(i, x)); - sb.append(","); - } - sb.append("]"); - - } else { - sb.append(i); - } - sb.append("*"); - } - return sb.toString(); - } - - public void testVarArgsSuperclass() { - SII q; - - q = MethodReferenceTestVarArgs::xvO; - assertEquals(q.m(55,66), "xvO:55*66*"); - } - - public void testVarArgsArray() { - Sai q; - - q = MethodReferenceTestVarArgs::xvO; - assertEquals(q.m(new int[] { 55,66 } ), "xvO:[55,66,]*"); - } - - public void testVarArgsII() { - SII q; - - q = MethodReferenceTestVarArgs::xvI; - assertEquals(q.m(33,7), "xvI:33-7-"); - - q = MethodReferenceTestVarArgs::xIvI; - assertEquals(q.m(50,40), "xIvI:5040-"); - - q = MethodReferenceTestVarArgs::xvi; - assertEquals(q.m(100,23), "xvi:123"); - - q = MethodReferenceTestVarArgs::xIvi; - assertEquals(q.m(9,21), "xIvi:(9)21"); - } - - public void testVarArgsiii() { - Siii q; - - q = MethodReferenceTestVarArgs::xvI; - assertEquals(q.m(3, 2, 1), "xvI:3-2-1-"); - - q = MethodReferenceTestVarArgs::xIvI; - assertEquals(q.m(888, 99, 2), "xIvI:88899-2-"); - - q = MethodReferenceTestVarArgs::xvi; - assertEquals(q.m(900,80,7), "xvi:987"); - - q = MethodReferenceTestVarArgs::xIvi; - assertEquals(q.m(333,27, 72), "xIvi:(333)99"); - } - - public void testVarArgsi() { - Si q; - - q = MethodReferenceTestVarArgs::xvI; - assertEquals(q.m(3), "xvI:3-"); - - q = MethodReferenceTestVarArgs::xIvI; - assertEquals(q.m(888), "xIvI:888"); - - q = MethodReferenceTestVarArgs::xvi; - assertEquals(q.m(900), "xvi:900"); - - q = MethodReferenceTestVarArgs::xIvi; - assertEquals(q.m(333), "xIvi:(333)0"); - } - - // These should NOT be processed as var args - - public void testVarArgsaO() { - SaO q; - - q = MethodReferenceTestVarArgs::xvO; - assertEquals(q.m(new String[] { "yo", "there", "dude" }), "xvO:yo*there*dude*"); - } - - -} diff --git a/jdk/test/jdk/lambda/MethodReferenceTestVarArgsExt.java b/jdk/test/jdk/lambda/MethodReferenceTestVarArgsExt.java deleted file mode 100644 index a3a967ce37d..00000000000 --- a/jdk/test/jdk/lambda/MethodReferenceTestVarArgsExt.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 org.testng.annotations.Test; -import java.lang.reflect.Array; - -import static org.testng.Assert.assertEquals; - -/** - * @author Robert Field - */ - -interface NXII { String m(Integer a, Integer b); } - -interface NXiii { String m(int a, int b, int c); } - -interface NXi { String m(int a); } - -interface NXaO { String m(Object[] a); } - -interface NXai { String m(int[] a); } - -interface NXvi { String m(int... va); } - -@Test -public class MethodReferenceTestVarArgsExt { - - // These should be processed as var args - - public void testVarArgsNXSuperclass() { - NXII q; - - q = (new Ext())::xvO; - assertEquals(q.m(55,66), "xvO:55*66*"); - } - - public void testVarArgsNXArray() { - NXai q; - - q = (new Ext())::xvO; - assertEquals(q.m(new int[] { 55,66 } ), "xvO:[55,66,]*"); - } - - public void testVarArgsNXII() { - NXII q; - - q = (new Ext())::xvI; - assertEquals(q.m(33,7), "xvI:33-7-"); - - q = (new Ext())::xIvI; - assertEquals(q.m(50,40), "xIvI:5040-"); - - q = (new Ext())::xvi; - assertEquals(q.m(100,23), "xvi:123"); - - q = (new Ext())::xIvi; - assertEquals(q.m(9,21), "xIvi:(9)21"); - } - - public void testVarArgsNXiii() { - NXiii q; - - q = (new Ext())::xvI; - assertEquals(q.m(3, 2, 1), "xvI:3-2-1-"); - - q = (new Ext())::xIvI; - assertEquals(q.m(888, 99, 2), "xIvI:88899-2-"); - - q = (new Ext())::xvi; - assertEquals(q.m(900,80,7), "xvi:987"); - - q = (new Ext())::xIvi; - assertEquals(q.m(333,27, 72), "xIvi:(333)99"); - } - - public void testVarArgsNXi() { - NXi q; - - q = (new Ext())::xvI; - assertEquals(q.m(3), "xvI:3-"); - - q = (new Ext())::xIvI; - assertEquals(q.m(888), "xIvI:888"); - - q = (new Ext())::xvi; - assertEquals(q.m(900), "xvi:900"); - - q = (new Ext())::xIvi; - assertEquals(q.m(333), "xIvi:(333)0"); - } - - // These should NOT be processed as var args - - public void testVarArgsNXaO() { - NXaO q; - - q = (new Ext())::xvO; - assertEquals(q.m(new String[] { "yo", "there", "dude" }), "xvO:yo*there*dude*"); - } - - -} - -class Ext { - - String xvI(Integer... vi) { - StringBuilder sb = new StringBuilder("xvI:"); - for (Integer i : vi) { - sb.append(i); - sb.append("-"); - } - return sb.toString(); - } - - String xIvI(Integer f, Integer... vi) { - StringBuilder sb = new StringBuilder("xIvI:"); - sb.append(f); - for (Integer i : vi) { - sb.append(i); - sb.append("-"); - } - return sb.toString(); - } - - String xvi(int... vi) { - int sum = 0; - for (int i : vi) { - sum += i; - } - return "xvi:" + sum; - } - - String xIvi(Integer f, int... vi) { - int sum = 0; - for (int i : vi) { - sum += i; - } - return "xIvi:(" + f + ")" + sum; - } - - String xvO(Object... vi) { - StringBuilder sb = new StringBuilder("xvO:"); - for (Object i : vi) { - if (i.getClass().isArray()) { - sb.append("["); - int len = Array.getLength(i); - for (int x = 0; x < len; ++x) { - sb.append(Array.get(i, x)); - sb.append(","); - } - sb.append("]"); - - } else { - sb.append(i); - } - sb.append("*"); - } - return sb.toString(); - } - - -} diff --git a/jdk/test/jdk/lambda/MethodReferenceTestVarArgsSuper.java b/jdk/test/jdk/lambda/MethodReferenceTestVarArgsSuper.java deleted file mode 100644 index 82e417cf384..00000000000 --- a/jdk/test/jdk/lambda/MethodReferenceTestVarArgsSuper.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 org.testng.annotations.Test; -import java.lang.reflect.Array; - -import static org.testng.Assert.assertEquals; - - -/** - * @author Robert Field - */ - -class MethodReferenceTestVarArgsSuper_Sub { - - String xvI(Integer... vi) { - StringBuilder sb = new StringBuilder("xvI:"); - for (Integer i : vi) { - sb.append(i); - sb.append("-"); - } - return sb.toString(); - } - - String xIvI(Integer f, Integer... vi) { - StringBuilder sb = new StringBuilder("xIvI:"); - sb.append(f); - for (Integer i : vi) { - sb.append(i); - sb.append("-"); - } - return sb.toString(); - } - - String xvi(int... vi) { - int sum = 0; - for (int i : vi) { - sum += i; - } - return "xvi:" + sum; - } - - String xIvi(Integer f, int... vi) { - int sum = 0; - for (int i : vi) { - sum += i; - } - return "xIvi:(" + f + ")" + sum; - } - - String xvO(Object... vi) { - StringBuilder sb = new StringBuilder("xvO:"); - for (Object i : vi) { - if (i.getClass().isArray()) { - sb.append("["); - int len = Array.getLength(i); - for (int x = 0; x < len; ++x) { - sb.append(Array.get(i, x)); - sb.append(","); - } - sb.append("]"); - - } else { - sb.append(i); - } - sb.append("*"); - } - return sb.toString(); - } -} - -@Test -public class MethodReferenceTestVarArgsSuper extends MethodReferenceTestVarArgsSuper_Sub { - - interface SPRII { String m(Integer a, Integer b); } - - interface SPRiii { String m(int a, int b, int c); } - - interface SPRi { String m(int a); } - - interface SPRaO { String m(Object[] a); } - - interface SPRai { String m(int[] a); } - - interface SPRvi { String m(int... va); } - - String xvI(Integer... vi) { - return "ERROR"; - } - - String xIvI(Integer f, Integer... vi) { - return "ERROR"; - } - - String xvi(int... vi) { - return "ERROR"; - } - - String xIvi(Integer f, int... vi) { - return "ERROR"; - } - - String xvO(Object... vi) { - return "ERROR"; - } - - // These should be processed as var args - - public void testVarArgsSPRSuperclass() { - SPRII q; - - q = super::xvO; - assertEquals(q.m(55,66), "xvO:55*66*"); - } - - public void testVarArgsSPRArray() { - SPRai q; - - q = super::xvO; - assertEquals(q.m(new int[] { 55,66 } ), "xvO:[55,66,]*"); - } - - public void testVarArgsSPRII() { - SPRII q; - - q = super::xvI; - assertEquals(q.m(33,7), "xvI:33-7-"); - - q = super::xIvI; - assertEquals(q.m(50,40), "xIvI:5040-"); - - q = super::xvi; - assertEquals(q.m(100,23), "xvi:123"); - - q = super::xIvi; - assertEquals(q.m(9,21), "xIvi:(9)21"); - } - - public void testVarArgsSPRiii() { - SPRiii q; - - q = super::xvI; - assertEquals(q.m(3, 2, 1), "xvI:3-2-1-"); - - q = super::xIvI; - assertEquals(q.m(888, 99, 2), "xIvI:88899-2-"); - - q = super::xvi; - assertEquals(q.m(900,80,7), "xvi:987"); - - q = super::xIvi; - assertEquals(q.m(333,27, 72), "xIvi:(333)99"); - } - - public void testVarArgsSPRi() { - SPRi q; - - q = super::xvI; - assertEquals(q.m(3), "xvI:3-"); - - q = super::xIvI; - assertEquals(q.m(888), "xIvI:888"); - - q = super::xvi; - assertEquals(q.m(900), "xvi:900"); - - q = super::xIvi; - assertEquals(q.m(333), "xIvi:(333)0"); - } - - // These should NOT be processed as var args - - public void testVarArgsSPRaO() { - SPRaO q; - - q = super::xvO; - assertEquals(q.m(new String[] { "yo", "there", "dude" }), "xvO:yo*there*dude*"); - } -} - diff --git a/jdk/test/jdk/lambda/MethodReferenceTestVarArgsSuperDefault.java b/jdk/test/jdk/lambda/MethodReferenceTestVarArgsSuperDefault.java deleted file mode 100644 index 8388b60ec8d..00000000000 --- a/jdk/test/jdk/lambda/MethodReferenceTestVarArgsSuperDefault.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 org.testng.annotations.Test; -import java.lang.reflect.Array; - -import static org.testng.Assert.assertEquals; - -/** - * @author Robert Field - */ - -interface MethodReferenceTestVarArgsSuperDefault_I { - - default String xvI(Integer... vi) { - StringBuilder sb = new StringBuilder("xvI:"); - for (Integer i : vi) { - sb.append(i); - sb.append("-"); - } - return sb.toString(); - } - - default String xIvI(Integer f, Integer... vi) { - StringBuilder sb = new StringBuilder("xIvI:"); - sb.append(f); - for (Integer i : vi) { - sb.append(i); - sb.append("-"); - } - return sb.toString(); - } - - default String xvi(int... vi) { - int sum = 0; - for (int i : vi) { - sum += i; - } - return "xvi:" + sum; - } - - default String xIvi(Integer f, int... vi) { - int sum = 0; - for (int i : vi) { - sum += i; - } - return "xIvi:(" + f + ")" + sum; - } - - default String xvO(Object... vi) { - StringBuilder sb = new StringBuilder("xvO:"); - for (Object i : vi) { - if (i.getClass().isArray()) { - sb.append("["); - int len = Array.getLength(i); - for (int x = 0; x < len; ++x) { - sb.append(Array.get(i, x)); - sb.append(","); - } - sb.append("]"); - - } else { - sb.append(i); - } - sb.append("*"); - } - return sb.toString(); - } -} - -@Test -public class MethodReferenceTestVarArgsSuperDefault implements MethodReferenceTestVarArgsSuperDefault_I { - - interface DSPRII { String m(Integer a, Integer b); } - - interface DSPRiii { String m(int a, int b, int c); } - - interface DSPRi { String m(int a); } - - interface DSPRaO { String m(Object[] a); } - - interface DSPRai { String m(int[] a); } - - interface DSPRvi { String m(int... va); } - - // These should be processed as var args - - public void testVarArgsSPRSuperclass() { - DSPRII q; - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xvO; - assertEquals(q.m(55,66), "xvO:55*66*"); - } - - public void testVarArgsSPRArray() { - DSPRai q; - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xvO; - assertEquals(q.m(new int[] { 55,66 } ), "xvO:[55,66,]*"); - } - - public void testVarArgsSPRII() { - DSPRII q; - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xvI; - assertEquals(q.m(33,7), "xvI:33-7-"); - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xIvI; - assertEquals(q.m(50,40), "xIvI:5040-"); - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xvi; - assertEquals(q.m(100,23), "xvi:123"); - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xIvi; - assertEquals(q.m(9,21), "xIvi:(9)21"); - } - - public void testVarArgsSPRiii() { - DSPRiii q; - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xvI; - assertEquals(q.m(3, 2, 1), "xvI:3-2-1-"); - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xIvI; - assertEquals(q.m(888, 99, 2), "xIvI:88899-2-"); - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xvi; - assertEquals(q.m(900,80,7), "xvi:987"); - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xIvi; - assertEquals(q.m(333,27, 72), "xIvi:(333)99"); - } - - public void testVarArgsSPRi() { - DSPRi q; - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xvI; - assertEquals(q.m(3), "xvI:3-"); - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xIvI; - assertEquals(q.m(888), "xIvI:888"); - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xvi; - assertEquals(q.m(900), "xvi:900"); - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xIvi; - assertEquals(q.m(333), "xIvi:(333)0"); - } - - // These should NOT be processed as var args - - public void testVarArgsSPRaO() { - DSPRaO q; - - q = MethodReferenceTestVarArgsSuperDefault_I.super::xvO; - assertEquals(q.m(new String[] { "yo", "there", "dude" }), "xvO:yo*there*dude*"); - } - - -} - diff --git a/jdk/test/jdk/lambda/MethodReferenceTestVarArgsThis.java b/jdk/test/jdk/lambda/MethodReferenceTestVarArgsThis.java deleted file mode 100644 index 2681a22e1da..00000000000 --- a/jdk/test/jdk/lambda/MethodReferenceTestVarArgsThis.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 org.testng.annotations.Test; -import java.lang.reflect.Array; - -import static org.testng.Assert.assertEquals; - -/** - * @author Robert Field - */ - -interface NsII { String m(Integer a, Integer b); } - -interface Nsiii { String m(int a, int b, int c); } - -interface Nsi { String m(int a); } - -interface NsaO { String m(Object[] a); } - -interface Nsai { String m(int[] a); } - -interface Nsvi { String m(int... va); } - -@Test -public class MethodReferenceTestVarArgsThis { - - // These should be processed as var args - - String xvI(Integer... vi) { - StringBuilder sb = new StringBuilder("xvI:"); - for (Integer i : vi) { - sb.append(i); - sb.append("-"); - } - return sb.toString(); - } - - String xIvI(Integer f, Integer... vi) { - StringBuilder sb = new StringBuilder("xIvI:"); - sb.append(f); - for (Integer i : vi) { - sb.append(i); - sb.append("-"); - } - return sb.toString(); - } - - String xvi(int... vi) { - int sum = 0; - for (int i : vi) { - sum += i; - } - return "xvi:" + sum; - } - - String xIvi(Integer f, int... vi) { - int sum = 0; - for (int i : vi) { - sum += i; - } - return "xIvi:(" + f + ")" + sum; - } - - String xvO(Object... vi) { - StringBuilder sb = new StringBuilder("xvO:"); - for (Object i : vi) { - if (i.getClass().isArray()) { - sb.append("["); - int len = Array.getLength(i); - for (int x = 0; x < len; ++x) { - sb.append(Array.get(i, x)); - sb.append(","); - } - sb.append("]"); - - } else { - sb.append(i); - } - sb.append("*"); - } - return sb.toString(); - } - - public void testVarArgsNsSuperclass() { - NsII q; - - q = this::xvO; - assertEquals(q.m(55,66), "xvO:55*66*"); - } - - public void testVarArgsNsArray() { - Nsai q; - - q = this::xvO; - assertEquals(q.m(new int[] { 55,66 } ), "xvO:[55,66,]*"); - } - - public void testVarArgsNsII() { - NsII q; - - q = this::xvI; - assertEquals(q.m(33,7), "xvI:33-7-"); - - q = this::xIvI; - assertEquals(q.m(50,40), "xIvI:5040-"); - - q = this::xvi; - assertEquals(q.m(100,23), "xvi:123"); - - q = this::xIvi; - assertEquals(q.m(9,21), "xIvi:(9)21"); - } - - public void testVarArgsNsiii() { - Nsiii q; - - q = this::xvI; - assertEquals(q.m(3, 2, 1), "xvI:3-2-1-"); - - q = this::xIvI; - assertEquals(q.m(888, 99, 2), "xIvI:88899-2-"); - - q = this::xvi; - assertEquals(q.m(900,80,7), "xvi:987"); - - q = this::xIvi; - assertEquals(q.m(333,27, 72), "xIvi:(333)99"); - } - - public void testVarArgsNsi() { - Nsi q; - - q = this::xvI; - assertEquals(q.m(3), "xvI:3-"); - - q = this::xIvI; - assertEquals(q.m(888), "xIvI:888"); - - q = this::xvi; - assertEquals(q.m(900), "xvi:900"); - - q = this::xIvi; - assertEquals(q.m(333), "xIvi:(333)0"); - } - - // These should NOT be processed as var args - - public void testVarArgsNsaO() { - NsaO q; - - q = this::xvO; - assertEquals(q.m(new String[] { "yo", "there", "dude" }), "xvO:yo*there*dude*"); - } - - -} diff --git a/jdk/test/jdk/lambda/shapegen/ClassCase.java b/jdk/test/jdk/lambda/shapegen/ClassCase.java deleted file mode 100644 index 85e942dffc6..00000000000 --- a/jdk/test/jdk/lambda/shapegen/ClassCase.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 shapegen; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * - * @author Robert Field - */ -public class ClassCase { - - public enum Kind { - IVAC (true, "v"), - IPRESENT (true, "p"), - IDEFAULT (true, "d"), - CNONE (false, "n"), - CABSTRACT (false, "a"), - CCONCRETE (false, "c"); - - private final String prefix; - public final boolean isInterface; - - Kind(boolean isInterface, String prefix) { - this.isInterface = isInterface; - this.prefix = prefix; - } - - public String getPrefix() { return prefix; } - } - - public final Kind kind; - private final ClassCase superclass; - private final List supertypes; - - private String name; - private boolean _OK; - private boolean _HasClassMethod; - private Set _mprov; - private boolean _IsConcrete; - private boolean _HasDefault; - private ClassCase _mres; - private ClassCase _mdefend; - - private Set executed = new HashSet(); - - public ClassCase(Kind kind, ClassCase superclass, List interfaces) { - this.kind = kind; - this.superclass = superclass; - - // Set supertypes from superclass (if any) and interfaces - List lc; - if (superclass == null) { - lc = interfaces; - } else { - lc = new ArrayList<>(); - lc.add(superclass); - lc.addAll(interfaces); - } - this.supertypes = lc; - } - - public final boolean isInterface() { return kind.isInterface; } - public final boolean isClass() { return !kind.isInterface; } - - public Set get_mprov() { - exec(RuleGroup.PROVENENCE); - return _mprov; - } - - public void set_mprov(ClassCase cc) { - Set s = new HashSet<>(); - s.add(cc); - _mprov = s; - } - - public void set_mprov(Set s) { - _mprov = s; - } - - public ClassCase get_mres() { - exec(RuleGroup.RESOLUTION); - return _mres; - } - - public void set_mres(ClassCase cc) { - _mres = cc; - } - - public ClassCase get_mdefend() { - exec(RuleGroup.DEFENDER); - return _mdefend; - } - - public void set_mdefend(ClassCase cc) { - _mdefend = cc; - } - - public boolean get_HasClassMethod() { - exec(RuleGroup.PROVENENCE); - return _HasClassMethod; - } - - public void set_HasClassMethod(boolean bool) { - _HasClassMethod = bool; - } - - public boolean get_HasDefault() { - exec(RuleGroup.MARKER); - return _HasDefault; - } - - public void set_HasDefault(boolean bool) { - _HasDefault = bool; - } - - public boolean get_IsConcrete() { - exec(RuleGroup.MARKER); - return _IsConcrete; - } - - public void set_IsConcrete(boolean bool) { - _IsConcrete = bool; - } - - public boolean get_OK() { - exec(RuleGroup.CHECKING); - return _OK; - } - - public void set_OK(boolean bool) { - _OK = bool; - } - - public boolean isMethodDefined() { - for (ClassCase cc : supertypes) { - if (cc.isMethodDefined()) { - return true; - } - } - switch (kind) { - case CCONCRETE: - case CABSTRACT: - case IPRESENT: - case IDEFAULT: - return true; - default: - return false; - } - } - - public boolean isAbstract() { - return isMethodDefined() && (get_mres()==null); - } - - public boolean hasSuperclass() { - return superclass != null; - } - - public ClassCase getSuperclass() { - return superclass; - } - - public List getSupertypes() { - return supertypes; - } - - public List getInterfaces() { - if (superclass != null) { - if (supertypes.get(0) != superclass) { - throw new AssertionError("superclass missing from supertypes"); - } - return supertypes.subList(1, supertypes.size()); - } else { - return supertypes; - } - } - - public boolean isSubtypeOf(ClassCase cc) { - // S-Refl - if (cc.equals(this)) { - return true; - } - - // S-Def - for (ClassCase sp : getSupertypes()) { - if (cc.equals(sp)) { - return true; - } - } - - // _S-Trans - for (ClassCase sp : getSupertypes()) { - if (sp.isSubtypeOf(cc)) { - return true; - } - } - - return false; - } - - public void init(Map namingContext) { - if (name != null) { - return; // Already inited - } - - for (ClassCase sup : supertypes) { - sup.init(namingContext); - } - - // Build name - StringBuilder sb = new StringBuilder(); - if (!supertypes.isEmpty()) { - sb.append(isInterface() ? "I" : "C"); - for (ClassCase cc : supertypes) { - sb.append(cc.getName()); - } - sb.append(kind.isInterface ? "i" : "c"); - } - sb.append(kind.prefix); - String pname = sb.toString(); - Integer icnt = namingContext.get(pname); - int cnt = icnt == null ? 0 : icnt; - ++cnt; - namingContext.put(pname, cnt); - if (cnt > 1) { - sb.append(cnt); - } - this.name = sb.toString(); - } - - public boolean isa(Kind... kinds) { - for (Kind k : kinds) { - if (kind == k) { - return true; - } - } - return false; - } - - private void exec(RuleGroup rg ) { - if (!executed.contains(rg)) { - rg.exec(this); - executed.add(rg); - } - } - - public void collectClasses(Set seen) { - seen.add(this); - for (ClassCase cc : supertypes) { - cc.collectClasses(seen); - } - } - - public String getID() { - if (name == null) { - throw new Error("Access to uninitialized ClassCase"); - } else { - return name; - } - } - - public final String getName() { - if (name == null) { - return "ClassCase uninited@" + hashCode(); - } else { - return name; - } - } - - @Override - public boolean equals(Object obj) { - return obj instanceof ClassCase && getID().equals(((ClassCase)obj).getID()); - } - - @Override - public int hashCode() { - return getID().hashCode(); - } - - @Override - public String toString() { - return getName(); - } -} diff --git a/jdk/test/jdk/lambda/shapegen/Hierarchy.java b/jdk/test/jdk/lambda/shapegen/Hierarchy.java deleted file mode 100644 index 64443d6440b..00000000000 --- a/jdk/test/jdk/lambda/shapegen/Hierarchy.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 shapegen; - -import java.util.ArrayList; -import java.util.List; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import static shapegen.ClassCase.Kind.*; - -/** - * - * @author Robert Field - */ -public class Hierarchy { - - public final ClassCase root; - public final Set all; - - public Hierarchy(ClassCase root) { - this.root = root; - root.init(new HashMap()); - Set allClasses = new HashSet<>(); - root.collectClasses(allClasses); - this.all = allClasses; - } - - public boolean anyDefaults() { - for (ClassCase cc : all) { - if (cc.kind == IDEFAULT) { - return true; - } - } - return false; - } - - public boolean get_OK() { - return root.get_OK(); - } - - public String testName() { - return root + "Test"; - } - - private static void genInterfaceList(StringBuilder buf, String prefix, List interfaces) { - if (!interfaces.isEmpty()) { - buf.append(" "); - buf.append(prefix); - buf.append(" "); - buf.append(interfaces.get(0)); - for (int i = 1; i < interfaces.size(); ++i) { - buf.append(", " + interfaces.get(i)); - } - } - } - - public static void genClassDef(StringBuilder buf, ClassCase cc, String implClass, List defaultRef) { - if (cc.isInterface()) { - buf.append("interface "); - buf.append(cc.getName() + " "); - genInterfaceList(buf, "extends", cc.getInterfaces()); - buf.append(" {\n"); - - switch (cc.kind) { - case IDEFAULT: - buf.append(" default String m() { return \"\"; }\n"); - defaultRef.add(cc); - break; - case IPRESENT: - buf.append(" String m();\n"); - break; - case IVAC: - break; - default: - throw new AssertionError("Unexpected kind"); - } - buf.append("}\n\n"); - } else { - buf.append((cc.isAbstract()? "abstract " : "")); - buf.append(" class " + cc.getName()); - if (cc.getSuperclass() != null) { - buf.append(" extends " + cc.getSuperclass()); - } - - genInterfaceList(buf, "implements", cc.getInterfaces()); - buf.append(" {\n"); - - switch (cc.kind) { - case CCONCRETE: - buf.append(" public String m() { return \"\"; }\n"); - break; - case CABSTRACT: - buf.append(" public abstract String m();\n"); - break; - case CNONE: - break; - default: - throw new AssertionError("Unexpected kind"); - } - buf.append("}\n\n"); - } - } - - @Override - public boolean equals(Object obj) { - return obj instanceof Hierarchy && root.getID().equals(((Hierarchy)obj).root.getID()); - } - - @Override - public int hashCode() { - return root.getID().hashCode(); - } - - @Override - public String toString() { - return root.getName(); - } - - private static String classNames[] = { - "C", "D", "E", "F", "G", "H", "S", "T", "U", "V" - }; - - private static String interfaceNames[] = { - "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R" - }; - - private static int CLASS_INDEX = 0; - private static int INTERFACE_INDEX = 1; - private static int NUM_INDICIES = 2; - - public List getDescription() { - Map nameMap = new HashMap<>(); - assignNames(root, new int[NUM_INDICIES], nameMap); - - ArrayList res = new ArrayList<>(); - if (root.getSupertypes().size() == 0) { - res.add(nameMap.get(root) + root.kind.getPrefix() + "()"); - } else { - genCaseDescription(root, res, new HashSet(), nameMap); - } - return res; - } - - private static void assignNames( - ClassCase cc, int indices[], Map names) { - String name = names.get(cc); - if (name == null) { - if (cc.isInterface()) { - names.put(cc, interfaceNames[indices[INTERFACE_INDEX]++]); - } else { - names.put(cc, classNames[indices[CLASS_INDEX]++]); - } - for (int i = 0; i < cc.getSupertypes().size(); ++i) { - assignNames(cc.getSupertypes().get(i), indices, names); - } - } - } - - private static void genCaseDescription( - ClassCase cc, List res, Set alreadyDone, - Map nameMap) { - if (!alreadyDone.contains(cc)) { - if (cc.getSupertypes().size() > 0) { - StringBuilder sb = new StringBuilder(); - sb.append(nameMap.get(cc)); - sb.append(cc.kind.getPrefix()); - sb.append("("); - for (int i = 0; i < cc.getSupertypes().size(); ++i) { - ClassCase supertype = cc.getSupertypes().get(i); - if (i != 0) { - sb.append(","); - } - genCaseDescription(supertype, res, alreadyDone, nameMap); - sb.append(nameMap.get(supertype)); - sb.append(supertype.kind.getPrefix()); - } - sb.append(")"); - res.add(sb.toString()); - } - } - alreadyDone.add(cc); - } -} diff --git a/jdk/test/jdk/lambda/shapegen/HierarchyGenerator.java b/jdk/test/jdk/lambda/shapegen/HierarchyGenerator.java deleted file mode 100644 index 9511c41c498..00000000000 --- a/jdk/test/jdk/lambda/shapegen/HierarchyGenerator.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 shapegen; - -import shapegen.ClassCase.Kind; - -import java.util.Collection; -import java.util.Set; -import java.util.HashSet; -import java.util.Collections; -import java.util.ArrayList; -import java.util.List; - -import static shapegen.ClassCase.Kind.*; - -import static java.lang.Math.pow; - -/** - * - * @author Robert Field - */ -public final class HierarchyGenerator { - - private int okcnt = 0; - private int errcnt = 0; - private Set uniqueOK = new HashSet<>(); - private Set uniqueErr = new HashSet<>(); - - /** - * @param args the command line arguments - */ - public HierarchyGenerator() { - organize("exhaustive interface", iExhaustive(2)); - organize("exhaustive class", cExhaustive()); - organize("shapes interface", iShapes()); - organize("shapes class/interface", ciShapes()); - - System.out.printf("\nExpect OK: %d -- unique %d", okcnt, uniqueOK.size()); - System.out.printf("\nExpect Error: %d -- unique %d\n", errcnt, uniqueErr.size()); - } - - public Collection getOK() { - return uniqueOK; - } - - public Collection getErr() { - return uniqueErr; - } - - private void organize(String tname, List totest) { - System.out.printf("\nGenerating %s....\n", tname); - int nodefault = 0; - List ok = new ArrayList<>(); - List err = new ArrayList<>(); - for (Hierarchy cc : totest) { - if (cc.anyDefaults()) { - //System.out.printf(" %s\n", cc); - if (cc.get_OK()) { - ok.add(cc); - } else { - err.add(cc); - } - } else { - ++nodefault; - } - } - - errcnt += err.size(); - okcnt += ok.size(); - uniqueErr.addAll(err); - uniqueOK.addAll(ok); - - System.out.printf(" %5d No default\n %5d Error\n %5d OK\n %5d Total\n", - nodefault, err.size(), ok.size(), totest.size()); - } - - public List iExhaustive(int idepth) { - List current = new ArrayList<>(); - for (int i = 0; i < idepth; ++i) { - current = ilayer(current); - } - return wrapInClassAndHierarchy(current); - } - - private List ilayer(List srcLayer) { - List lay = new ArrayList<>(); - for (int i = (int) pow(2, srcLayer.size()) - 1; i >= 0; --i) { - List itfs = new ArrayList<>(); - for (int b = srcLayer.size() - 1; b >= 0; --b) { - if ((i & (1< cExhaustive() { - final Kind[] iKinds = new Kind[]{IDEFAULT, IVAC, IPRESENT, null}; - final Kind[] cKinds = new Kind[]{CNONE, CABSTRACT, CCONCRETE}; - List totest = new ArrayList<>(); - for (int i1 = 0; i1 < iKinds.length; ++i1) { - for (int i2 = 0; i2 < iKinds.length; ++i2) { - for (int i3 = 0; i3 < iKinds.length; ++i3) { - for (int c1 = 0; c1 < cKinds.length; ++c1) { - for (int c2 = 0; c2 < cKinds.length; ++c2) { - for (int c3 = 0; c3 < cKinds.length; ++c3) { - totest.add( new Hierarchy( - new ClassCase(cKinds[c1], - new ClassCase(cKinds[c2], - new ClassCase(cKinds[c3], - null, - iList(iKinds[i1]) - ), - iList(iKinds[i2]) - ), - iList(iKinds[i3]) - ))); - } - } - } - } - } - } - return totest; - } - - public static final List EMPTY_LIST = new ArrayList<>(); - - private List iList(Kind kind) { - if (kind == null) { - return EMPTY_LIST; - } else { - List itfs = new ArrayList<>(); - itfs.add(new ClassCase(kind, null, EMPTY_LIST)); - return itfs; - } - } - - public List ciShapes() { - return wrapInHierarchy(TTShape.allCases(true)); - } - - public List iShapes() { - return wrapInClassAndHierarchy(TTShape.allCases(false)); - } - - public List wrapInClassAndHierarchy(List ihs) { - List totest = new ArrayList<>(); - for (ClassCase cc : ihs) { - List interfaces = new ArrayList<>(); - interfaces.add(cc); - totest.add(new Hierarchy(new ClassCase(CNONE, null, interfaces))); - } - return totest; - } - - public List wrapInHierarchy(List ihs) { - List totest = new ArrayList<>(); - for (ClassCase cc : ihs) { - totest.add(new Hierarchy(cc)); - } - return totest; - } -} diff --git a/jdk/test/jdk/lambda/shapegen/RuleGroup.java b/jdk/test/jdk/lambda/shapegen/RuleGroup.java deleted file mode 100644 index ef194abf45c..00000000000 --- a/jdk/test/jdk/lambda/shapegen/RuleGroup.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 shapegen; - -import java.util.HashSet; -import java.util.Set; - -import static shapegen.ClassCase.Kind.*; - -/** - * - * @author Robert Field - */ -public class RuleGroup { - - final String name; - private final Rule[] rules; - - public RuleGroup(String name, Rule[] rules) { - this.name = name; - this.rules = rules; - } - - public boolean exec(ClassCase cc) { - boolean found = false; - for (Rule rule : rules) { - if (rule.guard(cc)) { - if (found) { - throw new RuntimeException("Bad rules -- multiple matches " + toString() + " for " + cc); - } else { - rule.eval(cc); - found = true; - } - } - } - return found; - } - - @Override - public String toString() { - return name; - } - - public static RuleGroup PROVENENCE = new RuleGroup("Provenence", new Rule[] { - new Rule("P-CDeclare") { - boolean guard(ClassCase cc) { - return cc.isa(CCONCRETE, CABSTRACT); - } - - void eval(ClassCase cc) { - cc.set_mprov(cc); - cc.set_HasClassMethod(true); - } - }, - - new Rule("P-IDeclare") { - boolean guard(ClassCase cc) { - return cc.isa(IDEFAULT, IPRESENT); - } - - void eval(ClassCase cc) { - cc.set_mprov(cc); - } - }, - - new Rule("P-IntfInh") { - boolean guard(ClassCase cc) { - return cc.isa(IVAC, CNONE) && !(cc.hasSuperclass() && cc.getSuperclass().get_HasClassMethod()); - } - - void eval(ClassCase cc) { - Set _S = new HashSet<>(); - for (ClassCase t : cc.getSupertypes()) { - _S.addAll(t.get_mprov()); - } - Set tops = new HashSet<>(); - for (ClassCase _W : _S) { - for (ClassCase _V : _S) { - if (_V.equals(_W) || !(_V.isSubtypeOf(_W))) { - tops.add(_W); - } - } - } - cc.set_mprov(tops); - } - }, - - new Rule("P-ClassInh") { - boolean guard(ClassCase cc) { - return cc.isa(CNONE) && (cc.hasSuperclass() && cc.getSuperclass().get_HasClassMethod()); - } - - void eval(ClassCase cc) { - cc.set_mprov(cc.getSuperclass()); - cc.set_HasClassMethod(true); - } - }, - - }); - - public static RuleGroup MARKER = new RuleGroup("Marker", new Rule[] { - new Rule("M-Default") { - boolean guard(ClassCase cc) { - return cc.isa(IDEFAULT); - } - - void eval(ClassCase cc) { - cc.set_HasDefault(true); - } - }, - - new Rule("M-Conc") { - boolean guard(ClassCase cc) { - return cc.isa(CCONCRETE); - } - - void eval(ClassCase cc) { - cc.set_IsConcrete(true); - } - }, - - }); - - public static RuleGroup RESOLUTION = new RuleGroup("Resolution", new Rule[] { - new Rule("R-Resolve") { - boolean guard(ClassCase cc) { - if (!(cc.isClass() && cc.get_mprov().size() == 1)) { - return false; - } - ClassCase _V = cc.get_mprov().iterator().next(); - return _V.get_IsConcrete() || _V.get_HasDefault(); - } - - void eval(ClassCase cc) { - ClassCase _V = cc.get_mprov().iterator().next(); - cc.set_mres(_V); - } - }, - - }); - - public static RuleGroup DEFENDER = new RuleGroup("Defender", new Rule[] { - new Rule("D-Defend") { - boolean guard(ClassCase cc) { - ClassCase mresSuper = cc.hasSuperclass() ? cc.getSuperclass().get_mres() : null; - boolean eq = cc.get_mres() == null ? mresSuper == null : cc.get_mres().equals(mresSuper); - return cc.isa(CNONE) && !eq; - } - - void eval(ClassCase cc) { - cc.set_mdefend(cc.get_mres()); - } - }, - - }); - - public static RuleGroup CHECKING = new RuleGroup("Checking", new Rule[] { - new Rule("C-Check") { - boolean guard(ClassCase cc) { - for (ClassCase t : cc.getSupertypes()) { - if (! t.get_OK()) { - return false; - } - } - int defenderCount = 0; - int provCount = 0; - for (ClassCase prov : cc.get_mprov()) { - if (prov.get_HasDefault()) { - defenderCount++; - } - provCount++; - } - return provCount <= 1 || defenderCount == 0; - } - - void eval(ClassCase cc) { - cc.set_OK(true); - } - }, - - }); - -} diff --git a/jdk/test/jdk/lambda/shapegen/TTNode.java b/jdk/test/jdk/lambda/shapegen/TTNode.java deleted file mode 100644 index 48310dfd655..00000000000 --- a/jdk/test/jdk/lambda/shapegen/TTNode.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 shapegen; - -import shapegen.ClassCase.Kind; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import static shapegen.ClassCase.Kind.*; - -/** - * Type Template Node - * - * @author Robert Field - */ -public class TTNode { - - final List supertypes; - final boolean canBeClass; - - private int currentKindIndex; - private Kind[] kinds; - - public TTNode(List subtypes, boolean canBeClass) { - this.supertypes = subtypes; - this.canBeClass = canBeClass; - } - - public void start(boolean includeClasses) { - kinds = - supertypes.isEmpty()? - (new Kind[]{IDEFAULT, IPRESENT}) - : ((includeClasses && canBeClass)? - new Kind[]{CNONE, IVAC, IDEFAULT, IPRESENT} - : new Kind[]{IVAC, IDEFAULT, IPRESENT}); - currentKindIndex = 0; - - for (TTNode sub : supertypes) { - sub.start(includeClasses); - } - } - - public boolean next() { - ++currentKindIndex; - if (currentKindIndex >= kinds.length) { - currentKindIndex = 0; - return false; - } else { - return true; - } - } - - public void collectAllSubtypes(Set subs) { - subs.add(this); - for (TTNode n : supertypes) { - n.collectAllSubtypes(subs); - } - } - - private Kind getKind() { - return kinds[currentKindIndex]; - } - - boolean isInterface() { - return getKind().isInterface; - } - - boolean isClass() { - return !isInterface(); - } - - boolean hasDefault() { - return getKind() == IDEFAULT; - } - - public boolean isValid() { - for (TTNode n : supertypes) { - if (!n.isValid() || (isInterface() && n.isClass())) { - return false; - } - } - return true; - } - - public ClassCase genCase() { - ClassCase subclass; - List ttintfs; - if (isClass() && !supertypes.isEmpty() && supertypes.get(0).isClass()) { - subclass = supertypes.get(0).genCase(); - ttintfs = supertypes.subList(1, supertypes.size()); - } else { - subclass = null; - ttintfs = supertypes; - } - List intfs = new ArrayList<>(); - for (TTNode node : ttintfs) { - intfs.add(node.genCase()); - } - return new ClassCase(getKind(), subclass, intfs); - } -} diff --git a/jdk/test/jdk/lambda/shapegen/TTParser.java b/jdk/test/jdk/lambda/shapegen/TTParser.java deleted file mode 100644 index ffabee54fe1..00000000000 --- a/jdk/test/jdk/lambda/shapegen/TTParser.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 shapegen; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.io.IOException; -import java.io.StringReader; - -import static java.lang.Character.isLetter; -import static java.lang.Character.isUpperCase; -import static java.lang.Character.isWhitespace; - -/** - * Parse a type template definition string - * - * input :: classDef - * classDef :: letter [ ( classDef* ) ] - * - * @author Robert Field - */ -public class TTParser extends StringReader { - - private Map letterMap = new HashMap<>(); - private char ch; - - private final String def; - - public TTParser(String s) { - super(s); - this.def = s; - } - - private void advance() throws IOException { - do { - ch = (char)read(); - } while (isWhitespace(ch)); - } - - public TTNode parse() { - try { - advance(); - return classDef(); - } catch (IOException t) { - throw new RuntimeException(t); - } - } - - private TTNode classDef() throws IOException { - if (!isLetter(ch)) { - if (ch == (char)-1) { - throw new IOException("Unexpected end of type template in " + def); - } else { - throw new IOException("Unexpected character in type template: " + (Character)ch + " in " + def); - } - } - char nodeCh = ch; - TTNode node = letterMap.get(nodeCh); - boolean canBeClass = isUpperCase(nodeCh); - advance(); - if (node == null) { - List subtypes = new ArrayList<>(); - if (ch == '(') { - advance(); - while (ch != ')') { - subtypes.add(classDef()); - } - advance(); - } - node = new TTNode(subtypes, canBeClass); - letterMap.put(nodeCh, node); - } - return node; - } -} diff --git a/jdk/test/jdk/lambda/shapegen/TTShape.java b/jdk/test/jdk/lambda/shapegen/TTShape.java deleted file mode 100644 index 07b84e214dd..00000000000 --- a/jdk/test/jdk/lambda/shapegen/TTShape.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * 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 shapegen; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * - * @author Robert Field - */ -public class TTShape { - - private final TTNode root; - private final TTNode[] nodes; - - TTShape(TTNode root) { - this.root = root; - Set subs = new HashSet<>(); - root.collectAllSubtypes(subs); - nodes = subs.toArray(new TTNode[subs.size()]); - } - - private List toCases(boolean includeClasses) { - List ccs = new ArrayList<>(); - root.start(includeClasses); - int i; - outer: - while (true) { - if (root.isValid()) { - ClassCase cc = root.genCase(); - //System.out.println(cc); - ccs.add(cc); - } - - i = 0; - do { - if (i >= nodes.length) { - break outer; - } - } while(!nodes[i++].next()); - } - return ccs; - } - - public static List allCases(boolean includeClasses) { - List ccs = new ArrayList<>(); - for (TTShape shape : SHAPES) { - ccs.addAll(shape.toCases(includeClasses)); - } - return ccs; - } - - public static TTShape parse(String s) { - return new TTShape(new TTParser(s).parse()); - } - - public static final TTShape[] SHAPES = new TTShape[] { - parse("a"), - parse("a(b)"), - parse("A(bb)"), - parse("A(B(d)c(d))"), - parse("A(b(c))"), - parse("A(B(cd)d)"), - parse("A(B(c)c)"), - parse("A(B(Ce)d(e))"), - parse("A(B(C)d(e))"), - parse("A(Bc(d))"), - parse("A(B(d)dc)"), - parse("A(B(dc)dc)"), - parse("A(B(c(d))d)"), - parse("A(B(C(d))d)"), - parse("A(B(C(e)d(e))e)"), - parse("A(B(c(d))c)"), - parse("A(B(dc(d))c)"), - parse("A(B(C(d))d)"), - }; - -} diff --git a/jdk/test/lib/testlibrary/jdk/testlibrary/ProcessTools.java b/jdk/test/lib/testlibrary/jdk/testlibrary/ProcessTools.java index 3e88f8887df..31c2e3327cc 100644 --- a/jdk/test/lib/testlibrary/jdk/testlibrary/ProcessTools.java +++ b/jdk/test/lib/testlibrary/jdk/testlibrary/ProcessTools.java @@ -24,6 +24,8 @@ package jdk.testlibrary; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.io.PrintStream; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; @@ -34,6 +36,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.concurrent.CountDownLatch; import java.util.Map; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -188,8 +191,8 @@ public final class ProcessTools { } else { latch.countDown(); } - Future stdoutTask = stdout.process(); - Future stderrTask = stderr.process(); + final Future stdoutTask = stdout.process(); + final Future stderrTask = stderr.process(); try { if (timeout > -1) { @@ -216,7 +219,7 @@ public final class ProcessTools { throw e; } - return p; + return new ProcessImpl(p, stdoutTask, stderrTask); } /** @@ -436,4 +439,84 @@ public final class ProcessTools { System.out.println(analyzer.getOutput()); return analyzer; } + + private static class ProcessImpl extends Process { + + private final Process p; + private final Future stdoutTask; + private final Future stderrTask; + + public ProcessImpl(Process p, Future stdoutTask, Future stderrTask) { + this.p = p; + this.stdoutTask = stdoutTask; + this.stderrTask = stderrTask; + } + + @Override + public OutputStream getOutputStream() { + return p.getOutputStream(); + } + + @Override + public InputStream getInputStream() { + return p.getInputStream(); + } + + @Override + public InputStream getErrorStream() { + return p.getErrorStream(); + } + + @Override + public int waitFor() throws InterruptedException { + int rslt = p.waitFor(); + waitForStreams(); + return rslt; + } + + @Override + public int exitValue() { + return p.exitValue(); + } + + @Override + public void destroy() { + p.destroy(); + } + + @Override + public long getPid() { + return p.getPid(); + } + + @Override + public boolean isAlive() { + return p.isAlive(); + } + + @Override + public Process destroyForcibly() { + return p.destroyForcibly(); + } + + @Override + public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException { + boolean rslt = p.waitFor(timeout, unit); + if (rslt) { + waitForStreams(); + } + return rslt; + } + + private void waitForStreams() throws InterruptedException { + try { + stdoutTask.get(); + } catch (ExecutionException e) { + } + try { + stderrTask.get(); + } catch (ExecutionException e) { + } + } + } } diff --git a/jdk/test/lib/testlibrary/jdk/testlibrary/RandomFactory.java b/jdk/test/lib/testlibrary/jdk/testlibrary/RandomFactory.java new file mode 100644 index 00000000000..eee84b15573 --- /dev/null +++ b/jdk/test/lib/testlibrary/jdk/testlibrary/RandomFactory.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.util.Random; +import java.util.SplittableRandom; + +/** + * Factory class which generates and prints to STDOUT a long-valued seed + * for use in initializing a PRNG. An instance of {@code Random} or + * {@code SplittableRandom} may likewise be obtained. + */ +public class RandomFactory { + /** + * Attempt to obtain the seed from the value of the "seed" property. + * @return The seed or {@code null} if the "seed" property was not set or + * could not be parsed. + */ + private static Long getSystemSeed() { + Long seed = null; + try { + // note that Long.valueOf(null) also throws a + // NumberFormatException so if the property is undefined this + // will still work correctly + seed = Long.valueOf(System.getProperty("seed")); + } catch (NumberFormatException e) { + // do nothing: seed is still null + } + + return seed; + } + + /** + * Obtain a seed from an independent PRNG. + * + * @return A random seed. + */ + private static long getRandomSeed() { + return new Random().nextLong(); + } + + /** + * Obtain and print to STDOUT a seed appropriate for initializing a PRNG. + * If the system property "seed" is set and has value which may be correctly + * parsed it is used, otherwise a seed is generated using an independent + * PRNG. + * + * @return The seed. + */ + public static long getSeed() { + Long seed = getSystemSeed(); + if (seed == null) { + seed = getRandomSeed(); + } + System.out.println("Seed from RandomFactory = "+seed+"L"); + return seed; + } + + /** + * Obtain and print to STDOUT a seed and use it to initialize a new + * {@code Random} instance which is returned. If the system + * property "seed" is set and has value which may be correctly parsed it + * is used, otherwise a seed is generated using an independent PRNG. + * + * @return The {@code Random} instance. + */ + public static Random getRandom() { + return new Random(getSeed()); + } + + /** + * Obtain and print to STDOUT a seed and use it to initialize a new + * {@code SplittableRandom} instance which is returned. If the system + * property "seed" is set and has value which may be correctly parsed it + * is used, otherwise a seed is generated using an independent PRNG. + * + * @return The {@code SplittableRandom} instance. + */ + public static SplittableRandom getSplittableRandom() { + return new SplittableRandom(getSeed()); + } +} diff --git a/jdk/test/sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh b/jdk/test/sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh index a74fdd63622..f4cd49e2c66 100644 --- a/jdk/test/sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh +++ b/jdk/test/sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh @@ -1,5 +1,5 @@ # -# Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. # 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,6 +29,7 @@ # @library /lib/testlibrary # @build jdk.testlibrary.* TestLogger Utils RmiBootstrapTest # @run shell/timeout=300 RmiSslBootstrapTest.sh +# @ignore 8077924 # Define the Java class test name TESTCLASS="RmiBootstrapTest" diff --git a/jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.java b/jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.java index a516acfd449..de5e9b6bbcd 100644 --- a/jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.java +++ b/jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.java @@ -60,6 +60,7 @@ import sun.management.AgentConfigurationError; * @run main/othervm/timeout=600 -XX:+UsePerfData JMXStartStopTest * @summary Makes sure that enabling/disabling the management agent through JCMD * achieves the desired results + * @key randomness */ public class JMXStartStopTest { @@ -90,7 +91,6 @@ public class JMXStartStopTest { } } } - System.err.println("*** port = " + port); ports[i] = port; } return ports; diff --git a/jdk/test/sun/misc/CopyMemory.java b/jdk/test/sun/misc/CopyMemory.java index 6ddcbc81d71..89266ed052d 100644 --- a/jdk/test/sun/misc/CopyMemory.java +++ b/jdk/test/sun/misc/CopyMemory.java @@ -24,6 +24,7 @@ /* @test * @bug 6565543 * @summary Minimal test for unsafe.copyMemory() and unsafe.setMemory() + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/misc/FloatingDecimal/TestFloatingDecimal.java b/jdk/test/sun/misc/FloatingDecimal/TestFloatingDecimal.java index b04545a65f3..23e97d7421c 100644 --- a/jdk/test/sun/misc/FloatingDecimal/TestFloatingDecimal.java +++ b/jdk/test/sun/misc/FloatingDecimal/TestFloatingDecimal.java @@ -62,6 +62,7 @@ public class sun.misc.FloatingDecimal { * @build DoubleConsts FloatConsts * @run main TestFloatingDecimal * @author Brian Burkhalter + * @key randomness */ public class TestFloatingDecimal { private static enum ResultType { diff --git a/jdk/test/sun/net/www/ParseUtil_4922813.java b/jdk/test/sun/net/www/ParseUtil_4922813.java index 5646039b651..3dd5503af08 100644 --- a/jdk/test/sun/net/www/ParseUtil_4922813.java +++ b/jdk/test/sun/net/www/ParseUtil_4922813.java @@ -24,6 +24,7 @@ /* @test @bug 4922813 @summary Check the new impl of encodePath will not cause regression + @key randomness */ import java.util.BitSet; diff --git a/jdk/test/sun/net/www/protocol/https/NewImpl/ComHTTPSConnection.java b/jdk/test/sun/net/www/protocol/https/NewImpl/ComHTTPSConnection.java index 486d234003c..24e2572f78f 100644 --- a/jdk/test/sun/net/www/protocol/https/NewImpl/ComHTTPSConnection.java +++ b/jdk/test/sun/net/www/protocol/https/NewImpl/ComHTTPSConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,8 +34,8 @@ import java.io.*; import java.net.*; +import java.security.cert.Certificate; import javax.net.ssl.*; -import javax.security.cert.*; import com.sun.net.ssl.HostnameVerifier; import com.sun.net.ssl.HttpsURLConnection; @@ -240,8 +240,8 @@ public class ComHTTPSConnection { System.out.println("Cipher Suite: " + ((HttpsURLConnection)urlc).getCipherSuite()); - X509Certificate[] certs = - ((HttpsURLConnection)urlc).getServerCertificateChain(); + Certificate[] certs = + ((HttpsURLConnection)urlc).getServerCertificates(); for (int i = 0; i < certs.length; i++) { System.out.println(certs[0]); } diff --git a/jdk/test/sun/nio/cs/FindDecoderBugs.java b/jdk/test/sun/nio/cs/FindDecoderBugs.java index 8c1fd910f5b..df8afd18960 100644 --- a/jdk/test/sun/nio/cs/FindDecoderBugs.java +++ b/jdk/test/sun/nio/cs/FindDecoderBugs.java @@ -27,6 +27,7 @@ * @summary Decode many byte sequences in many ways * @run main/timeout=1800 FindDecoderBugs * @author Martin Buchholz + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/nio/cs/FindEncoderBugs.java b/jdk/test/sun/nio/cs/FindEncoderBugs.java index ecd63065980..bfef4037ec4 100644 --- a/jdk/test/sun/nio/cs/FindEncoderBugs.java +++ b/jdk/test/sun/nio/cs/FindEncoderBugs.java @@ -27,6 +27,7 @@ * @summary Encode many char sequences in many ways * @run main/timeout=1200 FindEncoderBugs * @author Martin Buchholz + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/nio/cs/TestStringCoding.java b/jdk/test/sun/nio/cs/TestStringCoding.java index aaee1bcd2e3..7c18a3596c6 100644 --- a/jdk/test/sun/nio/cs/TestStringCoding.java +++ b/jdk/test/sun/nio/cs/TestStringCoding.java @@ -25,6 +25,7 @@ @bug 6636323 6636319 7040220 7096080 7183053 @summary Test if StringCoding and NIO result have the same de/encoding result * @run main/othervm/timeout=2000 TestStringCoding + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/nio/cs/TestStringCodingUTF8.java b/jdk/test/sun/nio/cs/TestStringCodingUTF8.java index d1f69950684..b936838ea13 100644 --- a/jdk/test/sun/nio/cs/TestStringCodingUTF8.java +++ b/jdk/test/sun/nio/cs/TestStringCodingUTF8.java @@ -25,6 +25,7 @@ @bug 7040220 @summary Test if StringCoding and NIO result have the same de/encoding result for UTF-8 * @run main/othervm/timeout=2000 TestStringCodingUTF8 + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/security/krb5/auto/KDC.java b/jdk/test/sun/security/krb5/auto/KDC.java index 117e67655da..d288f563e44 100644 --- a/jdk/test/sun/security/krb5/auto/KDC.java +++ b/jdk/test/sun/security/krb5/auto/KDC.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -149,6 +149,9 @@ public class KDC { private List conf = new ArrayList<>(); private Thread thread1, thread2, thread3; + private volatile boolean udpConsumerReady = false; + private volatile boolean tcpConsumerReady = false; + private volatile boolean dispatcherReady = false; DatagramSocket u1 = null; ServerSocket t1 = null; @@ -1228,6 +1231,7 @@ public class KDC { // The UDP consumer thread1 = new Thread() { public void run() { + udpConsumerReady = true; while (true) { try { byte[] inbuf = new byte[8192]; @@ -1248,6 +1252,7 @@ public class KDC { // The TCP consumer thread2 = new Thread() { public void run() { + tcpConsumerReady = true; while (true) { try { Socket socket = tcp.accept(); @@ -1270,6 +1275,7 @@ public class KDC { // The dispatcher thread3 = new Thread() { public void run() { + dispatcherReady = true; while (true) { try { q.take().send(); @@ -1280,6 +1286,19 @@ public class KDC { }; thread3.setDaemon(true); thread3.start(); + + // wait for the KDC is ready + try { + while (!isReady()) { + Thread.sleep(100); + } + } catch(InterruptedException e) { + throw new IOException(e); + } + } + + boolean isReady() { + return udpConsumerReady && tcpConsumerReady && dispatcherReady; } public void terminate() { diff --git a/jdk/test/sun/security/krb5/auto/SSL.java b/jdk/test/sun/security/krb5/auto/SSL.java index db7aae88bd4..f3d7f134a11 100644 --- a/jdk/test/sun/security/krb5/auto/SSL.java +++ b/jdk/test/sun/security/krb5/auto/SSL.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,11 +39,10 @@ * @run main/othervm SSL TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 */ import java.io.*; -import java.net.InetAddress; -import java.security.AccessControlException; import java.security.Permission; import javax.net.ssl.*; import java.security.Principal; +import java.security.Security; import java.util.Date; import java.util.List; import java.util.ArrayList; @@ -82,6 +81,9 @@ public class SSL extends SecurityManager { } public static void main(String[] args) throws Exception { + // reset the security property to make sure that the algorithms + // and keys used in this test are not disabled. + Security.setProperty("jdk.tls.disabledAlgorithms", ""); krb5Cipher = args[0]; diff --git a/jdk/test/sun/security/krb5/auto/UnboundSSL.java b/jdk/test/sun/security/krb5/auto/UnboundSSL.java new file mode 100644 index 00000000000..0862f072f04 --- /dev/null +++ b/jdk/test/sun/security/krb5/auto/UnboundSSL.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivilegedActionException; +import java.util.HashMap; +import java.util.Map; +import javax.security.auth.login.LoginException; + +/* + * @test + * @bug 8025123 + * @summary Checks if an unbound server can handle connections + * only for allowed service principals + * @run main/othervm/policy=unbound.ssl.policy UnboundSSL + * unbound.ssl.jaas.conf server_star + * @run main/othervm/policy=unbound.ssl.policy UnboundSSL + * unbound.ssl.jaas.conf server_multiple_principals + */ +public class UnboundSSL { + + public static void main(String[] args) throws IOException, + NoSuchAlgorithmException,LoginException, PrivilegedActionException, + InterruptedException { + UnboundSSL test = new UnboundSSL(); + test.start(args[0], args[1]); + } + + private void start(String jaacConfigFile, String serverJaasConfig) + throws IOException, NoSuchAlgorithmException,LoginException, + PrivilegedActionException, InterruptedException { + + // define principals + String service1host = "service1." + UnboundSSLUtils.HOST; + String service2host = "service2." + UnboundSSLUtils.HOST; + String service3host = "service3." + UnboundSSLUtils.HOST; + String service1Principal = "host/" + service1host + "@" + + UnboundSSLUtils.REALM; + String service2Principal = "host/" + service2host + "@" + + UnboundSSLUtils.REALM; + String service3Principal = "host/" + service3host + "@" + + UnboundSSLUtils.REALM; + + Map principals = new HashMap<>(); + principals.put(UnboundSSLUtils.USER_PRINCIPAL, + UnboundSSLUtils.USER_PASSWORD); + principals.put(UnboundSSLUtils.KRBTGT_PRINCIPAL, null); + principals.put(service1Principal, null); + principals.put(service2Principal, null); + principals.put(service3Principal, null); + + System.setProperty("java.security.krb5.conf", + UnboundSSLUtils.KRB5_CONF_FILENAME); + + // start a local KDC instance + UnboundSSLUtils.startKDC(UnboundSSLUtils.REALM, principals, + UnboundSSLUtils.KTAB_FILENAME, UnboundSSLUtils.KtabMode.APPEND); + + System.setProperty("java.security.auth.login.config", + UnboundSSLUtils.TEST_SRC + UnboundSSLUtils.FS + jaacConfigFile); + System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); + + try (final SSLEchoServer server = SSLEchoServer.init( + UnboundSSLUtils.TLS_KRB5_FILTER, UnboundSSLUtils.SNI_PATTERN)) { + + // start a server instance + UnboundSSLUtils.startServerWithJaas(server, serverJaasConfig); + + // wait for the server is ready + while (!server.isReady()) { + Thread.sleep(UnboundSSLUtils.DELAY); + } + + int port = server.getPort(); + + // run clients + + // the server should have a permission to handle a request + // with this service principal (there should be an appropriate + // javax.security.auth.kerberos.ServicePermission in policy file) + System.out.println("Connect: SNI hostname = " + service1host + + ", successful connection is expected"); + SSLClient.init(UnboundSSLUtils.HOST, port, + UnboundSSLUtils.TLS_KRB5_FILTER, service1host).connect(); + + // the server should NOT have a permission to handle a request + // with this service principal (there should be an appropriate + // javax.security.auth.kerberos.ServicePermission in policy file) + // handshake failures is expected + System.out.println("Connect: SNI hostname = " + service2host + + ", connection failure is expected"); + try { + SSLClient.init(UnboundSSLUtils.HOST, port, + UnboundSSLUtils.TLS_KRB5_FILTER, service2host) + .connect(); + throw new RuntimeException("Test failed: " + + "expected IOException not thrown"); + } catch (IOException e) { + System.out.println("Expected exception: " + e); + } + + // the server should have a permission to handle a request + // with this service principal (there should be an appropriate + // javax.security.auth.kerberos.ServicePermission in policy file) + System.out.println("Connect: SNI hostname = " + service3host + + ", successful connection is expected"); + SSLClient.init(UnboundSSLUtils.HOST, port, + UnboundSSLUtils.TLS_KRB5_FILTER, service3host).connect(); + } + + System.out.println("Test passed"); + } +} diff --git a/jdk/test/sun/security/krb5/auto/UnboundSSLMultipleKeys.java b/jdk/test/sun/security/krb5/auto/UnboundSSLMultipleKeys.java new file mode 100644 index 00000000000..255a40ca106 --- /dev/null +++ b/jdk/test/sun/security/krb5/auto/UnboundSSLMultipleKeys.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivilegedActionException; +import java.util.HashMap; +import java.util.Map; +import javax.security.auth.login.LoginException; + +/* + * @test + * @bug 8025123 + * @summary Checks if an unbound server pick up a correct key from keytab + * @run main/othervm UnboundSSLMultipleKeys + * unbound.ssl.jaas.conf server_star + * @run main/othervm UnboundSSLMultipleKeys + * unbound.ssl.jaas.conf server_multiple_principals + */ +public class UnboundSSLMultipleKeys { + + public static void main(String[] args) + throws IOException, NoSuchAlgorithmException, LoginException, + PrivilegedActionException, InterruptedException { + UnboundSSLMultipleKeys test = new UnboundSSLMultipleKeys(); + test.start(args[0], args[1]); + } + + private void start(String jaacConfigFile, String serverJaasConfig) + throws IOException, NoSuchAlgorithmException, LoginException, + PrivilegedActionException, InterruptedException { + + // define service principals + String service1host = "service1." + UnboundSSLUtils.HOST; + String service2host = "service2." + UnboundSSLUtils.HOST; + String service3host = "service3." + UnboundSSLUtils.HOST; + String service1Principal = "host/" + service1host + "@" + + UnboundSSLUtils.REALM; + String service2Principal = "host/" + service2host + "@" + + UnboundSSLUtils.REALM; + String service3Principal = "host/" + service3host + "@" + + UnboundSSLUtils.REALM; + + Map principals = new HashMap<>(); + principals.put(UnboundSSLUtils.USER_PRINCIPAL, + UnboundSSLUtils.USER_PASSWORD); + principals.put(UnboundSSLUtils.KRBTGT_PRINCIPAL, "pass"); + principals.put(service1Principal, "pass0"); + principals.put(service1Principal, "pass1"); + principals.put(service1Principal, "pass2"); + principals.put(service2Principal, "pass"); + principals.put(service3Principal, "pass"); + + System.setProperty("java.security.krb5.conf", + UnboundSSLUtils.KRB5_CONF_FILENAME); + + /* + * Start a local KDC instance + * + * Keytab file contains 3 keys (with different KVNO) for service1 + * principal, but password for only one key is the same with the record + * for service1 principal in KDC. + */ + UnboundSSLUtils.startKDC(UnboundSSLUtils.REALM, principals, + UnboundSSLUtils.KTAB_FILENAME, UnboundSSLUtils.KtabMode.APPEND); + + System.setProperty("java.security.auth.login.config", + UnboundSSLUtils.TEST_SRC + UnboundSSLUtils.FS + jaacConfigFile); + System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); + + // start an SSL server instance + try (SSLEchoServer server = SSLEchoServer.init( + UnboundSSLUtils.TLS_KRB5_FILTER, UnboundSSLUtils.SNI_PATTERN)) { + + UnboundSSLUtils.startServerWithJaas(server, serverJaasConfig); + + // wait for the server is ready + while (!server.isReady()) { + Thread.sleep(UnboundSSLUtils.DELAY); + } + + // run a client + System.out.println("Successful connection is expected"); + SSLClient.init(UnboundSSLUtils.HOST, server.getPort(), + UnboundSSLUtils.TLS_KRB5_FILTER, service1host).connect(); + } + + System.out.println("Test passed"); + } + +} diff --git a/jdk/test/sun/security/krb5/auto/UnboundSSLPrincipalProperty.java b/jdk/test/sun/security/krb5/auto/UnboundSSLPrincipalProperty.java new file mode 100644 index 00000000000..3ccb4bf604a --- /dev/null +++ b/jdk/test/sun/security/krb5/auto/UnboundSSLPrincipalProperty.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivilegedActionException; +import java.util.HashMap; +import java.util.Map; +import javax.security.auth.login.LoginException; + +/* + * @test + * @bug 8025123 + * @summary Checks if an unbound server uses a service principal + * from sun.security.krb5.principal system property if specified + * @run main/othervm UnboundSSLPrincipalProperty + * unbound.ssl.jaas.conf server_star + * @run main/othervm UnboundSSLPrincipalProperty + * unbound.ssl.jaas.conf server_multiple_principals + */ +public class UnboundSSLPrincipalProperty { + + public static void main(String[] args) throws IOException, + NoSuchAlgorithmException,LoginException, PrivilegedActionException, + InterruptedException { + UnboundSSLPrincipalProperty test = new UnboundSSLPrincipalProperty(); + test.start(args[0], args[1]); + } + + public void start(String jaacConfigFile, String serverJaasConfig) + throws IOException, NoSuchAlgorithmException,LoginException, + PrivilegedActionException, InterruptedException { + + // define principals + String service1host = "service1." + UnboundSSLUtils.HOST; + String service3host = "service3." + UnboundSSLUtils.HOST; + String service1Principal = "host/" + service1host + "@" + + UnboundSSLUtils.REALM; + String service3Principal = "host/" + service3host + + "@" + UnboundSSLUtils.REALM; + + Map principals = new HashMap<>(); + principals.put(UnboundSSLUtils.USER_PRINCIPAL, + UnboundSSLUtils.USER_PASSWORD); + principals.put(UnboundSSLUtils.KRBTGT_PRINCIPAL, null); + principals.put(service1Principal, null); + principals.put(service3Principal, null); + + System.setProperty("java.security.krb5.conf", + UnboundSSLUtils.KRB5_CONF_FILENAME); + + // start a local KDC instance + UnboundSSLUtils.startKDC(UnboundSSLUtils.REALM, principals, + UnboundSSLUtils.KTAB_FILENAME, UnboundSSLUtils.KtabMode.APPEND); + + System.setProperty("java.security.auth.login.config", + UnboundSSLUtils.TEST_SRC + UnboundSSLUtils.FS + jaacConfigFile); + System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); + + // start an SSL server instance + try (final SSLEchoServer server = SSLEchoServer.init( + UnboundSSLUtils.TLS_KRB5_FILTER, UnboundSSLUtils.SNI_PATTERN)) { + + // specify a service principal for the server + System.setProperty("sun.security.krb5.principal", + service3Principal); + + UnboundSSLUtils.startServerWithJaas(server, serverJaasConfig); + + // wait for the server is ready + while (!server.isReady()) { + Thread.sleep(UnboundSSLUtils.DELAY); + } + + int port = server.getPort(); + + // connetion failure is expected + // since service3 principal was specified to use by the server + System.out.println("Connect: SNI hostname = " + service1host + + ", connection failure is expected"); + try { + SSLClient.init(UnboundSSLUtils.HOST, port, + UnboundSSLUtils.TLS_KRB5_FILTER, service1host) + .connect(); + throw new RuntimeException("Test failed: " + + "expected IOException not thrown"); + } catch (IOException e) { + System.out.println("Expected exception: " + e); + } + + System.out.println("Connect: SNI hostname = " + service3host + + ", successful connection is expected"); + SSLClient.init(UnboundSSLUtils.HOST, port, + UnboundSSLUtils.TLS_KRB5_FILTER, service3host).connect(); + } + + System.out.println("Test passed"); + } +} diff --git a/jdk/test/sun/security/krb5/auto/UnboundSSLUtils.java b/jdk/test/sun/security/krb5/auto/UnboundSSLUtils.java new file mode 100644 index 00000000000..ab55e1fa184 --- /dev/null +++ b/jdk/test/sun/security/krb5/auto/UnboundSSLUtils.java @@ -0,0 +1,353 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import javax.net.ssl.SNIHostName; +import javax.net.ssl.SNIMatcher; +import javax.net.ssl.SNIServerName; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import javax.security.auth.Subject; +import javax.security.auth.login.LoginContext; +import javax.security.auth.login.LoginException; + +/* + * Helper class for unbound krb5 tests. + */ +class UnboundSSLUtils { + + static enum KtabMode { APPEND, EXISTING }; + + static final String KTAB_FILENAME = "krb5.keytab.data"; + static final String HOST = "localhost"; + static final String REALM = "TEST.REALM"; + static final String KRBTGT_PRINCIPAL = "krbtgt/" + REALM; + static final String TEST_SRC = System.getProperty("test.src", "."); + static final String TLS_KRB5_FILTER = "TLS_KRB5"; + static final String USER = "USER"; + static final String USER_PASSWORD = "password"; + static final String FS = System.getProperty("file.separator"); + static final String SNI_PATTERN = ".*"; + static final String USER_PRINCIPAL = USER + "@" + REALM; + static final String KRB5_CONF_FILENAME = "krb5.conf"; + static final int DELAY = 1000; + + static String[] filterStringArray(String[] src, String filter) { + return Arrays.stream(src).filter((item) -> item.startsWith(filter)) + .toArray(size -> new String[size]); + } + + /* + * The method does JAAS login, + * and runs an SSL server in the JAAS context. + */ + static void startServerWithJaas(final SSLEchoServer server, + String config) throws LoginException, PrivilegedActionException { + LoginContext context = new LoginContext(config); + context.login(); + System.out.println("Server: successful authentication"); + Subject.doAs(context.getSubject(), + (PrivilegedExceptionAction) () -> { + SSLEchoServer.startServer(server); + return null; + }); + } + + /* + * Start a KDC server: + * - create a KDC instance + * - create Kerberos principals + * - save Kerberos configuration + * - save keys to keytab file + * - no pre-auth required + */ + static void startKDC(String realm, Map principals, + String ktab, KtabMode mode) { + try { + KDC kdc = KDC.create(realm, HOST, 0, true); + kdc.setOption(KDC.Option.PREAUTH_REQUIRED, Boolean.FALSE); + if (principals != null) { + for (Map.Entry entry : principals.entrySet()) { + String name = entry.getKey(); + String password = entry.getValue(); + if (password == null || password.isEmpty()) { + System.out.println("KDC: add a principal '" + name + + "' with a random password"); + kdc.addPrincipalRandKey(name); + } else { + System.out.println("KDC: add a principal '" + name + + "' with '" + password + "' password"); + kdc.addPrincipal(name, password.toCharArray()); + } + } + } + + KDC.saveConfig(KRB5_CONF_FILENAME, kdc); + + if (ktab != null) { + File ktabFile = new File(ktab); + if (mode == KtabMode.APPEND) { + if (ktabFile.exists()) { + System.out.println("KDC: append keys to an exising " + + "keytab file " + ktab); + kdc.appendKtab(ktab); + } else { + System.out.println("KDC: create a new keytab file " + + ktab); + kdc.writeKtab(ktab); + } + } else if (mode == KtabMode.EXISTING) { + System.out.println("KDC: use an existing keytab file " + + ktab); + } else { + throw new RuntimeException("KDC: unsupported keytab mode: " + + mode); + } + } + + System.out.println("KDC: started on " + HOST + ":" + kdc.getPort() + + " with '" + realm + "' realm"); + } catch (Exception e) { + throw new RuntimeException("KDC: unexpected exception", e); + } + } + +} + +class SSLClient { + + private final static byte[][] arrays = { + new byte[] {-1, 0, 2}, + new byte[] {} + }; + + private final SSLSocket socket; + + private SSLClient(SSLSocket socket) { + this.socket = socket; + } + + void connect() throws IOException { + System.out.println("Client: connect to server"); + try (BufferedInputStream bis = new BufferedInputStream( + socket.getInputStream()); + BufferedOutputStream bos = new BufferedOutputStream( + socket.getOutputStream())) { + + for (byte[] bytes : arrays) { + System.out.println("Client: send byte array: " + + Arrays.toString(bytes)); + + bos.write(bytes); + bos.flush(); + + byte[] recieved = new byte[bytes.length]; + int read = bis.read(recieved, 0, bytes.length); + if (read < 0) { + throw new IOException("Client: couldn't read a response"); + } + + System.out.println("Client: recieved byte array: " + + Arrays.toString(recieved)); + + if (!Arrays.equals(bytes, recieved)) { + throw new IOException("Client: sent byte array " + + "is not equal with recieved byte array"); + } + } + socket.getSession().invalidate(); + } finally { + if (!socket.isClosed()) { + socket.close(); + } + } + } + + static SSLClient init(String host, int port, String cipherSuiteFilter, + String sniHostName) throws NoSuchAlgorithmException, IOException { + SSLContext sslContext = SSLContext.getDefault(); + SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory(); + SSLSocket socket = (SSLSocket) ssf.createSocket(host, port); + SSLParameters params = new SSLParameters(); + + if (cipherSuiteFilter != null) { + String[] cipherSuites = UnboundSSLUtils.filterStringArray( + ssf.getSupportedCipherSuites(), cipherSuiteFilter); + System.out.println("Client: enabled cipher suites: " + + Arrays.toString(cipherSuites)); + params.setCipherSuites(cipherSuites); + } + + if (sniHostName != null) { + System.out.println("Client: set SNI hostname: " + sniHostName); + SNIHostName serverName = new SNIHostName(sniHostName); + List serverNames = new ArrayList<>(); + serverNames.add(serverName); + params.setServerNames(serverNames); + } + + socket.setSSLParameters(params); + + return new SSLClient(socket); + } + +} + +class SSLEchoServer implements Runnable, AutoCloseable { + + private final SSLServerSocket ssocket; + private volatile boolean stopped = false; + private volatile boolean ready = false; + + /* + * Starts the server in a separate thread. + */ + static void startServer(SSLEchoServer server) { + Thread serverThread = new Thread(server, "SSL echo server thread"); + serverThread.setDaemon(true); + serverThread.start(); + } + + private SSLEchoServer(SSLServerSocket ssocket) { + this.ssocket = ssocket; + } + + /* + * Main server loop. + */ + @Override + public void run() { + System.out.println("Server: started"); + while (!stopped) { + ready = true; + try (SSLSocket socket = (SSLSocket) ssocket.accept()) { + System.out.println("Server: client connection accepted"); + try ( + BufferedInputStream bis = new BufferedInputStream( + socket.getInputStream()); + BufferedOutputStream bos = new BufferedOutputStream( + socket.getOutputStream()) + ) { + byte[] buffer = new byte[1024]; + int read; + while ((read = bis.read(buffer)) > 0) { + bos.write(buffer, 0, read); + System.out.println("Server: recieved " + read + + " bytes: " + + Arrays.toString(Arrays.copyOf(buffer, read))); + bos.flush(); + } + } + } catch (IOException e) { + if (stopped) { + // stopped == true means that stop() method was called, + // so just ignore the exception, and finish the loop + break; + } + System.out.println("Server: couldn't accept client connection: " + + e); + } + } + System.out.println("Server: finished"); + } + + boolean isReady() { + return ready; + } + + void stop() { + stopped = true; + ready = false; + + // close the server socket to interupt accept() method + try { + if (!ssocket.isClosed()) { + ssocket.close(); + } + } catch (IOException e) { + throw new RuntimeException("Unexpected exception: " + e); + } + } + + @Override + public void close() { + stop(); + } + + int getPort() { + return ssocket.getLocalPort(); + } + + /* + * Creates server instance. + * + * @param cipherSuiteFilter Filter for enabled cipher suites + * @param sniMatcherPattern Pattern for SNI server hame + */ + static SSLEchoServer init(String cipherSuiteFilter, + String sniPattern) throws NoSuchAlgorithmException, IOException { + SSLContext context = SSLContext.getDefault(); + SSLServerSocketFactory ssf = + (SSLServerSocketFactory) context.getServerSocketFactory(); + SSLServerSocket ssocket = + (SSLServerSocket) ssf.createServerSocket(0); + + // specify enabled cipher suites + if (cipherSuiteFilter != null) { + String[] ciphersuites = UnboundSSLUtils.filterStringArray( + ssf.getSupportedCipherSuites(), cipherSuiteFilter); + System.out.println("Server: enabled cipher suites: " + + Arrays.toString(ciphersuites)); + ssocket.setEnabledCipherSuites(ciphersuites); + } + + // specify SNI matcher pattern + if (sniPattern != null) { + System.out.println("Server: set SNI matcher: " + sniPattern); + SNIMatcher matcher = SNIHostName.createSNIMatcher(sniPattern); + List matchers = new ArrayList<>(); + matchers.add(matcher); + SSLParameters params = ssocket.getSSLParameters(); + params.setSNIMatchers(matchers); + ssocket.setSSLParameters(params); + } + + return new SSLEchoServer(ssocket); + } + +} + diff --git a/jdk/test/sun/security/krb5/auto/unbound.ssl.jaas.conf b/jdk/test/sun/security/krb5/auto/unbound.ssl.jaas.conf new file mode 100644 index 00000000000..bee0a670c4b --- /dev/null +++ b/jdk/test/sun/security/krb5/auto/unbound.ssl.jaas.conf @@ -0,0 +1,40 @@ +com.sun.net.ssl.client { + com.sun.security.auth.module.Krb5LoginModule required + principal="USER@TEST.REALM" + doNotPrompt=true + useKeyTab=true + keyTab="krb5.keytab.data"; +}; + +server_star { + com.sun.security.auth.module.Krb5LoginModule required + principal="*" + isInitiator=false + useKeyTab=true + keyTab="krb5.keytab.data" + storeKey=true; +}; + +server_multiple_principals { + com.sun.security.auth.module.Krb5LoginModule required + principal="host/service1.localhost@TEST.REALM" + isInitiator=false + useKeyTab=true + keyTab="krb5.keytab.data" + storeKey=true; + + com.sun.security.auth.module.Krb5LoginModule required + principal="host/service2.localhost@TEST.REALM" + isInitiator=false + useKeyTab=true + keyTab="krb5.keytab.data" + storeKey=true; + + com.sun.security.auth.module.Krb5LoginModule required + principal="host/service3.localhost@TEST.REALM" + isInitiator=false + useKeyTab=true + keyTab="krb5.keytab.data" + storeKey=true; +}; + diff --git a/jdk/test/sun/security/krb5/auto/unbound.ssl.policy b/jdk/test/sun/security/krb5/auto/unbound.ssl.policy new file mode 100644 index 00000000000..12bab4559f1 --- /dev/null +++ b/jdk/test/sun/security/krb5/auto/unbound.ssl.policy @@ -0,0 +1,26 @@ +grant { + permission java.util.PropertyPermission "*", "read,write"; + permission java.net.SocketPermission "*:*", "listen,resolve,accept,connect"; + permission java.io.FilePermission "*", "read,write,delete"; + permission java.lang.RuntimePermission "accessDeclaredMembers"; + permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; + permission java.lang.RuntimePermission "accessClassInPackage.*"; + permission javax.security.auth.AuthPermission "doAs"; + permission javax.security.auth.AuthPermission "getSubject"; + permission javax.security.auth.AuthPermission + "createLoginContext.server_star"; + permission javax.security.auth.AuthPermission + "createLoginContext.server_multiple_principals"; + permission javax.security.auth.AuthPermission "modifyPrincipals"; + permission javax.security.auth.PrivateCredentialPermission "javax.security.auth.kerberos.KeyTab java.security.Principal \"krb5.keytab.data\"", "read"; + + // clients have a permission to use all service principals + permission javax.security.auth.kerberos.ServicePermission "*", "initiate"; + + // server has a service permission + // to accept only service1 and service3 principals + permission javax.security.auth.kerberos.ServicePermission + "host/service1.localhost@TEST.REALM", "accept"; + permission javax.security.auth.kerberos.ServicePermission + "host/service3.localhost@TEST.REALM", "accept"; +}; diff --git a/jdk/test/sun/security/mscapi/PrngSlow.java b/jdk/test/sun/security/mscapi/PrngSlow.java index f9001eea80d..3420cc6b2a1 100644 --- a/jdk/test/sun/security/mscapi/PrngSlow.java +++ b/jdk/test/sun/security/mscapi/PrngSlow.java @@ -25,6 +25,7 @@ * @test * @bug 6449335 * @summary MSCAPI's PRNG is too slow + * @key randomness */ import java.security.SecureRandom; diff --git a/jdk/test/sun/security/mscapi/ShortRSAKey1024.sh b/jdk/test/sun/security/mscapi/ShortRSAKey1024.sh index 8c290ebbdec..f7094f210af 100644 --- a/jdk/test/sun/security/mscapi/ShortRSAKey1024.sh +++ b/jdk/test/sun/security/mscapi/ShortRSAKey1024.sh @@ -30,6 +30,7 @@ # @run shell ShortRSAKey1024.sh 1024 # @run shell ShortRSAKey1024.sh 768 # @run shell ShortRSAKey1024.sh 512 +# @key intermittent # set a few environment variables so that the shell-script can run stand-alone # in the source directory diff --git a/jdk/test/sun/security/mscapi/SignUsingNONEwithRSA.sh b/jdk/test/sun/security/mscapi/SignUsingNONEwithRSA.sh index 961d1e5e3f1..e8c93a75781 100644 --- a/jdk/test/sun/security/mscapi/SignUsingNONEwithRSA.sh +++ b/jdk/test/sun/security/mscapi/SignUsingNONEwithRSA.sh @@ -28,6 +28,7 @@ # @bug 6578658 # @run shell SignUsingNONEwithRSA.sh # @summary Sign using the NONEwithRSA signature algorithm from SunMSCAPI +# @key intermittent # set a few environment variables so that the shell-script can run stand-alone # in the source directory diff --git a/jdk/test/sun/security/mscapi/SignUsingSHA2withRSA.sh b/jdk/test/sun/security/mscapi/SignUsingSHA2withRSA.sh index 2d433f108f0..d70a4e1c973 100644 --- a/jdk/test/sun/security/mscapi/SignUsingSHA2withRSA.sh +++ b/jdk/test/sun/security/mscapi/SignUsingSHA2withRSA.sh @@ -28,6 +28,7 @@ # @bug 6753664 # @run shell SignUsingSHA2withRSA.sh # @summary Support SHA256 (and higher) in SunMSCAPI +# @key intermittent # set a few environment variables so that the shell-script can run stand-alone # in the source directory diff --git a/jdk/test/sun/security/pkcs11/Cipher/ReinitCipher.java b/jdk/test/sun/security/pkcs11/Cipher/ReinitCipher.java index 9c87ce2b503..2cd68b44a9b 100644 --- a/jdk/test/sun/security/pkcs11/Cipher/ReinitCipher.java +++ b/jdk/test/sun/security/pkcs11/Cipher/ReinitCipher.java @@ -27,6 +27,7 @@ * @summary * @author Andreas Sterbenz * @library .. + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestRSACipher.java b/jdk/test/sun/security/pkcs11/Cipher/TestRSACipher.java index 4f27ff5de0c..876048f46cf 100644 --- a/jdk/test/sun/security/pkcs11/Cipher/TestRSACipher.java +++ b/jdk/test/sun/security/pkcs11/Cipher/TestRSACipher.java @@ -27,6 +27,7 @@ * @summary basic test for RSA cipher * @author Andreas Sterbenz * @library .. + * @key randomness */ import java.io.*; diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestRawRSACipher.java b/jdk/test/sun/security/pkcs11/Cipher/TestRawRSACipher.java index d1dd0206031..17ffe9553c2 100644 --- a/jdk/test/sun/security/pkcs11/Cipher/TestRawRSACipher.java +++ b/jdk/test/sun/security/pkcs11/Cipher/TestRawRSACipher.java @@ -27,6 +27,7 @@ * @summary basic test for RSA/ECB/NoPadding cipher * @author Valerie Peng * @library .. + * @key randomness */ import javax.crypto.*; diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphers.java b/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphers.java index 14e41cdddd2..e6b7f7d8a34 100644 --- a/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphers.java +++ b/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphers.java @@ -22,11 +22,12 @@ */ /** - * @test %I% %E% + * @test * @bug 4898461 6604496 * @summary basic test for symmetric ciphers with padding * @author Valerie Peng * @library .. + * @key randomness */ import java.io.*; import java.nio.*; diff --git a/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java b/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java index a8b71a30a4d..07d48649be5 100644 --- a/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java +++ b/jdk/test/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java @@ -27,6 +27,7 @@ * @summary basic test for symmetric ciphers with no padding * @author Valerie Peng * @library .. + * @key randomness */ import java.io.*; diff --git a/jdk/test/sun/security/pkcs11/KeyGenerator/DESParity.java b/jdk/test/sun/security/pkcs11/KeyGenerator/DESParity.java index 33ef9eb1749..2d7f77bc9c5 100644 --- a/jdk/test/sun/security/pkcs11/KeyGenerator/DESParity.java +++ b/jdk/test/sun/security/pkcs11/KeyGenerator/DESParity.java @@ -27,6 +27,7 @@ * @summary Verify that the parity bits are set correctly * @author Andreas Sterbenz * @library .. + * @key randomness */ import java.io.*; diff --git a/jdk/test/sun/security/pkcs11/Mac/MacSameTest.java b/jdk/test/sun/security/pkcs11/Mac/MacSameTest.java index f5e2787e609..21eae39b0c6 100644 --- a/jdk/test/sun/security/pkcs11/Mac/MacSameTest.java +++ b/jdk/test/sun/security/pkcs11/Mac/MacSameTest.java @@ -37,6 +37,7 @@ import javax.crypto.spec.SecretKeySpec; * @author Yu-Ching Valerie Peng, Bill Situ, Alexander Fomin * @library .. * @run main MacSameTest + * @key randomness */ public class MacSameTest extends PKCS11Test { diff --git a/jdk/test/sun/security/pkcs11/Mac/ReinitMac.java b/jdk/test/sun/security/pkcs11/Mac/ReinitMac.java index 0466330572a..68bef343889 100644 --- a/jdk/test/sun/security/pkcs11/Mac/ReinitMac.java +++ b/jdk/test/sun/security/pkcs11/Mac/ReinitMac.java @@ -27,6 +27,7 @@ * @summary * @author Andreas Sterbenz * @library .. + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/security/pkcs11/MessageDigest/ByteBuffers.java b/jdk/test/sun/security/pkcs11/MessageDigest/ByteBuffers.java index 49b3c9c8337..1b502a95bcf 100644 --- a/jdk/test/sun/security/pkcs11/MessageDigest/ByteBuffers.java +++ b/jdk/test/sun/security/pkcs11/MessageDigest/ByteBuffers.java @@ -27,6 +27,7 @@ * @summary Test the MessageDigest.update(ByteBuffer) method * @author Andreas Sterbenz * @library .. + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/security/pkcs11/MessageDigest/ReinitDigest.java b/jdk/test/sun/security/pkcs11/MessageDigest/ReinitDigest.java index 417b4c28d77..2f8290a2a7a 100644 --- a/jdk/test/sun/security/pkcs11/MessageDigest/ReinitDigest.java +++ b/jdk/test/sun/security/pkcs11/MessageDigest/ReinitDigest.java @@ -27,6 +27,7 @@ * @summary * @author Andreas Sterbenz * @library .. + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/security/pkcs11/MessageDigest/TestCloning.java b/jdk/test/sun/security/pkcs11/MessageDigest/TestCloning.java index c998e8092e0..5ea2264109f 100644 --- a/jdk/test/sun/security/pkcs11/MessageDigest/TestCloning.java +++ b/jdk/test/sun/security/pkcs11/MessageDigest/TestCloning.java @@ -27,6 +27,7 @@ * @summary Ensure the cloning functionality works. * @author Valerie Peng * @library .. + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/security/pkcs11/Secmod/AddPrivateKey.java b/jdk/test/sun/security/pkcs11/Secmod/AddPrivateKey.java index c99c498946d..a42ca861396 100644 --- a/jdk/test/sun/security/pkcs11/Secmod/AddPrivateKey.java +++ b/jdk/test/sun/security/pkcs11/Secmod/AddPrivateKey.java @@ -28,6 +28,7 @@ * @author Andreas Sterbenz * @library .. * @run main/othervm AddPrivateKey + * @key randomness */ import java.io.*; diff --git a/jdk/test/sun/security/pkcs11/Secmod/Crypto.java b/jdk/test/sun/security/pkcs11/Secmod/Crypto.java index c44ab87835f..39465f794d1 100644 --- a/jdk/test/sun/security/pkcs11/Secmod/Crypto.java +++ b/jdk/test/sun/security/pkcs11/Secmod/Crypto.java @@ -28,6 +28,7 @@ * @author Andreas Sterbenz * @library .. * @run main/othervm Crypto + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/security/pkcs11/Secmod/GetPrivateKey.java b/jdk/test/sun/security/pkcs11/Secmod/GetPrivateKey.java index a41bef9c77e..2dd1ce69056 100644 --- a/jdk/test/sun/security/pkcs11/Secmod/GetPrivateKey.java +++ b/jdk/test/sun/security/pkcs11/Secmod/GetPrivateKey.java @@ -28,6 +28,7 @@ * @author Andreas Sterbenz * @library .. * @run main/othervm GetPrivateKey + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/security/pkcs11/SecureRandom/Basic.java b/jdk/test/sun/security/pkcs11/SecureRandom/Basic.java index 63ebcb4750b..f9bfb1759ef 100644 --- a/jdk/test/sun/security/pkcs11/SecureRandom/Basic.java +++ b/jdk/test/sun/security/pkcs11/SecureRandom/Basic.java @@ -27,6 +27,7 @@ * @summary basic test for PKCS#11 SecureRandom * @author Andreas Sterbenz * @library .. + * @key randomness */ import java.io.*; diff --git a/jdk/test/sun/security/pkcs11/Signature/ByteBuffers.java b/jdk/test/sun/security/pkcs11/Signature/ByteBuffers.java index 31ae86c9a5e..8a76866f73f 100644 --- a/jdk/test/sun/security/pkcs11/Signature/ByteBuffers.java +++ b/jdk/test/sun/security/pkcs11/Signature/ByteBuffers.java @@ -27,6 +27,7 @@ * @summary Test the Signature.update(ByteBuffer) method * @author Andreas Sterbenz * @library .. + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/security/pkcs11/Signature/ReinitSignature.java b/jdk/test/sun/security/pkcs11/Signature/ReinitSignature.java index 36f80f3436e..d5ace8b9602 100644 --- a/jdk/test/sun/security/pkcs11/Signature/ReinitSignature.java +++ b/jdk/test/sun/security/pkcs11/Signature/ReinitSignature.java @@ -27,6 +27,7 @@ * @summary test that reinitializing Signatures works correctly * @author Andreas Sterbenz * @library .. + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/security/pkcs11/Signature/TestDSA.java b/jdk/test/sun/security/pkcs11/Signature/TestDSA.java index c7845ae4831..9f8c099f4c2 100644 --- a/jdk/test/sun/security/pkcs11/Signature/TestDSA.java +++ b/jdk/test/sun/security/pkcs11/Signature/TestDSA.java @@ -27,6 +27,7 @@ * @summary basic test of SHA1withDSA and RawDSA signing/verifying * @author Andreas Sterbenz * @library .. + * @key randomness */ import java.io.*; diff --git a/jdk/test/sun/security/pkcs11/Signature/TestDSAKeyLength.java b/jdk/test/sun/security/pkcs11/Signature/TestDSAKeyLength.java index 89b2b7a1c18..0287e7d028f 100644 --- a/jdk/test/sun/security/pkcs11/Signature/TestDSAKeyLength.java +++ b/jdk/test/sun/security/pkcs11/Signature/TestDSAKeyLength.java @@ -26,6 +26,7 @@ * @summary verify that P11Signature impl will error out when initialized * with unsupported key sizes * @library .. + * @key randomness */ diff --git a/jdk/test/sun/security/pkcs11/ec/ReadPKCS12.java b/jdk/test/sun/security/pkcs11/ec/ReadPKCS12.java index 930e0625b43..112470509fe 100644 --- a/jdk/test/sun/security/pkcs11/ec/ReadPKCS12.java +++ b/jdk/test/sun/security/pkcs11/ec/ReadPKCS12.java @@ -28,6 +28,7 @@ * @author Andreas Sterbenz * @library .. * @library ../../../../java/security/testlibrary + * @key randomness */ import java.io.*; diff --git a/jdk/test/sun/security/pkcs11/ec/TestCurves.java b/jdk/test/sun/security/pkcs11/ec/TestCurves.java index de53e2147fc..fb9cd836ad6 100644 --- a/jdk/test/sun/security/pkcs11/ec/TestCurves.java +++ b/jdk/test/sun/security/pkcs11/ec/TestCurves.java @@ -29,6 +29,7 @@ * @library .. * @compile -XDignore.symbol.file TestCurves.java * @run main TestCurves + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/security/pkcs11/ec/TestECDSA.java b/jdk/test/sun/security/pkcs11/ec/TestECDSA.java index 98dd939eaec..b811b44c6ef 100644 --- a/jdk/test/sun/security/pkcs11/ec/TestECDSA.java +++ b/jdk/test/sun/security/pkcs11/ec/TestECDSA.java @@ -28,6 +28,7 @@ * @author Andreas Sterbenz * @library .. * @library ../../../../java/security/testlibrary + * @key randomness */ import java.util.*; diff --git a/jdk/test/sun/security/pkcs11/rsa/KeyWrap.java b/jdk/test/sun/security/pkcs11/rsa/KeyWrap.java index ed31aa203fc..7f08481d6f7 100644 --- a/jdk/test/sun/security/pkcs11/rsa/KeyWrap.java +++ b/jdk/test/sun/security/pkcs11/rsa/KeyWrap.java @@ -27,6 +27,7 @@ * @summary Verify key wrapping (of extractable keys) works for RSA/PKCS1 * @author Andreas Sterbenz * @library .. + * @key randomness */ import java.io.*; diff --git a/jdk/test/sun/security/pkcs11/rsa/TestKeyPairGenerator.java b/jdk/test/sun/security/pkcs11/rsa/TestKeyPairGenerator.java index 92eb0f91b93..dbabc0c3dfa 100644 --- a/jdk/test/sun/security/pkcs11/rsa/TestKeyPairGenerator.java +++ b/jdk/test/sun/security/pkcs11/rsa/TestKeyPairGenerator.java @@ -24,10 +24,13 @@ /** * @test * @bug 4856966 - * @summary Verify that the RSA KeyPairGenerator works + * @summary Verify that the RSA KeyPairGenerator works (use -Dseed=X to set PRNG seed) * @author Andreas Sterbenz * @library .. + * @library /lib/testlibrary + * @build jdk.testlibrary.* * @run main/othervm TestKeyPairGenerator + * @key intermittent randomness */ import java.io.*; @@ -105,7 +108,7 @@ public class TestKeyPairGenerator extends PKCS11Test { int[] keyLengths = {512, 512, 1024}; BigInteger[] pubExps = {null, BigInteger.valueOf(3), null}; KeyPair[] keyPairs = new KeyPair[3]; - new Random().nextBytes(data); + RandomFactory.getRandom().nextBytes(data); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", provider); for (int i = 0; i < keyLengths.length; i++) { int len = keyLengths[i]; diff --git a/jdk/test/sun/security/pkcs11/rsa/TestSignatures.java b/jdk/test/sun/security/pkcs11/rsa/TestSignatures.java index fd11d0cb67b..b27de0a9b77 100644 --- a/jdk/test/sun/security/pkcs11/rsa/TestSignatures.java +++ b/jdk/test/sun/security/pkcs11/rsa/TestSignatures.java @@ -27,6 +27,7 @@ * @summary Test signing/verifying using all the signature algorithms * @author Andreas Sterbenz * @library .. + * @key randomness */ import java.io.*; diff --git a/jdk/test/sun/security/pkcs11/sslecc/CipherTest.java b/jdk/test/sun/security/pkcs11/sslecc/CipherTest.java index ae5091e0b09..4ec23743b2a 100644 --- a/jdk/test/sun/security/pkcs11/sslecc/CipherTest.java +++ b/jdk/test/sun/security/pkcs11/sslecc/CipherTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -45,7 +45,7 @@ import javax.net.ssl.*; public class CipherTest { // use any available port for the server socket - static int serverPort = 0; + static volatile int serverPort = 0; final int THREADS; diff --git a/jdk/test/sun/security/pkcs11/sslecc/JSSEServer.java b/jdk/test/sun/security/pkcs11/sslecc/JSSEServer.java index 0d1002b5834..af8d4b5a088 100644 --- a/jdk/test/sun/security/pkcs11/sslecc/JSSEServer.java +++ b/jdk/test/sun/security/pkcs11/sslecc/JSSEServer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ class JSSEServer extends CipherTest.Server { serverContext.init(new KeyManager[] {cipherTest.keyManager}, new TrustManager[] {cipherTest.trustManager}, cipherTest.secureRandom); SSLServerSocketFactory factory = (SSLServerSocketFactory)serverContext.getServerSocketFactory(); - serverSocket = (SSLServerSocket)factory.createServerSocket(cipherTest.serverPort); + serverSocket = (SSLServerSocket)factory.createServerSocket(0); cipherTest.serverPort = serverSocket.getLocalPort(); serverSocket.setEnabledCipherSuites(factory.getSupportedCipherSuites()); serverSocket.setWantClientAuth(true); diff --git a/jdk/test/sun/security/provider/DSA/TestDSA.java b/jdk/test/sun/security/provider/DSA/TestDSA.java index 197841bb0e1..d730b69f6cb 100644 --- a/jdk/test/sun/security/provider/DSA/TestDSA.java +++ b/jdk/test/sun/security/provider/DSA/TestDSA.java @@ -26,6 +26,7 @@ * @bug 4815057 4839277 * @summary basic test of SHA1withDSA and RawDSA signing/verifying * @author Andreas Sterbenz + * @key randomness */ import java.io.*; diff --git a/jdk/test/sun/security/provider/DSA/TestDSA2.java b/jdk/test/sun/security/provider/DSA/TestDSA2.java index 600161d00f7..00691535ac1 100644 --- a/jdk/test/sun/security/provider/DSA/TestDSA2.java +++ b/jdk/test/sun/security/provider/DSA/TestDSA2.java @@ -26,6 +26,7 @@ * @run main/othervm/timeout=250 TestDSA2 * @summary verify that DSA signature works using SHA and SHA-224 and * SHA-256 digests. + * @key randomness */ diff --git a/jdk/test/sun/security/provider/SeedGenerator/Priority_Inversion.java b/jdk/test/sun/security/provider/SeedGenerator/Priority_Inversion.java index e41e2816142..857e55ceab9 100644 --- a/jdk/test/sun/security/provider/SeedGenerator/Priority_Inversion.java +++ b/jdk/test/sun/security/provider/SeedGenerator/Priority_Inversion.java @@ -29,6 +29,7 @@ * * if the test returns, then it passed. * if the test never returns (hangs forever), then it failed. + * @key randomness */ import java.security.SecureRandom; diff --git a/jdk/test/sun/security/provider/X509Factory/BadPem.java b/jdk/test/sun/security/provider/X509Factory/BadPem.java new file mode 100644 index 00000000000..9147ab8ce93 --- /dev/null +++ b/jdk/test/sun/security/provider/X509Factory/BadPem.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 8074935 + * @summary jdk8 keytool doesn't validate pem files for RFC 1421 correctness, as jdk7 did + */ + +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.PrintStream; +import java.security.KeyStore; +import java.security.cert.CertificateException; +import java.util.Arrays; +import java.util.Base64; + +import sun.security.provider.X509Factory; +import java.security.cert.CertificateFactory; +import java.io.ByteArrayInputStream; + +public class BadPem { + + public static void main(String[] args) throws Exception { + String ks = System.getProperty("test.src", ".") + + "/../../../../javax/net/ssl/etc/keystore"; + String pass = "passphrase"; + String alias = "dummy"; + + KeyStore keyStore = KeyStore.getInstance("JKS"); + keyStore.load(new FileInputStream(ks), pass.toCharArray()); + byte[] cert = keyStore.getCertificate(alias).getEncoded(); + + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + PrintStream pout = new PrintStream(bout); + byte[] CRLF = new byte[] {'\r', '\n'}; + pout.println(X509Factory.BEGIN_CERT); + for (int i=0; i i + 48) ? 48 : (cert.length - i); + pout.println("!" + Base64.getEncoder() + .encodeToString(Arrays.copyOfRange(cert, i, i + blockLen))); + } + pout.println(X509Factory.END_CERT); + + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + + try { + cf.generateCertificate(new ByteArrayInputStream(bout.toByteArray())); + throw new Exception("Should fail"); + } catch (CertificateException e) { + // Good + } + } +} + diff --git a/jdk/test/sun/security/provider/certpath/ReverseBuilder/BuildPath.java b/jdk/test/sun/security/provider/certpath/ReverseBuilder/BuildPath.java deleted file mode 100644 index 28ff643bd64..00000000000 --- a/jdk/test/sun/security/provider/certpath/ReverseBuilder/BuildPath.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * 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 6511784 - * @summary Make sure that building a path to a CRL issuer works in the - * reverse direction - * @library ../../../../../java/security/testlibrary - * @build CertUtils - * @run main BuildPath - */ -import java.security.cert.*; -import java.util.Collections; -import sun.security.provider.certpath.SunCertPathBuilderParameters; - -public class BuildPath { - - public static void main(String[] args) throws Exception { - - TrustAnchor anchor = - new TrustAnchor(CertUtils.getCertFromFile("mgrM2mgrM"), null); - X509Certificate target = CertUtils.getCertFromFile("mgrM2leadMA"); - X509CertSelector xcs = new X509CertSelector(); - xcs.setSubject("CN=leadMA,CN=mgrM,OU=prjM,OU=divE,OU=Comp,O=sun,C=us"); - xcs.setCertificate(target); - SunCertPathBuilderParameters params = - new SunCertPathBuilderParameters(Collections.singleton(anchor),xcs); - params.setBuildForward(false); - CertStore cs = CertUtils.createStore(new String[] - {"mgrM2prjM", "prjM2mgrM", "prjM2divE", "mgrM2leadMA" }); - params.addCertStore(cs); - CertStore cs2 = CertUtils.createCRLStore - (new String[] {"mgrMcrl", "prjMcrl"}); - params.addCertStore(cs2); - PKIXCertPathBuilderResult res = CertUtils.build(params); - } -} diff --git a/jdk/test/sun/security/provider/certpath/ReverseBuilder/ReverseBuild.java b/jdk/test/sun/security/provider/certpath/ReverseBuilder/ReverseBuild.java deleted file mode 100644 index abb18ebd439..00000000000 --- a/jdk/test/sun/security/provider/certpath/ReverseBuilder/ReverseBuild.java +++ /dev/null @@ -1,356 +0,0 @@ -/* - * Copyright (c) 2012, 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. - */ - -// -// Security properties, once set, cannot revert to unset. To avoid -// conflicts with tests running in the same VM isolate this test by -// running it in otherVM mode. -// - -/* - * @test - * @bug 7167988 - * @summary PKIX CertPathBuilder in reverse mode doesn't work if more than - * one trust anchor is specified - * @run main/othervm ReverseBuild - */ -import java.io.*; -import java.util.*; -import java.security.cert.*; -import java.security.Security; - -import sun.security.provider.certpath.SunCertPathBuilderParameters; - -public class ReverseBuild { - // Certificate information: - // Issuer: C=US, ST=Some-State, L=Some-City, O=Some-Org - // Validity - // Not Before: Dec 8 02:43:36 2008 GMT - // Not After : Aug 25 02:43:36 2028 GMT - // Subject: C=US, ST=Some-State, L=Some-City, O=Some-Org - // X509v3 Subject Key Identifier: - // FA:B9:51:BF:4C:E7:D9:86:98:33:F9:E7:CB:1E:F1:33:49:F7:A8:14 - // X509v3 Authority Key Identifier: - // keyid:FA:B9:51:BF:4C:E7:D9:86:98:33:F9:E7:CB:1E:F1:33:49:F7:A8:14 - // DirName:/C=US/ST=Some-State/L=Some-City/O=Some-Org - // serial:00 - static String NoiceTrusedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICrDCCAhWgAwIBAgIBADANBgkqhkiG9w0BAQQFADBJMQswCQYDVQQGEwJVUzET\n" + - "MBEGA1UECBMKU29tZS1TdGF0ZTESMBAGA1UEBxMJU29tZS1DaXR5MREwDwYDVQQK\n" + - "EwhTb21lLU9yZzAeFw0wODEyMDgwMjQzMzZaFw0yODA4MjUwMjQzMzZaMEkxCzAJ\n" + - "BgNVBAYTAlVTMRMwEQYDVQQIEwpTb21lLVN0YXRlMRIwEAYDVQQHEwlTb21lLUNp\n" + - "dHkxETAPBgNVBAoTCFNvbWUtT3JnMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n" + - "gQDLxDggB76Ip5OwoUNRLdeOha9U3a2ieyNbz5kTU5lFfe5tui2/461uPZ8a+QOX\n" + - "4BdVrhEmV94BKY4FPyH35zboLjfXSKxT1mAOx1Bt9sWF94umxZE1cjyU7vEX8HHj\n" + - "7BvOyk5AQrBt7moO1uWtPA/JuoJPePiJl4kqlRJM2Akq6QIDAQABo4GjMIGgMB0G\n" + - "A1UdDgQWBBT6uVG/TOfZhpgz+efLHvEzSfeoFDBxBgNVHSMEajBogBT6uVG/TOfZ\n" + - "hpgz+efLHvEzSfeoFKFNpEswSTELMAkGA1UEBhMCVVMxEzARBgNVBAgTClNvbWUt\n" + - "U3RhdGUxEjAQBgNVBAcTCVNvbWUtQ2l0eTERMA8GA1UEChMIU29tZS1PcmeCAQAw\n" + - "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQBcIm534U123Hz+rtyYO5uA\n" + - "ofd81G6FnTfEAV8Kw9fGyyEbQZclBv34A9JsFKeMvU4OFIaixD7nLZ/NZ+IWbhmZ\n" + - "LovmJXyCkOufea73pNiZ+f/4/ScZaIlM/PRycQSqbFNd4j9Wott+08qxHPLpsf3P\n" + - "6Mvf0r1PNTY2hwTJLJmKtg==\n" + - "-----END CERTIFICATE-----"; - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce - // Validity - // Not Before: Aug 19 01:52:19 2011 GMT - // Not After : Jul 29 01:52:19 2032 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce - - // X509v3 Subject Key Identifier: - // B9:7C:D5:D9:DF:A7:4C:03:AE:FD:0E:27:5B:31:95:6C:C7:F3:75:E1 - // X509v3 Authority Key Identifier: - // keyid:B9:7C:D5:D9:DF:A7:4C:03:AE:FD:0E:27:5B:31:95:6C:C7:F3:75:E1 - // DirName:/C=US/O=Java/OU=SunJSSE Test Serivce - // serial:00 - static String NoiceTrusedCertStr_2nd = - "-----BEGIN CERTIFICATE-----\n" + - "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTEwODE5MDE1MjE5WhcNMzIwNzI5MDE1MjE5WjA7MQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" + - "KoZIhvcNAQEBBQADgY0AMIGJAoGBAM8orG08DtF98TMSscjGsidd1ZoN4jiDpi8U\n" + - "ICz+9dMm1qM1d7O2T+KH3/mxyox7Rc2ZVSCaUD0a3CkhPMnlAx8V4u0H+E9sqso6\n" + - "iDW3JpOyzMExvZiRgRG/3nvp55RMIUV4vEHOZ1QbhuqG4ebN0Vz2DkRft7+flthf\n" + - "vDld6f5JAgMBAAGjgaUwgaIwHQYDVR0OBBYEFLl81dnfp0wDrv0OJ1sxlWzH83Xh\n" + - "MGMGA1UdIwRcMFqAFLl81dnfp0wDrv0OJ1sxlWzH83XhoT+kPTA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEE\n" + - "BQADgYEALlgaH1gWtoBZ84EW8Hu6YtGLQ/L9zIFmHonUPZwn3Pr//icR9Sqhc3/l\n" + - "pVTxOINuFHLRz4BBtEylzRIOPzK3tg8XwuLb1zd0db90x3KBCiAL6E6cklGEPwLe\n" + - "XYMHDn9eDsaq861Tzn6ZwzMgw04zotPMoZN0mVd/3Qca8UJFucE=\n" + - "-----END CERTIFICATE-----"; - - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce - // Validity - // Not Before: May 5 02:40:50 2012 GMT - // Not After : Apr 15 02:40:50 2033 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce - // X509v3 Subject Key Identifier: - // DD:4E:8D:2A:11:C0:83:03:F0:AC:EB:A2:BF:F9:F2:7D:C8:69:1F:9B - // X509v3 Authority Key Identifier: - // keyid:DD:4E:8D:2A:11:C0:83:03:F0:AC:EB:A2:BF:F9:F2:7D:C8:69:1F:9B - // DirName:/C=US/O=Java/OU=SunJSSE Test Serivce - // serial:00 - static String trustedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQIFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTIwNTA1MDI0MDUwWhcNMzMwNDE1MDI0MDUwWjA7MQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" + - "KoZIhvcNAQEBBQADgY0AMIGJAoGBANtiq0AIJK+iVRwFrqcD7fYXTCbMYC5Qz/k6\n" + - "AXBy7/1rI8wDhEJLE3m/+NSqiJwZcmdq2dNh/1fJFrwvzuURbc9+paOBWeHbN+Sc\n" + - "x3huw91oPZme385VpoK3G13rSE114S/rF4DM9mz4EStFhSHXATjtdbskNOAYGLTV\n" + - "x8uEy9GbAgMBAAGjgaUwgaIwHQYDVR0OBBYEFN1OjSoRwIMD8Kzror/58n3IaR+b\n" + - "MGMGA1UdIwRcMFqAFN1OjSoRwIMD8Kzror/58n3IaR+boT+kPTA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEC\n" + - "BQADgYEAjjkJesQrkbr36N40egybaIxw7RcqT6iy5fkAGS1JYlBDk8uSCK1o6bCH\n" + - "ls5EpYcGeEoabSS73WRdkO1lgeyWDduO4ef8cCCSpmpT6/YdZG0QS1PtcREeVig+\n" + - "Zr25jNemS4ADHX0aaXP4kiV/G80cR7nX5t5XCUm4bYdbwM07NgI=\n" + - "-----END CERTIFICATE-----"; - static String trustedPrivateKey = // Private key in the format of PKCS#8 - "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANtiq0AIJK+iVRwF\n" + - "rqcD7fYXTCbMYC5Qz/k6AXBy7/1rI8wDhEJLE3m/+NSqiJwZcmdq2dNh/1fJFrwv\n" + - "zuURbc9+paOBWeHbN+Scx3huw91oPZme385VpoK3G13rSE114S/rF4DM9mz4EStF\n" + - "hSHXATjtdbskNOAYGLTVx8uEy9GbAgMBAAECgYEA2VjHkIiA0ABjkX+PqKeb+VLb\n" + - "fxS7tSca5C8zfdRhLxAWRui0/3ihst0eCJNrBDuxvAOACovsDWyLuaUjtI2v2ysz\n" + - "vz6SPyGy82PhQOFzyKQuQ814N6EpothpiZzF0yFchfKIGhUsdY89UrGs9nM7m6NT\n" + - "rztYvgIu4avg2VPR2AECQQD+pFAqipR2BplQRIuuRSZfHRxvoEyDjT1xnHJsC6WP\n" + - "I5hCLghL91MhQGWbP4EJMKYQOTRVukWlcp2Kycpf+P5hAkEA3I43gmVUAPEdyZdY\n" + - "fatW7OaLlbbYJb6qEtpCZ1Rwe/BIvm6H6E3qSi/lpz7Ia7WDulpbF6BawHH3pRFq\n" + - "CUY5ewJBAP3pUDqrRpBN0jB0uSeDslhjSciQ+dqvSpZv3rSYBHUvlBJhnkpJiy37\n" + - "7ZUZhIxqYxyIPgRBolLwb+FFh7OdL+ECQCtldDic9WVmC+VheRDpCKZ+SlK/8lGi\n" + - "7VXeShiIvcU1JysJFoa35fSI7hf1O3wt7+hX5PqGG7Un94EsJwACKEcCQQC1TWt6\n" + - "ArKH6tRxKjOxFtqfs8fgEVYUaOr3j1jF4KBUuX2mtQtddZe3VfJ2wPsuKMMxmhkB\n" + - "e7xWWZnJsErt2e+E"; - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce - // Validity - // Not Before: May 5 02:40:53 2012 GMT - // Not After : Jan 21 02:40:53 2032 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce, CN=casigner - // X509v3 Subject Key Identifier: - // 13:07:E0:11:07:DB:EB:33:23:87:31:D0:DB:7E:16:56:BE:11:90:0A - // X509v3 Authority Key Identifier: - // keyid:DD:4E:8D:2A:11:C0:83:03:F0:AC:EB:A2:BF:F9:F2:7D:C8:69:1F:9B - // DirName:/C=US/O=Java/OU=SunJSSE Test Serivce - // serial:00 - static String caSignerStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICqDCCAhGgAwIBAgIBAjANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTIwNTA1MDI0MDUzWhcNMzIwMTIxMDI0MDUzWjBOMQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxETAPBgNV\n" + - "BAMTCGNhc2lnbmVyMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+x8+o7oM0\n" + - "ct/LZmZLXBL4CQ8jrULD5P7NtEW0hg/zxBFZfBHf+44Oo2eMPYZj+7xaREOH5BmV\n" + - "KRYlzRtONAaC5Ng4Mrm5UKNPcMIIUjUOvm7vWM4oSTMSfoEcSX+vp99uUAkw3w7Z\n" + - "+frYDm1M4At/j0b+lLij71GFN2L8drpgPQIDAQABo4GoMIGlMB0GA1UdDgQWBBQT\n" + - "B+ARB9vrMyOHMdDbfhZWvhGQCjBjBgNVHSMEXDBagBTdTo0qEcCDA/Cs66K/+fJ9\n" + - "yGkfm6E/pD0wOzELMAkGA1UEBhMCVVMxDTALBgNVBAoTBEphdmExHTAbBgNVBAsT\n" + - "FFN1bkpTU0UgVGVzdCBTZXJpdmNlggEAMBIGA1UdEwEB/wQIMAYBAf8CAQEwCwYD\n" + - "VR0PBAQDAgEGMA0GCSqGSIb3DQEBBAUAA4GBAI+LXA/UCPkTANablUkt80JNPWsl\n" + - "pS4XLNgPxWaN0bkRDs5oI4ooWAz1rwpeJ/nfetOvWlpmrVjSeovBFja5Hl+dUHTf\n" + - "VfuyzkxXbhuNiJIpo1mVBpNsjwu9YRxuwX6UA2LTUQpgvtVJEE012x3zRvxBCbu2\n" + - "Y/v1R5fZ4c+hXDfC\n" + - "-----END CERTIFICATE-----"; - static String caSignerPrivateKey = // Private key in the format of PKCS#8 - "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAL7Hz6jugzRy38tm\n" + - "ZktcEvgJDyOtQsPk/s20RbSGD/PEEVl8Ed/7jg6jZ4w9hmP7vFpEQ4fkGZUpFiXN\n" + - "G040BoLk2DgyublQo09wwghSNQ6+bu9YzihJMxJ+gRxJf6+n325QCTDfDtn5+tgO\n" + - "bUzgC3+PRv6UuKPvUYU3Yvx2umA9AgMBAAECgYBYvu30cW8LONyt62Zua9hPFTe7\n" + - "qt9B7QYyfkdmoG5PQMepTrOp84SzfoOukvgvDm0huFuJnSvhXQl2cCDhkgXskvFj\n" + - "Hh7KBCFViVXokGdq5YoS0/KYMyQV0TZfJUvILBl51uc4/siQ2tClC/N4sa+1JhgW\n" + - "a6dFGfRjiUKSSlmMwQJBAPWpIz3Q/c+DYMvoQr5OD8EaYwYIevlTdXb97RnJJh2b\n" + - "UnhB9jrqesJiHYVzPmP0ukyPOXOwlp2T5Am4Kw0LFOkCQQDGz150NoHOp28Mvyc4\n" + - "CTqz/zYzUhy2eCJESl196uyP4N65Y01VYQ3JDww4DlsXiU17tVSbgA9TCcfTYOzy\n" + - "vyw1AkARUky+1hafZCcWGZljK8PmnMKwsTZikCTvL/Zg5BMA8Wu+OQBwpQnk3OAy\n" + - "Aa87gw0DyvGFG8Vy9POWT9sRP1/JAkBqP0hrMvYMSs6+MSn0eHo2151PsAJIQcuO\n" + - "U2/Da1khSzu8N6WMi2GiobgV/RYRbf9KrY2ZzMZjykZQYOxAjopBAkEAghCu38cN\n" + - "aOsW6ueo24uzsWI1FTdE+qWNVEi3RSP120xXBCyhaBjIq4WVSlJK9K2aBaJpit3j\n" + - "iQ5tl6zrLlxQhg=="; - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce, CN=casigner - // Validity - // Not Before: May 5 02:40:57 2012 GMT - // Not After : Jan 21 02:40:57 2032 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce, CN=certissuer - // X509v3 Subject Key Identifier: - // 39:0E:C6:33:B1:50:BC:73:07:31:E5:D8:04:F7:BB:97:55:CF:9B:C8 - // X509v3 Authority Key Identifier: - // keyid:13:07:E0:11:07:DB:EB:33:23:87:31:D0:DB:7E:16:56:BE:11:90:0A - // DirName:/C=US/O=Java/OU=SunJSSE Test Serivce - // serial:02 - static String certIssuerStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICvjCCAiegAwIBAgIBAzANBgkqhkiG9w0BAQQFADBOMQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxETAP\n" + - "BgNVBAMTCGNhc2lnbmVyMB4XDTEyMDUwNTAyNDA1N1oXDTMyMDEyMTAyNDA1N1ow\n" + - "UDELMAkGA1UEBhMCVVMxDTALBgNVBAoTBEphdmExHTAbBgNVBAsTFFN1bkpTU0Ug\n" + - "VGVzdCBTZXJpdmNlMRMwEQYDVQQDEwpjZXJ0aXNzdWVyMIGfMA0GCSqGSIb3DQEB\n" + - "AQUAA4GNADCBiQKBgQCyz55zinU6kNL/LeiTNiBI0QWYmDG0YTotuC4D75liBNqs\n" + - "7Mmladsh2mTtQUAwmuGaGzaZV25a+cUax0DXZoyBwdbTI09u1bUYsZcaUUKbPoCC\n" + - "HH26e4jLFL4olW13Sv4ZAd57tIYevMw+Fp5f4fLPFGegCJTFlv2Qjpmic/cuvQID\n" + - "AQABo4GpMIGmMB0GA1UdDgQWBBQ5DsYzsVC8cwcx5dgE97uXVc+byDBjBgNVHSME\n" + - "XDBagBQTB+ARB9vrMyOHMdDbfhZWvhGQCqE/pD0wOzELMAkGA1UEBhMCVVMxDTAL\n" + - "BgNVBAoTBEphdmExHTAbBgNVBAsTFFN1bkpTU0UgVGVzdCBTZXJpdmNlggECMBMG\n" + - "A1UdEwEB/wQJMAcBAf8CAgQAMAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQQFAAOB\n" + - "gQCQTagenCdClT98C+oTJGJrw/dUBD9K3tE6ZJKPMc/2bUia8G5ei1C0eXj4mWG2\n" + - "lu9umR6C90/A6qB050QB2h50qtqxSrkpu+ym1yypauZpg7U3nUY9wZWJNI1vqrQZ\n" + - "pqUMRcXY3iQIVKx+Qj+4/Za1wwFQzpEoGmqRW31V1SdMEw==\n" + - "-----END CERTIFICATE-----"; - static String certIssuerPrivateKey = // Private key in the format of PKCS#8 - "MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBALLPnnOKdTqQ0v8t\n" + - "6JM2IEjRBZiYMbRhOi24LgPvmWIE2qzsyaVp2yHaZO1BQDCa4ZobNplXblr5xRrH\n" + - "QNdmjIHB1tMjT27VtRixlxpRQps+gIIcfbp7iMsUviiVbXdK/hkB3nu0hh68zD4W\n" + - "nl/h8s8UZ6AIlMWW/ZCOmaJz9y69AgMBAAECgYEAjtew2tgm4gxDojqIauF4VPM1\n" + - "pzsdqd1p3pAdomNLgrQiBLZ8N7oiph6TNb1EjA+OXc+ThFgF/oM9ZDD8qZZwcvjN\n" + - "qDZlpTkFs2TaGcyEZfUaMB45NHVs6Nn+pSkagSNwwy3xeyAct7sQEzGNTDlEwVv5\n" + - "7V9LQutQtBd6xT48KzkCQQDpNRfv2OFNG/6GtzJoO68oJhpnpl2MsYNi4ntRkre/\n" + - "6uXpiCYaDskcrPMRwOOs0m7mxG+Ev+uKnLnSoEMm1GCbAkEAxEmDtiD0Psb8Z9BL\n" + - "ZRb83Jqho3xe2MCAh3xUfz9b/Mhae9dZ44o4OCgQZuwvW1mczF0NtpgZl93BmYa2\n" + - "hTwHhwJBAKHrEj6ep/fA6x0gD2idoATRR94VfbiU+7NpqtO9ecVP0+gsdr/66hn1\n" + - "3yLBeZLh3MxvMTrLgkAQh1i9m0JXjOcCQQClLXAHHegrw+u3uNMZeKTFR+Lp3sk6\n" + - "AZSnbvr0Me9I45kxSeG81x3ENALJecvIRbrrRws5MvmmkNhQR8rkh8WVAkEAk6b+\n" + - "aVtmBgUaTS5+FFlHGHJY9HFrfT1a1C/dwyMuqlmbC3YsBmZaMOlKli5TXNybLff8\n" + - "5KMeGEpXMzgC7AscGA=="; - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce, CN=certissuer - // Validity - // Not Before: May 5 02:41:01 2012 GMT - // Not After : Jan 21 02:41:01 2032 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce, CN=localhost - // X509v3 Subject Key Identifier: - // AD:C0:2C:4C:E4:C2:2E:A1:BB:5D:92:BE:66:E0:4E:E0:0D:2F:11:EF - // X509v3 Authority Key Identifier: - // keyid:39:0E:C6:33:B1:50:BC:73:07:31:E5:D8:04:F7:BB:97:55:CF:9B:C8 - static String targetCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICjTCCAfagAwIBAgIBBDANBgkqhkiG9w0BAQQFADBQMQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxEzAR\n" + - "BgNVBAMTCmNlcnRpc3N1ZXIwHhcNMTIwNTA1MDI0MTAxWhcNMzIwMTIxMDI0MTAx\n" + - "WjBPMQswCQYDVQQGEwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNT\n" + - "RSBUZXN0IFNlcml2Y2UxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0B\n" + - "AQEFAAOBjQAwgYkCgYEAvwaUd7wmBSKqycEstYLWD26vkU08DM39EtaT8wL9HnQ0\n" + - "fgPblwBFI4zdLa2cuYXRZcFUb04N8nrkcpR0D6kkE+AlFAoRWrrZF80B7JTbtEK4\n" + - "1PIeurihXvUT+4MpzGLOojIihMfvM4ufelblD56SInso4WFHm7t4qCln88J1gjkC\n" + - "AwEAAaN4MHYwCwYDVR0PBAQDAgPoMB0GA1UdDgQWBBStwCxM5MIuobtdkr5m4E7g\n" + - "DS8R7zAfBgNVHSMEGDAWgBQ5DsYzsVC8cwcx5dgE97uXVc+byDAnBgNVHSUEIDAe\n" + - "BggrBgEFBQcDAQYIKwYBBQUHAwIGCCsGAQUFBwMDMA0GCSqGSIb3DQEBBAUAA4GB\n" + - "AGfwcfdvEG/nSCiAn2MGbYHp34mgF3OA1SJLWUW0LvWJhwm2cn4AXlSoyvbwrkaB\n" + - "IDDCwhJvvc0vUyL2kTx7sqVaFTq3mDs+ktlB/FfH0Pb+i8FE+g+7T42Iw/j0qxHL\n" + - "YmgbrjBQf5WYN1AvBE/rrPt9aOtS3UsqtVGW574b0shW\n" + - "-----END CERTIFICATE-----"; - static String targetPrivateKey = // Private key in the format of PKCS#8 - "MIICdAIBADANBgkqhkiG9w0BAQEFAASCAl4wggJaAgEAAoGBAL8GlHe8JgUiqsnB\n" + - "LLWC1g9ur5FNPAzN/RLWk/MC/R50NH4D25cARSOM3S2tnLmF0WXBVG9ODfJ65HKU\n" + - "dA+pJBPgJRQKEVq62RfNAeyU27RCuNTyHrq4oV71E/uDKcxizqIyIoTH7zOLn3pW\n" + - "5Q+ekiJ7KOFhR5u7eKgpZ/PCdYI5AgMBAAECf3CscOYvFD3zNMnMJ5LomVqA7w3F\n" + - "gKYM2jlCWAH+wU41PMEXhW6Lujw92jgXL1o+lERwxFzirVdZJWZwKgUSvzP1G0h3\n" + - "fkucq1/UWnToK+8NSXNM/yS8hXbBgSEoJo5f7LKcIi1Ev6doBVofMxs+njzyWKbM\n" + - "Nb7rOLHadghoon0CQQDgQzbzzSN8Dc1YmmylhI5v+0sQRHH0DL7D24k4Weh4vInG\n" + - "EAbt4x8M7ZKEo8/dv0s4hbmNmAnJl93/RRxIyEqLAkEA2g87DiswSQam2pZ8GlrO\n" + - "+w4Qg9mH8uxx8ou2rl0XlHzH1XiTNbkjfY0EZoL7L31BHFk9n11Fb2P85g6ws+Hy\n" + - "ywJAM/xgyLNM/nzUlS128geAXUULaYH0SHaL4isJ7B4rXZGW/mrIsGxtzjlkNYsj\n" + - "rGujrD6TfNc5rZmexIXowJZtcQJBAIww+pCzZ4mrgx5JXWQ8OZHiiu+ZrPOa2+9J\n" + - "r5sOMpi+WGN/73S8oHqZbNjTINZ5OqEVJq8MchWZPQBTNXuQql0CQHEjUzzkCQa3\n" + - "j6JTa2KAdqyvLOx0XF9zcc1gA069uNQI2gPUHS8V215z57f/gMGnDNhVfLs/vMKz\n" + - "sFkVZ3zg7As="; - - - public static void main(String args[]) throws Exception { - // MD5 is used in this test case, don't disable MD5 algorithm. - Security.setProperty( - "jdk.certpath.disabledAlgorithms", "MD2, RSA keySize < 1024"); - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a set of trust anchors - LinkedHashSet trustAnchors = new LinkedHashSet<>(); - - ByteArrayInputStream is = - new ByteArrayInputStream(NoiceTrusedCertStr.getBytes()); - Certificate trustedCert = cf.generateCertificate(is); - is.close(); - TrustAnchor anchor = - new TrustAnchor((X509Certificate)trustedCert, null); - trustAnchors.add(anchor); - - is = new ByteArrayInputStream(trustedCertStr.getBytes()); - trustedCert = cf.generateCertificate(is); - is.close(); - anchor = new TrustAnchor((X509Certificate)trustedCert, null); - trustAnchors.add(anchor); - - is = new ByteArrayInputStream(NoiceTrusedCertStr_2nd.getBytes()); - trustedCert = cf.generateCertificate(is); - is.close(); - anchor = new TrustAnchor((X509Certificate)trustedCert, null); - trustAnchors.add(anchor); - - // create a list of certificates - List chainList = new ArrayList<>(); - - is = new ByteArrayInputStream(targetCertStr.getBytes()); - Certificate cert = cf.generateCertificate(is); - is.close(); - chainList.add(cert); - - is = new ByteArrayInputStream(certIssuerStr.getBytes()); - cert = cf.generateCertificate(is); - is.close(); - chainList.add(cert); - - is = new ByteArrayInputStream(caSignerStr.getBytes()); - cert = cf.generateCertificate(is); - is.close(); - chainList.add(cert); - - // create a certificate selector - X509CertSelector xcs = new X509CertSelector(); - X509Certificate eeCert = (X509Certificate)chainList.get(0); - xcs.setSubject(eeCert.getSubjectX500Principal()); - - // reverse build - SunCertPathBuilderParameters params = - new SunCertPathBuilderParameters(trustAnchors, xcs); - params.setBuildForward(false); - params.setRevocationEnabled(false); - - CollectionCertStoreParameters ccsp = - new CollectionCertStoreParameters(chainList); - params.addCertStore(CertStore.getInstance("Collection", ccsp)); - - CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX"); - CertPathBuilderResult res = cpb.build(params); - } -} diff --git a/jdk/test/sun/security/provider/certpath/ReverseBuilder/mgrM2leadMA b/jdk/test/sun/security/provider/certpath/ReverseBuilder/mgrM2leadMA deleted file mode 100644 index ed96b647b7b..00000000000 Binary files a/jdk/test/sun/security/provider/certpath/ReverseBuilder/mgrM2leadMA and /dev/null differ diff --git a/jdk/test/sun/security/provider/certpath/ReverseBuilder/mgrM2mgrM b/jdk/test/sun/security/provider/certpath/ReverseBuilder/mgrM2mgrM deleted file mode 100644 index 1953d3e0ba9..00000000000 Binary files a/jdk/test/sun/security/provider/certpath/ReverseBuilder/mgrM2mgrM and /dev/null differ diff --git a/jdk/test/sun/security/provider/certpath/ReverseBuilder/mgrM2prjM b/jdk/test/sun/security/provider/certpath/ReverseBuilder/mgrM2prjM deleted file mode 100644 index 7f306ed6f58..00000000000 Binary files a/jdk/test/sun/security/provider/certpath/ReverseBuilder/mgrM2prjM and /dev/null differ diff --git a/jdk/test/sun/security/provider/certpath/ReverseBuilder/mgrMcrl b/jdk/test/sun/security/provider/certpath/ReverseBuilder/mgrMcrl deleted file mode 100644 index 0977ea1b91b..00000000000 Binary files a/jdk/test/sun/security/provider/certpath/ReverseBuilder/mgrMcrl and /dev/null differ diff --git a/jdk/test/sun/security/provider/certpath/ReverseBuilder/prjM2divE b/jdk/test/sun/security/provider/certpath/ReverseBuilder/prjM2divE deleted file mode 100644 index f0e5eddf289..00000000000 Binary files a/jdk/test/sun/security/provider/certpath/ReverseBuilder/prjM2divE and /dev/null differ diff --git a/jdk/test/sun/security/provider/certpath/ReverseBuilder/prjM2mgrM b/jdk/test/sun/security/provider/certpath/ReverseBuilder/prjM2mgrM deleted file mode 100644 index 4004685dce2..00000000000 Binary files a/jdk/test/sun/security/provider/certpath/ReverseBuilder/prjM2mgrM and /dev/null differ diff --git a/jdk/test/sun/security/provider/certpath/ReverseBuilder/prjMcrl b/jdk/test/sun/security/provider/certpath/ReverseBuilder/prjMcrl deleted file mode 100644 index 88fb9d87ebd..00000000000 Binary files a/jdk/test/sun/security/provider/certpath/ReverseBuilder/prjMcrl and /dev/null differ diff --git a/jdk/test/sun/security/rsa/TestKeyPairGenerator.java b/jdk/test/sun/security/rsa/TestKeyPairGenerator.java index 5e661b08ef1..1d7d1b82e2d 100644 --- a/jdk/test/sun/security/rsa/TestKeyPairGenerator.java +++ b/jdk/test/sun/security/rsa/TestKeyPairGenerator.java @@ -26,6 +26,7 @@ * @bug 4853305 4865198 4888410 4963723 * @summary Verify that the RSA KeyPairGenerator works * @author Andreas Sterbenz + * @key randomness */ import java.io.*; diff --git a/jdk/test/sun/security/rsa/TestSignatures.java b/jdk/test/sun/security/rsa/TestSignatures.java index 1933f264295..f3b613f88ba 100644 --- a/jdk/test/sun/security/rsa/TestSignatures.java +++ b/jdk/test/sun/security/rsa/TestSignatures.java @@ -26,6 +26,7 @@ * @bug 4853305 4963723 * @summary Test signing/verifying using all the signature algorithms * @author Andreas Sterbenz + * @key randomness */ import java.io.*; diff --git a/jdk/test/sun/security/ssl/ClientHandshaker/CipherSuiteOrder.java b/jdk/test/sun/security/ssl/ClientHandshaker/CipherSuiteOrder.java index 5276fcba027..6f4a18edc07 100644 --- a/jdk/test/sun/security/ssl/ClientHandshaker/CipherSuiteOrder.java +++ b/jdk/test/sun/security/ssl/ClientHandshaker/CipherSuiteOrder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,7 +34,7 @@ */ import java.io.*; -import java.net.*; +import java.security.Security; import javax.net.ssl.*; public class CipherSuiteOrder { @@ -196,6 +196,10 @@ public class CipherSuiteOrder { volatile Exception clientException = null; public static void main(String[] args) throws Exception { + // reset the security property to make sure that the algorithms + // and keys used in this test are not disabled. + Security.setProperty("jdk.tls.disabledAlgorithms", ""); + String keyFilename = System.getProperty("test.src", "./") + "/" + pathToStores + "/" + keyStoreFile; diff --git a/jdk/test/sun/security/ssl/ClientHandshaker/LengthCheckTest.java b/jdk/test/sun/security/ssl/ClientHandshaker/LengthCheckTest.java index 2d4940ac378..aaaaddff950 100644 --- a/jdk/test/sun/security/ssl/ClientHandshaker/LengthCheckTest.java +++ b/jdk/test/sun/security/ssl/ClientHandshaker/LengthCheckTest.java @@ -27,6 +27,7 @@ * @summary Vectors and fixed length fields should be verified * for allowed sizes. * @run main/othervm LengthCheckTest + * @key randomness */ /** diff --git a/jdk/test/sun/security/ssl/DHKeyExchange/DHEKeySizing.java b/jdk/test/sun/security/ssl/DHKeyExchange/DHEKeySizing.java index 5c784b4e9ec..b94381ae629 100644 --- a/jdk/test/sun/security/ssl/DHKeyExchange/DHEKeySizing.java +++ b/jdk/test/sun/security/ssl/DHKeyExchange/DHEKeySizing.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -102,10 +102,10 @@ import java.io.*; import java.nio.*; import java.security.KeyStore; import java.security.KeyFactory; +import java.security.Security; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.*; import java.security.interfaces.*; import java.util.Base64; @@ -377,6 +377,10 @@ public class DHEKeySizing { } public static void main(String args[]) throws Exception { + // reset the security property to make sure that the algorithms + // and keys used in this test are not disabled. + Security.setProperty("jdk.tls.disabledAlgorithms", ""); + if (args.length != 4) { System.out.println( "Usage: java DHEKeySizing cipher-suite " + diff --git a/jdk/test/sun/security/ssl/GenSSLConfigs/main.java b/jdk/test/sun/security/ssl/GenSSLConfigs/main.java index 13460595a81..0bfd59d8823 100644 --- a/jdk/test/sun/security/ssl/GenSSLConfigs/main.java +++ b/jdk/test/sun/security/ssl/GenSSLConfigs/main.java @@ -3,6 +3,7 @@ * @build TestThread Traffic Handler ServerHandler ServerThread ClientThread * @run main/othervm/timeout=140 -Djsse.enableCBCProtection=false main * @summary Make sure that different configurations of SSL sockets work + * @key randomness */ /* diff --git a/jdk/test/sun/security/tools/keytool/KeyToolTest.java b/jdk/test/sun/security/tools/keytool/KeyToolTest.java index 74290da1c81..a036db96da0 100644 --- a/jdk/test/sun/security/tools/keytool/KeyToolTest.java +++ b/jdk/test/sun/security/tools/keytool/KeyToolTest.java @@ -56,6 +56,8 @@ * NSS PKCS11 config file are changed, DSA not supported now. */ +import java.nio.file.Files; +import java.nio.file.Paths; import java.security.KeyStore; import sun.security.x509.*; import java.io.*; @@ -1222,6 +1224,24 @@ public class KeyToolTest { remove("mykey.cert"); } + // 8074935: jdk8 keytool doesn't validate pem files for RFC 1421 correctness + static void checkPem(String file) throws Exception { + boolean maybeLast = false; + for (String s: Files.readAllLines(Paths.get(file))) { + if (s.isEmpty()) continue; + if (s.startsWith("---")) continue; + if (maybeLast) { + throw new Exception("Last line already seen"); + } + if (s.length() > 64) { + throw new Exception(s); + } + if (s.length() < 64) { + maybeLast = true; + } + } + } + void v3extTest(String keyAlg) throws Exception { KeyStore ks; remove("x.jks"); @@ -1588,12 +1608,14 @@ public class KeyToolTest { "-rfc -file test.req"); // printcertreq testOK("", "-printcertreq -file test.req"); + checkPem("test.req"); // issue: deny KU, change criticality of 1.2.3 and 1.2.4, // change content of BC, add 2.3.4 testOK("", simple+"-gencert -alias ca -infile test.req -ext " + "honored=all,-KU,1.2.3:critical,1.2.4:non-critical " + "-ext BC=2 -ext 2.3.4=01020304 " + "-debug -rfc -outfile test.cert"); + checkPem("test.cert"); testOK("", simple+"-importcert -file test.cert -alias a"); ks = loadStore("x.jks", "changeit", "JKS"); X509CertImpl a = (X509CertImpl)ks.getCertificate("a"); diff --git a/jdk/test/sun/security/validator/EndEntityExtensionCheck.java b/jdk/test/sun/security/validator/EndEntityExtensionCheck.java new file mode 100644 index 00000000000..122bae237f2 --- /dev/null +++ b/jdk/test/sun/security/validator/EndEntityExtensionCheck.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * 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 8076117 + * @summary EndEntityChecker should not process custom extensions + * after PKIX validation + */ + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.security.KeyStore; +import java.security.cert.CertPathValidatorException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.PKIXBuilderParameters; +import java.security.cert.PKIXCertPathChecker; +import java.security.cert.TrustAnchor; +import java.security.cert.X509Certificate; +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; +import sun.security.validator.KeyStores; +import sun.security.validator.Validator; + + +public class EndEntityExtensionCheck { + + /* + * Owner: CN=TestCA + * Issuer: CN=TestCA + */ + private static final String CA = + "-----BEGIN CERTIFICATE-----\n" + + "MIICgDCCAj2gAwIBAgIEC18hWjALBgcqhkjOOAQDBQAwETEPMA0GA1UEAxMGVGVz\n" + + "dENBMB4XDTE1MDQwNzIyMzUyMFoXDTI1MDQwNjIyMzUyMFowETEPMA0GA1UEAxMG\n" + + "VGVzdENBMIIBuDCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2\n" + + "EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdr\n" + + "mVClpJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXz\n" + + "rith1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+Gghdab\n" + + "Pd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6Ewo\n" + + "FhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhR\n" + + "kImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoDgYUAAoGBAJOWy2hVy4iNwsi/idWG\n" + + "oksr9IZxQIFR2YavoUmD+rIgfYUpiCihzftDLMMaNYqp9PPxuOyoIPGPbwmKpAs5\n" + + "nq6gLwH2lSsN+EwyV2SJ0J26PHiMuRNZWWfKR3cpEqbQVb0CmvqSpj8zYfamPzp7\n" + + "eXSWwahzgLCGJM3SgCfDFC0uoyEwHzAdBgNVHQ4EFgQU7tLD8FnWM+r6jBr+mCXs\n" + + "8G5yBpgwCwYHKoZIzjgEAwUAAzAAMC0CFQCHCtzC3S0ST0EZBucikVui4WXD8QIU\n" + + "L3Oxy6989/FhZlZWJlhqc1ungEQ=\n" + + "-----END CERTIFICATE-----"; + + /* + * Owner: CN=TestEE + * Issuer: CN=TestCA + * Contains a custom critical extension with OID 1.2.3.4: + * #1: ObjectId: 1.2.3.4 Criticality=true + * 0000: 00 00 + */ + private static final String EE = + "-----BEGIN CERTIFICATE-----\n" + + "MIICrTCCAmugAwIBAgIELjciKzALBgcqhkjOOAQDBQAwETEPMA0GA1UEAxMGVGVz\n" + + "dENBMB4XDTE1MDQwNzIzMDA1OFoXDTE1MDcwNjIzMDA1OFowETEPMA0GA1UEAxMG\n" + + "VGVzdEVFMIIBtzCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2\n" + + "EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdr\n" + + "mVClpJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXz\n" + + "rith1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+Gghdab\n" + + "Pd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6Ewo\n" + + "FhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhR\n" + + "kImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoDgYQAAoGAN97otrAJEuUg/O97vScI\n" + + "01xs1jqTz5o0PGpKiDDJNB3tCCUbLqXoBQBvSefQ8vYL3mmlEJLxlwfbajRmJQp0\n" + + "tUy5SUCZHk3MdoKxSvrqYnVpYwJHFXKWs6lAawxfuWbkm9SREuepOWnVzy2ecf5z\n" + + "hvy9mgEBfi4E9Cy8Byq2TpyjUDBOMAwGAyoDBAEB/wQCAAAwHwYDVR0jBBgwFoAU\n" + + "7tLD8FnWM+r6jBr+mCXs8G5yBpgwHQYDVR0OBBYEFNRVqt5F+EAuJ5x1IZLDkoMs\n" + + "mDj4MAsGByqGSM44BAMFAAMvADAsAhQyNGhxIp5IshN1zqLs4pUY214IMAIUMmTL\n" + + "3ZMpMAjITbuHHlFNUqZ7A9s=\n" + + "-----END CERTIFICATE-----"; + + public static void main(String[] args) throws Exception { + X509Certificate[] chain = createChain(); + + /* Test 1: Test SimpleValidator + * SimpleValidator doesn't check for unsupported critical + * extensions in the end entity certificate, and leaves that up + * to EndEntityChecker, which should catch such extensions. + */ + KeyStore ks = KeyStore.getInstance("JKS"); + ks.load(null, null); + ks.setCertificateEntry("testca", chain[chain.length - 1]); + + Validator v = Validator.getInstance(Validator.TYPE_SIMPLE, + Validator.VAR_TLS_CLIENT, + KeyStores.getTrustedCerts(ks)); + try { + v.validate(chain); + throw new Exception("Chain should not have validated " + + "successfully."); + } catch (CertificateException ex) { + // EE cert has an unsupported critical extension that is not + // checked by SimpleValidator's extension checks, so this + // failure is expected + } + + /* Test 2: Test PKIXValidator without custom checker + * PKIXValidator accepts PKIXParameters that can contain + * custom PKIXCertPathCheckers, which would be run against + * each cert in the chain, including EE certs. + * Check that if PKIXValidator is not provided a custom + * PKIXCertPathChecker for an unknown critical extension in + * the EE cert, chain validation will fail. + */ + TrustAnchor ta = new TrustAnchor(chain[chain.length - 1], null); + Set tas = new HashSet<>(); + tas.add(ta); + PKIXBuilderParameters params = new PKIXBuilderParameters(tas, null); + params.setDate(new Date(115, 5, 1)); // 2015-05-01 + params.setRevocationEnabled(false); + + v = Validator.getInstance(Validator.TYPE_PKIX, + Validator.VAR_TLS_CLIENT, + params); + try { + v.validate(chain); + throw new Exception("Chain should not have validated " + + "successfully."); + } catch (CertificateException ex) { + // EE cert has an unsupported critical extension and + // PKIXValidator was not provided any custom checker + // for it, so this failure ie expected. + } + + /* Test 3: Test PKIXValidator with custom checker + * Check that PKIXValidator will successfully validate a chain + * containing an EE cert with a critical custom extension, given + * a corresponding PKIXCertPathChecker for the extension. + */ + params = new PKIXBuilderParameters(tas, null); + params.addCertPathChecker(new CustomChecker()); + params.setDate(new Date(115, 5, 1)); // 2015-05-01 + params.setRevocationEnabled(false); + + v = Validator.getInstance(Validator.TYPE_PKIX, + Validator.VAR_TLS_CLIENT, + params); + v.validate(chain); // This should validate successfully + + System.out.println("Tests passed."); + } + + public static X509Certificate[] createChain() throws Exception { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + X509Certificate ee = (X509Certificate) + cf.generateCertificate((new ByteArrayInputStream(EE.getBytes()))); + X509Certificate ca = (X509Certificate) + cf.generateCertificate((new ByteArrayInputStream(CA.getBytes()))); + + X509Certificate[] chain = {ee, ca}; + return chain; + } + + /* + * A custom PKIXCertPathChecker. Looks for a critical extension + * in an end entity certificate with the OID 1.2.3.4. + */ + static class CustomChecker extends PKIXCertPathChecker { + + @Override + public void init(boolean forward) throws CertPathValidatorException { + // nothing to do + } + + @Override + public boolean isForwardCheckingSupported() { + return false; + } + + @Override + public Set getSupportedExtensions() { + Set exts = new HashSet<>(); + exts.add("1.2.3.4"); + return exts; + } + + @Override + public void check(Certificate cert, + Collection unresolvedCritExts) + throws CertPathValidatorException { + X509Certificate currCert = (X509Certificate)cert; + // check that this is an EE cert + if (currCert.getBasicConstraints() == -1) { + if (unresolvedCritExts != null && + !unresolvedCritExts.isEmpty()) { + unresolvedCritExts.remove("1.2.3.4"); + } + } + } + + } +} diff --git a/jdk/test/sun/text/resources/LocaleData b/jdk/test/sun/text/resources/LocaleData index 719cc3df066..9033fe6c125 100644 --- a/jdk/test/sun/text/resources/LocaleData +++ b/jdk/test/sun/text/resources/LocaleData @@ -8279,3 +8279,6 @@ FormatData/fi/DatePatterns/0=d. MMMM yyyy FormatData/fi/DatePatterns/1=d. MMMM yyyy FormatData/fi/DatePatterns/2=d.M.yyyy FormatData/fi/DatePatterns/3=d.M.yyyy + +# bug #8075173 +FormatData/de/standalone.MonthAbbreviations/2=M\u00e4r diff --git a/jdk/test/sun/text/resources/LocaleDataTest.java b/jdk/test/sun/text/resources/LocaleDataTest.java index 96d6d1d9a75..bd2b331fc78 100644 --- a/jdk/test/sun/text/resources/LocaleDataTest.java +++ b/jdk/test/sun/text/resources/LocaleDataTest.java @@ -36,7 +36,7 @@ * 6919624 6998391 7019267 7020960 7025837 7020583 7036905 7066203 7101495 * 7003124 7085757 7028073 7171028 7189611 8000983 7195759 8004489 8006509 * 7114053 7074882 7040556 8013836 8021121 6192407 6931564 8027695 8017142 - * 8037343 8055222 8042126 8074791 + * 8037343 8055222 8042126 8074791 8075173 * @summary Verify locale data * */ diff --git a/jdk/test/sun/tools/jmap/heapconfig/LingeredApp.java b/jdk/test/sun/tools/jmap/heapconfig/LingeredApp.java index 1ac1a137088..a6f1a64ee88 100644 --- a/jdk/test/sun/tools/jmap/heapconfig/LingeredApp.java +++ b/jdk/test/sun/tools/jmap/heapconfig/LingeredApp.java @@ -417,7 +417,9 @@ public class LingeredApp { setLastModified(theLockFileName, epoch()); Thread.sleep(spinDelay); } - + } catch (NoSuchFileException ex) { + // Lock deleted while we are setting last modified time. + // Ignore error and lets the app exits } catch (Exception ex) { System.err.println("LingeredApp ERROR: " + ex); // Leave exit_code = 1 to Java launcher diff --git a/jdk/test/sun/util/calendar/zi/tzdata/VERSION b/jdk/test/sun/util/calendar/zi/tzdata/VERSION index 034114ae6ca..ebd4db73b0e 100644 --- a/jdk/test/sun/util/calendar/zi/tzdata/VERSION +++ b/jdk/test/sun/util/calendar/zi/tzdata/VERSION @@ -21,4 +21,4 @@ # or visit www.oracle.com if you need additional information or have any # questions. # -tzdata2015a +tzdata2015b diff --git a/jdk/test/sun/util/calendar/zi/tzdata/asia b/jdk/test/sun/util/calendar/zi/tzdata/asia index bff837c48d8..fa4f2461cbb 100644 --- a/jdk/test/sun/util/calendar/zi/tzdata/asia +++ b/jdk/test/sun/util/calendar/zi/tzdata/asia @@ -1927,6 +1927,13 @@ Zone Indian/Maldives 4:54:00 - LMT 1880 # Male # was at the start of 2008-03-31 (the day of Steffen Thorsen's report); # this is almost surely wrong. +# From Ganbold Tsagaankhuu (2015-03-10): +# It seems like yesterday Mongolian Government meeting has concluded to use +# daylight saving time in Mongolia.... Starting at 2:00AM of last Saturday of +# March 2015, daylight saving time starts. And 00:00AM of last Saturday of +# September daylight saving time ends. Source: +# http://zasag.mn/news/view/8969 + # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Mongol 1983 1984 - Apr 1 0:00 1:00 S Rule Mongol 1983 only - Oct 1 0:00 0 - @@ -1947,6 +1954,8 @@ Rule Mongol 1984 1998 - Sep lastSun 0:00 0 - Rule Mongol 2001 only - Apr lastSat 2:00 1:00 S Rule Mongol 2001 2006 - Sep lastSat 2:00 0 - Rule Mongol 2002 2006 - Mar lastSat 2:00 1:00 S +Rule Mongol 2015 max - Mar lastSat 2:00 1:00 S +Rule Mongol 2015 max - Sep lastSat 0:00 0 - # Zone NAME GMTOFF RULES FORMAT [UNTIL] # Hovd, a.k.a. Chovd, Dund-Us, Dzhargalant, Khovd, Jirgalanta @@ -2365,13 +2374,19 @@ Zone Asia/Karachi 4:28:12 - LMT 1907 # official source...: # http://www.palestinecabinet.gov.ps/ar/Views/ViewDetails.aspx?pid=1252 -# From Paul Eggert (2013-09-24): -# For future dates, guess the last Thursday in March at 24:00 through -# the first Friday on or after September 21 at 00:00. This is consistent with -# the predictions in today's editions of the following URLs, -# which are for Gaza and Hebron respectively: -# http://www.timeanddate.com/worldclock/timezone.html?n=702 -# http://www.timeanddate.com/worldclock/timezone.html?n=2364 +# From Steffen Thorsen (2015-03-03): +# Sources such as http://www.alquds.com/news/article/view/id/548257 +# and http://www.raya.ps/ar/news/890705.html say Palestine areas will +# start DST on 2015-03-28 00:00 which is one day later than expected. +# +# From Paul Eggert (2015-03-03): +# http://www.timeanddate.com/time/change/west-bank/ramallah?year=2014 +# says that the fall 2014 transition was Oct 23 at 24:00. +# For future dates, guess the last Friday in March at 24:00 through +# the first Friday on or after October 21 at 00:00. This is consistent with +# the predictions in today's editions of the following URLs: +# http://www.timeanddate.com/time/change/gaza-strip/gaza +# http://www.timeanddate.com/time/change/west-bank/hebron # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule EgyptAsia 1957 only - May 10 0:00 1:00 S @@ -2397,9 +2412,11 @@ Rule Palestine 2011 only - Apr 1 0:01 1:00 S Rule Palestine 2011 only - Aug 1 0:00 0 - Rule Palestine 2011 only - Aug 30 0:00 1:00 S Rule Palestine 2011 only - Sep 30 0:00 0 - -Rule Palestine 2012 max - Mar lastThu 24:00 1:00 S +Rule Palestine 2012 2014 - Mar lastThu 24:00 1:00 S Rule Palestine 2012 only - Sep 21 1:00 0 - -Rule Palestine 2013 max - Sep Fri>=21 0:00 0 - +Rule Palestine 2013 only - Sep Fri>=21 0:00 0 - +Rule Palestine 2014 max - Oct Fri>=21 0:00 0 - +Rule Palestine 2015 max - Mar lastFri 24:00 1:00 S # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Asia/Gaza 2:17:52 - LMT 1900 Oct diff --git a/jdk/test/sun/util/calendar/zi/tzdata/australasia b/jdk/test/sun/util/calendar/zi/tzdata/australasia index f2a89e8ee37..ec9f392f88f 100644 --- a/jdk/test/sun/util/calendar/zi/tzdata/australasia +++ b/jdk/test/sun/util/calendar/zi/tzdata/australasia @@ -396,6 +396,7 @@ Zone Pacific/Guam -14:21:00 - LMT 1844 Dec 31 9:39:00 - LMT 1901 # Agana 10:00 - GST 2000 Dec 23 # Guam 10:00 - ChST # Chamorro Standard Time +Link Pacific/Guam Pacific/Saipan # N Mariana Is # Kiribati # Zone NAME GMTOFF RULES FORMAT [UNTIL] @@ -411,12 +412,7 @@ Zone Pacific/Kiritimati -10:29:20 - LMT 1901 14:00 - LINT # N Mariana Is -# Zone NAME GMTOFF RULES FORMAT [UNTIL] -Zone Pacific/Saipan -14:17:00 - LMT 1844 Dec 31 - 9:43:00 - LMT 1901 - 9:00 - MPT 1969 Oct # N Mariana Is Time - 10:00 - MPT 2000 Dec 23 - 10:00 - ChST # Chamorro Standard Time +# See Pacific/Guam. # Marshall Is # Zone NAME GMTOFF RULES FORMAT [UNTIL] @@ -586,6 +582,7 @@ Zone Pacific/Pago_Pago 12:37:12 - LMT 1879 Jul 5 -11:00 - NST 1967 Apr # N=Nome -11:00 - BST 1983 Nov 30 # B=Bering -11:00 - SST # S=Samoa +Link Pacific/Pago_Pago Pacific/Midway # in US minor outlying islands # Samoa (formerly and also known as Western Samoa) @@ -767,23 +764,7 @@ Zone Pacific/Funafuti 11:56:52 - LMT 1901 # uninhabited # Midway -# -# From Mark Brader (2005-01-23): -# [Fallacies and Fantasies of Air Transport History, by R.E.G. Davies, -# published 1994 by Paladwr Press, McLean, VA, USA; ISBN 0-9626483-5-3] -# reproduced a Pan American Airways timetable from 1936, for their weekly -# "Orient Express" flights between San Francisco and Manila, and connecting -# flights to Chicago and the US East Coast. As it uses some time zone -# designations that I've never seen before:.... -# Fri. 6:30A Lv. HONOLOLU (Pearl Harbor), H.I. H.L.T. Ar. 5:30P Sun. -# " 3:00P Ar. MIDWAY ISLAND . . . . . . . . . M.L.T. Lv. 6:00A " -# -Zone Pacific/Midway -11:49:28 - LMT 1901 - -11:00 - NST 1956 Jun 3 - -11:00 1:00 NDT 1956 Sep 2 - -11:00 - NST 1967 Apr # N=Nome - -11:00 - BST 1983 Nov 30 # B=Bering - -11:00 - SST # S=Samoa +# See Pacific/Pago_Pago. # Palmyra # uninhabited since World War II; was probably like Pacific/Kiritimati diff --git a/jdk/test/sun/util/calendar/zi/tzdata/europe b/jdk/test/sun/util/calendar/zi/tzdata/europe index 89790f06c17..008268ac763 100644 --- a/jdk/test/sun/util/calendar/zi/tzdata/europe +++ b/jdk/test/sun/util/calendar/zi/tzdata/europe @@ -2423,7 +2423,7 @@ Zone Europe/Volgograd 2:57:40 - LMT 1920 Jan 3 4:00 Russia VOL%sT 1989 Mar 26 2:00s # Volgograd T 3:00 Russia VOL%sT 1991 Mar 31 2:00s 4:00 - VOLT 1992 Mar 29 2:00s - 3:00 Russia MSK 2011 Mar 27 2:00s + 3:00 Russia MSK/MSD 2011 Mar 27 2:00s 4:00 - MSK 2014 Oct 26 2:00s 3:00 - MSK diff --git a/jdk/test/sun/util/calendar/zi/tzdata/northamerica b/jdk/test/sun/util/calendar/zi/tzdata/northamerica index 5943cfeec4b..442a50eef0f 100644 --- a/jdk/test/sun/util/calendar/zi/tzdata/northamerica +++ b/jdk/test/sun/util/calendar/zi/tzdata/northamerica @@ -2335,8 +2335,24 @@ Zone America/Dawson -9:17:40 - LMT 1900 Aug 20 # "...the new time zone will come into effect at two o'clock on the first Sunday # of February, when we will have to advance the clock one hour from its current # time..." -# # Also, the new zone will not use DST. +# +# From Carlos Raúl Perasso (2015-02-02): +# The decree that modifies the Mexican Hour System Law has finally +# been published at the Diario Oficial de la Federación +# http://www.dof.gob.mx/nota_detalle.php?codigo=5380123&fecha=31/01/2015 +# It establishes 5 zones for Mexico: +# 1- Zona Centro (Central Zone): Corresponds to longitude 90 W, +# includes most of Mexico, excluding what's mentioned below. +# 2- Zona Pacífico (Pacific Zone): Longitude 105 W, includes the +# states of Baja California Sur; Chihuahua; Nayarit (excluding Bahía +# de Banderas which lies in Central Zone); Sinaloa and Sonora. +# 3- Zona Noroeste (Northwest Zone): Longitude 120 W, includes the +# state of Baja California. +# 4- Zona Sureste (Southeast Zone): Longitude 75 W, includes the state +# of Quintana Roo. +# 5- The islands, reefs and keys shall take their timezone from the +# longitude they are located at. # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S Rule Mexico 1939 only - Feb 5 0:00 1:00 D @@ -2531,13 +2547,8 @@ Zone America/Santa_Isabel -7:39:28 - LMT 1922 Jan 1 0:20:32 ############################################################################### # Anguilla -# See America/Port_of_Spain. - # Antigua and Barbuda -# Zone NAME GMTOFF RULES FORMAT [UNTIL] -Zone America/Antigua -4:07:12 - LMT 1912 Mar 2 - -5:00 - EST 1951 - -4:00 - AST +# See America/Port_of_Spain. # Bahamas # @@ -2604,10 +2615,7 @@ Zone Atlantic/Bermuda -4:19:18 - LMT 1930 Jan 1 2:00 # Hamilton -4:00 US A%sT # Cayman Is -# Zone NAME GMTOFF RULES FORMAT [UNTIL] -Zone America/Cayman -5:25:32 - LMT 1890 # Georgetown - -5:07:11 - KMT 1912 Feb # Kingston Mean Time - -5:00 - EST +# See America/Panama. # Costa Rica @@ -3130,6 +3138,7 @@ Zone America/Managua -5:45:08 - LMT 1890 Zone America/Panama -5:18:08 - LMT 1890 -5:19:36 - CMT 1908 Apr 22 # Colón Mean Time -5:00 - EST +Link America/Panama America/Cayman # Puerto Rico # There are too many San Juans elsewhere, so we'll use 'Puerto_Rico'. diff --git a/jdk/test/sun/util/calendar/zi/tzdata/southamerica b/jdk/test/sun/util/calendar/zi/tzdata/southamerica index 02cf12113a0..238ae3dc569 100644 --- a/jdk/test/sun/util/calendar/zi/tzdata/southamerica +++ b/jdk/test/sun/util/calendar/zi/tzdata/southamerica @@ -1229,10 +1229,13 @@ Zone America/Rio_Branco -4:31:12 - LMT 1914 # DST Start: first Saturday of September 2014 (Sun 07 Sep 2014 04:00 UTC) # http://www.diariooficial.interior.gob.cl//media/2014/02/19/do-20140219.pdf -# From Juan Correa (2015-01-28): -# ... today the Ministry of Energy announced that Chile will drop DST, will keep -# "summer time" (UTC -3 / UTC -5) all year round.... -# http://www.minenergia.cl/ministerio/noticias/generales/ministerio-de-energia-anuncia.html +# From Eduardo Romero Urra (2015-03-03): +# Today has been published officially that Chile will use the DST time +# permanently until March 25 of 2017 +# http://www.diariooficial.interior.gob.cl/media/2015/03/03/1-large.jpg +# +# From Paul Eggert (2015-03-03): +# For now, assume that the extension will persist indefinitely. # NOTE: ChileAQ rules for Antarctic bases are stored separately in the # 'antarctica' file. @@ -1291,7 +1294,7 @@ Zone America/Santiago -4:42:46 - LMT 1890 -3:00 - CLT Zone Pacific/Easter -7:17:44 - LMT 1890 -7:17:28 - EMT 1932 Sep # Easter Mean Time - -7:00 Chile EAS%sT 1982 Mar 13 3:00u # Easter Time + -7:00 Chile EAS%sT 1982 Mar 14 3:00u # Easter Time -6:00 Chile EAS%sT 2015 Apr 26 3:00u -5:00 - EAST # @@ -1626,6 +1629,7 @@ Zone America/Port_of_Spain -4:06:04 - LMT 1912 Mar 2 # These all agree with Trinidad and Tobago since 1970. Link America/Port_of_Spain America/Anguilla +Link America/Port_of_Spain America/Antigua Link America/Port_of_Spain America/Dominica Link America/Port_of_Spain America/Grenada Link America/Port_of_Spain America/Guadeloupe diff --git a/jdk/test/tools/launcher/ExecutionEnvironment.java b/jdk/test/tools/launcher/ExecutionEnvironment.java index 894c9a252fa..58acf380b0e 100644 --- a/jdk/test/tools/launcher/ExecutionEnvironment.java +++ b/jdk/test/tools/launcher/ExecutionEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -184,15 +184,7 @@ public class ExecutionEnvironment extends TestHelper { Map env = new HashMap<>(); - if (TestHelper.isLinux || TestHelper.isMacOSX || TestHelper.isAIX) { - for (String x : LD_PATH_STRINGS) { - String pairs[] = x.split("="); - env.put(pairs[0], pairs[1]); - } - - tr = doExec(env, javaCmd, "-jar", testJarFile.getAbsolutePath()); - verifyJavaLibraryPathGeneric(tr); - } else { // Solaris + if (TestHelper.isSolaris) { // no override env.clear(); env.put(LD_LIBRARY_PATH, LD_LIBRARY_PATH_VALUE); @@ -208,6 +200,14 @@ public class ExecutionEnvironment extends TestHelper { // verify the override occurs for 64-bit system tr = doExec(env, javaCmd, "-jar", testJarFile.getAbsolutePath()); verifyJavaLibraryPathOverride(tr, false); + } else { + for (String x : LD_PATH_STRINGS) { + String pairs[] = x.split("="); + env.put(pairs[0], pairs[1]); + } + + tr = doExec(env, javaCmd, "-jar", testJarFile.getAbsolutePath()); + verifyJavaLibraryPathGeneric(tr); } } diff --git a/langtools/.hgtags b/langtools/.hgtags index 315de464668..ad8c0236c61 100644 --- a/langtools/.hgtags +++ b/langtools/.hgtags @@ -298,3 +298,10 @@ ee20efe0255d7ac6e06e88e06f7c72f6c6da7bf9 jdk9-b52 99ff00581f3633c1787bec21f2a8f3a2ffe57665 jdk9-b53 ed34864f3b43a7df394fce6c3f0bc86b70a5d686 jdk9-b54 32a2e724988499e6f68611a65168c5f2fde0f6b9 jdk9-b55 +5ee7bba6ef41447f921184e8522da36734aec089 jdk9-b56 +ec977a00cecbf0007b0fa26c7af2852d57a79cad jdk9-b57 +07ce89fec30165a2f1212047bd23b30086ed1e74 jdk9-b58 +a598534d277e170a0bbf177bd54d9d179245532b jdk9-b59 +81bdc4545337c404bb87373838c983584a49afd6 jdk9-b60 +0eb91327db5a840779cc5c35b9b858d6ef7959d1 jdk9-b61 +40058141a4ec04a3d4cacdb693ad188a5ddf48ed jdk9-b62 diff --git a/langtools/make/CompileInterim.gmk b/langtools/make/CompileInterim.gmk index d3c78279b2a..c957a904978 100644 --- a/langtools/make/CompileInterim.gmk +++ b/langtools/make/CompileInterim.gmk @@ -43,7 +43,6 @@ $(eval $(call SetupJavaCompilation,BUILD_INTERIM_LANGTOOLS, \ $(LANGTOOLS_TOPDIR)/src/jdk.compiler/share/classes \ $(LANGTOOLS_TOPDIR)/src/jdk.dev/share/classes \ $(LANGTOOLS_TOPDIR)/src/jdk.javadoc/share/classes \ - $(LANGTOOLS_TOPDIR)/src/java.base/share/classes \ $(SUPPORT_OUTPUTDIR)/gensrc/jdk.compiler \ $(SUPPORT_OUTPUTDIR)/gensrc/jdk.dev \ $(SUPPORT_OUTPUTDIR)/gensrc/jdk.javadoc, \ diff --git a/langtools/make/Makefile b/langtools/make/Makefile deleted file mode 100644 index ce3a3333405..00000000000 --- a/langtools/make/Makefile +++ /dev/null @@ -1,49 +0,0 @@ -# -# Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# 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. -# - -# Locate this Makefile -ifeq ($(filter /%, $(lastword $(MAKEFILE_LIST))), ) - makefile_path := $(CURDIR)/$(lastword $(MAKEFILE_LIST)) -else - makefile_path := $(lastword $(MAKEFILE_LIST)) -endif -repo_dir := $(patsubst %/make/Makefile, %, $(makefile_path)) - -# What is the name of this subsystem (langtools, corba, etc)? -subsystem_name := $(notdir $(repo_dir)) - -# Try to locate top-level makefile -top_level_makefile := $(repo_dir)/../Makefile -ifneq ($(wildcard $(top_level_makefile)), ) - $(info Will run $(subsystem_name) target on top-level Makefile) - $(info WARNING: This is a non-recommended way of building!) - $(info ===================================================) -else - $(info Cannot locate top-level Makefile. Is this repo not checked out as part of a complete forest?) - $(error Build from top-level Makefile instead) -endif - -all: - @$(MAKE) -f $(top_level_makefile) $(subsystem_name) diff --git a/langtools/make/build.properties b/langtools/make/build.properties index 2a12dbec711..dd902e0ad9e 100644 --- a/langtools/make/build.properties +++ b/langtools/make/build.properties @@ -47,12 +47,11 @@ boot.javac.source = 8 boot.javac.target = 8 #configuration of submodules (share by both the bootstrap and normal compilation): -langtools.modules=java.base:java.compiler:jdk.compiler:jdk.dev:jdk.javadoc -java.base.dependencies= -java.compiler.dependencies=java.base -jdk.compiler.dependencies=java.base:java.compiler -jdk.javadoc.dependencies=java.base:java.compiler:jdk.compiler -jdk.dev.dependencies=java.base:java.compiler:jdk.compiler +langtools.modules=java.compiler:jdk.compiler:jdk.dev:jdk.javadoc +java.compiler.dependencies= +jdk.compiler.dependencies=java.compiler +jdk.javadoc.dependencies=java.compiler:jdk.compiler +jdk.dev.dependencies=java.compiler:jdk.compiler javac.resource.includes = \ com/sun/tools/javac/resources/compiler.properties diff --git a/langtools/make/build.xml b/langtools/make/build.xml index bdaae283bde..e88cf9e76c4 100644 --- a/langtools/make/build.xml +++ b/langtools/make/build.xml @@ -254,7 +254,6 @@ warningsProperty="findbugs.all.warnings" jvm="${target.java.home}/bin/java" jvmargs="-Xmx512M"> - @@ -461,7 +460,6 @@ - @@ -522,8 +520,6 @@ - - - diff --git a/langtools/make/intellij/workspace.xml b/langtools/make/intellij/workspace.xml index bff7ec024c2..135f05a0fd3 100644 --- a/langtools/make/intellij/workspace.xml +++ b/langtools/make/intellij/workspace.xml @@ -10,7 +10,7 @@