This commit is contained in:
Vladimir Kozlov 2017-07-05 18:22:22 -07:00
commit 62d0eedfba
1764 changed files with 30876 additions and 141389 deletions

View file

@ -1,3 +1,5 @@
994036e74ab805bcc09afa0646be17a725bec42f jdk-9+175
94680c6d60ecd9ed3ffd1847706efde7eb947afc jdk-9+174
6dd7fda42bab7ecf648cafb0a4e9b4ca11b3094f jdk-9+173
dad6746278facbbea57dd462cb56fb743dc0a5f0 jdk-9+172
643b5f18c2656fe91b69fea85b07b98d5fad394d jdk-9+171
@ -428,3 +430,5 @@ c42dc7b58b4d4301ea676a76326fd9bbd403d595 jdk-10+8
aa5b01f5e5620438fd39efdb2e2f6365a2c7d898 jdk-10+9
b0f2b8ff25a2209b2c807785d75f20e5086bbfc2 jdk-10+10
036dbf8b381798e5d31065109714d04d97bf98a4 jdk-10+11
e6d70017f5b9adbb2ec82d826973d0251800a3c3 jdk-10+12
9927a9f16738e240ab7014f0118f41e314ef8f99 jdk-10+13

View file

@ -428,3 +428,7 @@ b94be69cbb1d2943b886bf2d458745756df146e4 jdk-10+9
2c25fc24103251f9711a1c280c31e1e41016d90f jdk-9+172
6b750cdb823a029a25ff2e560302cc2d28a86cb6 jdk-10+11
88d7fd969e7df0e07a53b201cfd29393ca33ede9 jdk-9+173
5466f409346e0446ee9a6daeb7f5d75c8fc76823 jdk-9+174
8d4ed1e06fe184c9cb08c5b708e7d6f5c066644f jdk-10+12
8f7227c6012b0051ea4e0bcee040c627bf699b88 jdk-9+175
d67a3f1f057f7e31e12f33ebe3667cb73d252268 jdk-10+13

View file

@ -1 +1,2 @@
project=jdk10
bugids=dup

View file

@ -688,6 +688,7 @@ LIBFFI_LIBS
LIBFFI_CFLAGS
ALSA_LIBS
ALSA_CFLAGS
FREETYPE_LICENSE
FREETYPE_BUNDLE_LIB_PATH
FREETYPE_LIBS
FREETYPE_CFLAGS
@ -1200,6 +1201,7 @@ with_freetype_include
with_freetype_lib
with_freetype_src
enable_freetype_bundling
with_freetype_license
with_alsa
with_alsa_include
with_alsa_lib
@ -2153,6 +2155,7 @@ Optional Packages:
--with-freetype-src specify directory with freetype sources to
automatically build the library (experimental,
Windows-only)
--with-freetype-license if bundling freetype, also bundle this license file
--with-alsa specify prefix directory for the alsa package
(expecting the libraries under PATH/lib and the
headers under PATH/include)
@ -5186,7 +5189,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=1494858828
DATE_WHEN_GENERATED=1496926402
###############################################################################
#
@ -57906,6 +57909,12 @@ if test "${enable_freetype_bundling+set}" = set; then :
fi
# Check whether --with-freetype-license was given.
if test "${with_freetype_license+set}" = set; then :
withval=$with_freetype_license;
fi
# Need to specify explicitly since it needs to be overridden on some versions of macosx
FREETYPE_BASE_NAME=freetype
FREETYPE_CFLAGS=
@ -63852,6 +63861,153 @@ $as_echo "$BUNDLE_FREETYPE" >&6; }
fi # end freetype needed
FREETYPE_LICENSE=""
if test "x$with_freetype_license" = "xyes"; then
as_fn_error $? "--with-freetype-license must have a value" "$LINENO" 5
elif test "x$with_freetype_license" != "x"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for freetype license" >&5
$as_echo_n "checking for freetype license... " >&6; }
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_freetype_license" >&5
$as_echo "$with_freetype_license" >&6; }
FREETYPE_LICENSE="$with_freetype_license"
# Only process if variable expands to non-empty
if test "x$FREETYPE_LICENSE" != 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="$FREETYPE_LICENSE"
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 FREETYPE_LICENSE, which resolves as \"$path\", is invalid." >&5
$as_echo "$as_me: The path of FREETYPE_LICENSE, which resolves as \"$path\", is invalid." >&6;}
as_fn_error $? "Cannot locate the the path of FREETYPE_LICENSE" "$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
FREETYPE_LICENSE="$new_path"
{ $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting FREETYPE_LICENSE to \"$new_path\"" >&5
$as_echo "$as_me: Rewriting FREETYPE_LICENSE to \"$new_path\"" >&6;}
fi
elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then
path="$FREETYPE_LICENSE"
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
FREETYPE_LICENSE="$new_path"
{ $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting FREETYPE_LICENSE to \"$new_path\"" >&5
$as_echo "$as_me: Rewriting FREETYPE_LICENSE 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="$FREETYPE_LICENSE"
has_space=`$ECHO "$path" | $GREP " "`
if test "x$has_space" != x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: The path of FREETYPE_LICENSE, which resolves as \"$path\", is invalid." >&5
$as_echo "$as_me: The path of FREETYPE_LICENSE, 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 FREETYPE_LICENSE, which resolves as \"$path\", is not found." "$LINENO" 5
fi
if test -d "$path"; then
FREETYPE_LICENSE="`cd "$path"; $THEPWDCMD -L`"
else
dir="`$DIRNAME "$path"`"
base="`$BASENAME "$path"`"
FREETYPE_LICENSE="`cd "$dir"; $THEPWDCMD -L`/$base"
fi
fi
fi
if test ! -f "$FREETYPE_LICENSE"; then
as_fn_error $? "$FREETYPE_LICENSE cannot be found" "$LINENO" 5
fi
fi

View file

@ -194,6 +194,8 @@ AC_DEFUN_ONCE([LIB_SETUP_FREETYPE],
[specify directory with freetype sources to automatically build the library (experimental, Windows-only)])])
AC_ARG_ENABLE(freetype-bundling, [AS_HELP_STRING([--disable-freetype-bundling],
[disable bundling of the freetype library with the build result @<:@enabled on Windows or when using --with-freetype, disabled otherwise@:>@])])
AC_ARG_WITH(freetype-license, [AS_HELP_STRING([--with-freetype-license],
[if bundling freetype, also bundle this license file])])
# Need to specify explicitly since it needs to be overridden on some versions of macosx
FREETYPE_BASE_NAME=freetype
@ -443,7 +445,21 @@ AC_DEFUN_ONCE([LIB_SETUP_FREETYPE],
fi # end freetype needed
FREETYPE_LICENSE=""
if test "x$with_freetype_license" = "xyes"; then
AC_MSG_ERROR([--with-freetype-license must have a value])
elif test "x$with_freetype_license" != "x"; then
AC_MSG_CHECKING([for freetype license])
AC_MSG_RESULT([$with_freetype_license])
FREETYPE_LICENSE="$with_freetype_license"
BASIC_FIXUP_PATH(FREETYPE_LICENSE)
if test ! -f "$FREETYPE_LICENSE"; then
AC_MSG_ERROR([$FREETYPE_LICENSE cannot be found])
fi
fi
AC_SUBST(FREETYPE_BUNDLE_LIB_PATH)
AC_SUBST(FREETYPE_CFLAGS)
AC_SUBST(FREETYPE_LIBS)
AC_SUBST(FREETYPE_LICENSE)
])

View file

@ -312,6 +312,7 @@ DEFAULT_MAKE_TARGET:=@DEFAULT_MAKE_TARGET@
FREETYPE_LIBS:=@FREETYPE_LIBS@
FREETYPE_CFLAGS:=@FREETYPE_CFLAGS@
FREETYPE_BUNDLE_LIB_PATH=@FREETYPE_BUNDLE_LIB_PATH@
FREETYPE_LICENSE=@FREETYPE_LICENSE@
CUPS_CFLAGS:=@CUPS_CFLAGS@
ALSA_LIBS:=@ALSA_LIBS@
ALSA_CFLAGS:=@ALSA_CFLAGS@

View file

@ -893,6 +893,16 @@ var getJibProfilesProfiles = function (input, common, data) {
}
});
// The windows ri profile needs to add the freetype license file
profilesRiFreetype = {
"windows-x86-ri": {
configure_args: "--with-freetype-license="
+ input.get("freetype", "install_path")
+ "/freetype-2.7.1-v120-x86/freetype.md"
}
};
profiles = concatObjects(profiles, profilesRiFreetype);
// Generate the missing platform attributes
profiles = generatePlatformAttributes(profiles);
profiles = generateDefaultMakeTargetsConfigureArg(common, profiles);

View file

@ -18,14 +18,16 @@
</header>
<nav id="TOC">
<ul>
<li><a href="#using-the-run-test-framework">Using the run-test framework</a></li>
<li><a href="#using-the-run-test-framework">Using the run-test framework</a><ul>
<li><a href="#configuration">Configuration</a></li>
</ul></li>
<li><a href="#test-selection">Test selection</a><ul>
<li><a href="#jtreg">JTreg</a></li>
<li><a href="#jtreg">JTReg</a></li>
<li><a href="#gtest">Gtest</a></li>
</ul></li>
<li><a href="#test-results-and-summary">Test results and summary</a></li>
<li><a href="#test-suite-control">Test suite control</a><ul>
<li><a href="#jtreg-keywords">JTreg keywords</a></li>
<li><a href="#jtreg-keywords">JTReg keywords</a></li>
<li><a href="#gtest-keywords">Gtest keywords</a></li>
</ul></li>
</ul>
@ -41,14 +43,17 @@ $ make run-test-only TEST=&quot;gtest:LogTagSet gtest:LogTagSetDescriptions&quot
$ make run-test TEST=&quot;hotspot/test:hotspot_gc&quot; JTREG=&quot;JOBS=1;TIMEOUT=8;VM_OTIONS=-XshowSettings -Xlog:gc+ref=debug&quot;
$ make run-test TEST=&quot;jtreg:hotspot/test:hotspot_gc hotspot/test/native_sanity/JniVersion.java&quot;
$ make exploded-run-test TEST=hotspot_tier1</code></pre>
<h3 id="configuration">Configuration</h3>
<p>To be able to run JTReg tests, <code>configure</code> needs to know where to find the JTReg test framework. If it is not picked up automatically by configure, use the <code>--with-jtreg=&lt;path to jtreg home&gt;</code> option to point to the JTReg framework. Note that this option should point to the JTReg home, i.e. the top directory, containing <code>lib/jtreg.jar</code> etc. (An alternative is to set the <code>JT_HOME</code> environment variable to point to the JTReg home before running <code>configure</code>.)</p>
<h2 id="test-selection">Test selection</h2>
<p>All functionality is available using the run-test make target. In this use case, the test or tests to be executed is controlled using the <code>TEST</code> variable. To speed up subsequent test runs with no source code changes, run-test-only can be used instead, which do not depend on the source and test image build.</p>
<p>For some common top-level tests, direct make targets have been generated. This includes all JTreg test groups, the hotspot gtest, and custom tests (if present). This means that <code>make run-test-tier1</code> is equivalent to <code>make run-test TEST=&quot;tier1&quot;</code>, but the latter is more tab-completion friendly. For more complex test runs, the <code>run-test TEST=&quot;x&quot;</code> solution needs to be used.</p>
<p>For some common top-level tests, direct make targets have been generated. This includes all JTReg test groups, the hotspot gtest, and custom tests (if present). This means that <code>make run-test-tier1</code> is equivalent to <code>make run-test TEST=&quot;tier1&quot;</code>, but the latter is more tab-completion friendly. For more complex test runs, the <code>run-test TEST=&quot;x&quot;</code> solution needs to be used.</p>
<p>The test specifications given in <code>TEST</code> is parsed into fully qualified test descriptors, which clearly and unambigously show which tests will be run. As an example, <code>:tier1</code> will expand to <code>jtreg:jdk/test:tier1 jtreg:langtools/test:tier1 jtreg:nashorn/test:tier1 jtreg:jaxp/test:tier1</code>. You can always submit a list of fully qualified test descriptors in the <code>TEST</code> variable if you want to shortcut the parser.</p>
<h3 id="jtreg">JTreg</h3>
<p>JTreg test groups can be specified either without a test root, e.g. <code>:tier1</code> (or <code>tier1</code>, the initial colon is optional), or with, e.g. <code>hotspot/test:tier1</code>, <code>jdk/test:jdk_util</code>.</p>
<h3 id="jtreg">JTReg</h3>
<p>JTReg test groups can be specified either without a test root, e.g. <code>:tier1</code> (or <code>tier1</code>, the initial colon is optional), or with, e.g. <code>hotspot/test:tier1</code>, <code>jdk/test:jdk_util</code>.</p>
<p>When specified without a test root, all matching groups from all tests roots will be added. Otherwise, only the group from the specified test root will be added.</p>
<p>Individual JTreg tests or directories containing JTreg tests can also be specified, like <code>hotspot/test/native_sanity/JniVersion.java</code> or <code>hotspot/test/native_sanity</code>. You can also specify an absolute path, to point to a JTreg test outside the source tree.</p>
<p>Individual JTReg tests or directories containing JTReg tests can also be specified, like <code>hotspot/test/native_sanity/JniVersion.java</code> or <code>hotspot/test/native_sanity</code>. You can also specify an absolute path, to point to a JTReg test outside the source tree.</p>
<p>As long as the test groups or test paths can be uniquely resolved, you do not need to enter the <code>jtreg:</code> prefix. If this is not possible, or if you want to use a fully qualified test descriptor, add <code>jtreg:</code>, e.g. <code>jtreg:hotspot/test/native_sanity</code>.</p>
<h3 id="gtest">Gtest</h3>
<p>Since the Hotspot Gtest suite is so quick, the default is to run all tests. This is specified by just <code>gtest</code>, or as a fully qualified test descriptor <code>gtest:all</code>.</p>
@ -67,15 +72,15 @@ TEST FAILURE</code></pre>
<p>Tests where the number of TOTAL tests does not equal the number of PASSed tests will be considered a test failure. These are marked with the <code>&gt;&gt; ... &lt;&lt;</code> marker for easy identification.</p>
<p>The classification of non-passed tests differs a bit between test suites. In the summary, ERROR is used as a catch-all for tests that neither passed nor are classified as failed by the framework. This might indicate test framework error, timeout or other problems.</p>
<p>In case of test failures, <code>make run-test</code> will exit with a non-zero exit value.</p>
<p>All tests have their result stored in <code>build/$BUILD/test-result/$TEST_ID</code>, where TEST_ID is a path-safe conversion from the fully qualified test descriptor, e.g. for <code>jtreg:jdk/test:tier1</code> the TEST_ID is <code>jtreg_jdk_test_tier1</code>. This path is also printed in the log at the end of the test run.</p>
<p>All tests have their result stored in <code>build/$BUILD/test-results/$TEST_ID</code>, where TEST_ID is a path-safe conversion from the fully qualified test descriptor, e.g. for <code>jtreg:jdk/test:tier1</code> the TEST_ID is <code>jtreg_jdk_test_tier1</code>. This path is also printed in the log at the end of the test run.</p>
<p>Additional work data is stored in <code>build/$BUILD/test-support/$TEST_ID</code>. For some frameworks, this directory might contain information that is useful in determining the cause of a failed test.</p>
<h2 id="test-suite-control">Test suite control</h2>
<p>It is possible to control various aspects of the test suites using make control variables.</p>
<p>These variables use a keyword=value approach to allow multiple values to be set. So, for instance, <code>JTREG=&quot;JOBS=1;TIMEOUT=8&quot;</code> will set the JTreg concurrency level to 1 and the timeout factor to 8. This is equivalent to setting <code>JTREG_JOBS=1 JTREG_TIMEOUT=8</code>, but using the keyword format means that the <code>JTREG</code> variable is parsed and verified for correctness, so <code>JTREG=&quot;TMIEOUT=8&quot;</code> would give an error, while <code>JTREG_TMIEOUT=8</code> would just pass unnoticed.</p>
<p>These variables use a keyword=value approach to allow multiple values to be set. So, for instance, <code>JTREG=&quot;JOBS=1;TIMEOUT=8&quot;</code> will set the JTReg concurrency level to 1 and the timeout factor to 8. This is equivalent to setting <code>JTREG_JOBS=1 JTREG_TIMEOUT=8</code>, but using the keyword format means that the <code>JTREG</code> variable is parsed and verified for correctness, so <code>JTREG=&quot;TMIEOUT=8&quot;</code> would give an error, while <code>JTREG_TMIEOUT=8</code> would just pass unnoticed.</p>
<p>To separate multiple keyword=value pairs, use <code>;</code> (semicolon). Since the shell normally eats <code>;</code>, the recommended usage is to write the assignment inside qoutes, e.g. <code>JTREG=&quot;...;...&quot;</code>. This will also make sure spaces are preserved, as in <code>JTREG=&quot;VM_OTIONS=-XshowSettings -Xlog:gc+ref=debug&quot;</code>.</p>
<p>(Other ways are possible, e.g. using backslash: <code>JTREG=JOBS=1\;TIMEOUT=8</code>. Also, as a special technique, the string <code>%20</code> will be replaced with space for certain options, e.g. <code>JTREG=VM_OTIONS=-XshowSettings%20-Xlog:gc+ref=debug</code>. This can be useful if you have layers of scripts and have trouble getting proper quoting of command line arguments through.)</p>
<p>As far as possible, the names of the keywords have been standardized between test suites.</p>
<h3 id="jtreg-keywords">JTreg keywords</h3>
<h3 id="jtreg-keywords">JTReg keywords</h3>
<h4 id="jobs">JOBS</h4>
<p>The test concurrency (<code>-concurrency</code>).</p>
<p>Defaults to TEST_JOBS (if set by <code>--with-test-jobs=</code>), otherwise it defaults to JOBS, except for Hotspot, where the default is <em>number of CPU cores/2</em>, but never more than 12.</p>
@ -96,15 +101,15 @@ TEST FAILURE</code></pre>
<p>Defaults to <code>fail,error</code>.</p>
<h4 id="max_mem">MAX_MEM</h4>
<p>Limit memory consumption (<code>-Xmx</code> and <code>-vmoption:-Xmx</code>, or none).</p>
<p>Limit memory consumption for JTreg test framework and VM under test. Set to 0 to disable the limits.</p>
<p>Limit memory consumption for JTReg test framework and VM under test. Set to 0 to disable the limits.</p>
<p>Defaults to 512m, except for hotspot, where it defaults to 0 (no limit).</p>
<h4 id="options">OPTIONS</h4>
<p>Additional options to the JTreg test framework.</p>
<p>Use <code>JTREG=&quot;OPTIONS=--help all&quot;</code> to see all available JTreg options.</p>
<p>Additional options to the JTReg test framework.</p>
<p>Use <code>JTREG=&quot;OPTIONS=--help all&quot;</code> to see all available JTReg options.</p>
<h4 id="java_options">JAVA_OPTIONS</h4>
<p>Additional Java options to JTreg (<code>-javaoption</code>).</p>
<p>Additional Java options to JTReg (<code>-javaoption</code>).</p>
<h4 id="vm_options">VM_OPTIONS</h4>
<p>Additional VM options to JTreg (<code>-vmoption</code>).</p>
<p>Additional VM options to JTReg (<code>-vmoption</code>).</p>
<h3 id="gtest-keywords">Gtest keywords</h3>
<h4 id="repeat">REPEAT</h4>
<p>The number of times to repeat the tests (<code>--gtest_repeat</code>).</p>

View file

@ -22,6 +22,15 @@ Some example command-lines:
$ make run-test TEST="jtreg:hotspot/test:hotspot_gc hotspot/test/native_sanity/JniVersion.java"
$ make exploded-run-test TEST=hotspot_tier1
### Configuration
To be able to run JTReg tests, `configure` needs to know where to find the
JTReg test framework. If it is not picked up automatically by configure, use
the `--with-jtreg=<path to jtreg home>` option to point to the JTReg framework.
Note that this option should point to the JTReg home, i.e. the top directory,
containing `lib/jtreg.jar` etc. (An alternative is to set the `JT_HOME`
environment variable to point to the JTReg home before running `configure`.)
## Test selection
All functionality is available using the run-test make target. In this use
@ -30,7 +39,7 @@ To speed up subsequent test runs with no source code changes, run-test-only can
be used instead, which do not depend on the source and test image build.
For some common top-level tests, direct make targets have been generated. This
includes all JTreg test groups, the hotspot gtest, and custom tests (if
includes all JTReg test groups, the hotspot gtest, and custom tests (if
present). This means that `make run-test-tier1` is equivalent to `make run-test
TEST="tier1"`, but the latter is more tab-completion friendly. For more complex
test runs, the `run-test TEST="x"` solution needs to be used.
@ -42,9 +51,9 @@ jtreg:langtools/test:tier1 jtreg:nashorn/test:tier1 jtreg:jaxp/test:tier1`. You
can always submit a list of fully qualified test descriptors in the `TEST`
variable if you want to shortcut the parser.
### JTreg
### JTReg
JTreg test groups can be specified either without a test root, e.g. `:tier1`
JTReg test groups can be specified either without a test root, e.g. `:tier1`
(or `tier1`, the initial colon is optional), or with, e.g.
`hotspot/test:tier1`, `jdk/test:jdk_util`.
@ -52,10 +61,10 @@ When specified without a test root, all matching groups from all tests roots
will be added. Otherwise, only the group from the specified test root will be
added.
Individual JTreg tests or directories containing JTreg tests can also be
Individual JTReg tests or directories containing JTReg tests can also be
specified, like `hotspot/test/native_sanity/JniVersion.java` or
`hotspot/test/native_sanity`. You can also specify an absolute path, to point
to a JTreg test outside the source tree.
to a JTReg test outside the source tree.
As long as the test groups or test paths can be uniquely resolved, you do not
need to enter the `jtreg:` prefix. If this is not possible, or if you want to
@ -99,7 +108,7 @@ error, timeout or other problems.
In case of test failures, `make run-test` will exit with a non-zero exit value.
All tests have their result stored in `build/$BUILD/test-result/$TEST_ID`,
All tests have their result stored in `build/$BUILD/test-results/$TEST_ID`,
where TEST_ID is a path-safe conversion from the fully qualified test
descriptor, e.g. for `jtreg:jdk/test:tier1` the TEST_ID is
`jtreg_jdk_test_tier1`. This path is also printed in the log at the end of the
@ -115,7 +124,7 @@ It is possible to control various aspects of the test suites using make control
variables.
These variables use a keyword=value approach to allow multiple values to be
set. So, for instance, `JTREG="JOBS=1;TIMEOUT=8"` will set the JTreg
set. So, for instance, `JTREG="JOBS=1;TIMEOUT=8"` will set the JTReg
concurrency level to 1 and the timeout factor to 8. This is equivalent to
setting `JTREG_JOBS=1 JTREG_TIMEOUT=8`, but using the keyword format means that
the `JTREG` variable is parsed and verified for correctness, so
@ -136,7 +145,7 @@ proper quoting of command line arguments through.)
As far as possible, the names of the keywords have been standardized between
test suites.
### JTreg keywords
### JTReg keywords
#### JOBS
The test concurrency (`-concurrency`).
@ -174,21 +183,21 @@ Defaults to `fail,error`.
#### MAX_MEM
Limit memory consumption (`-Xmx` and `-vmoption:-Xmx`, or none).
Limit memory consumption for JTreg test framework and VM under test. Set to 0
Limit memory consumption for JTReg test framework and VM under test. Set to 0
to disable the limits.
Defaults to 512m, except for hotspot, where it defaults to 0 (no limit).
#### OPTIONS
Additional options to the JTreg test framework.
Additional options to the JTReg test framework.
Use `JTREG="OPTIONS=--help all"` to see all available JTreg options.
Use `JTREG="OPTIONS=--help all"` to see all available JTReg options.
#### JAVA_OPTIONS
Additional Java options to JTreg (`-javaoption`).
Additional Java options to JTReg (`-javaoption`).
#### VM_OPTIONS
Additional VM options to JTreg (`-vmoption`).
Additional VM options to JTReg (`-vmoption`).
### Gtest keywords

View file

@ -428,3 +428,7 @@ c62e5964cfcf144d8f72e9ba69757897785349a9 jdk-9+171
95ed14547ca9246baed34f90ef3ca13217538a8c jdk-9+172
8ef8a0f1c4dfea17e10125e1f885920538e63085 jdk-10+11
534ba4f8cfcf12accc5b9adb943103f2ff79fe16 jdk-9+173
3615768c12904e29bb2ec1b506cd4633cd8a9ced jdk-9+174
00ae6307d78bac49883ddc85d687aa88c49f3971 jdk-10+12
dc78a3dd6b3a4f11cdae8a3e3d160e6a78bc7838 jdk-9+175
564fced058bd2c8375e9104aa8f9494642cd7bdd jdk-10+13

View file

@ -1 +1,2 @@
project=jdk10
bugids=dup

View file

@ -26,18 +26,21 @@
/**
* Defines the Java binding of the OMG CORBA APIs, and the RMI-IIOP API.
*
* <p> This module is upgradeble.
*
* @moduleGraph
* @since 9
*/
@Deprecated(since="9", forRemoval=true)
module java.corba {
requires transitive java.desktop;
requires transitive java.rmi;
requires java.logging;
requires java.naming;
requires java.transaction;
requires jdk.unsupported;
requires transitive java.desktop;
requires transitive java.rmi;
exports javax.activity;
exports javax.rmi;
exports javax.rmi.CORBA;

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -29,7 +29,7 @@ package org.omg.CORBA;
/**
* This Helper class is used to facilitate the marshalling of {@code Bounds}.
* For more information on Helper files, see
* <a href="doc-files/generatedfiles.html#helper">
* <a href="{@docRoot}/org/omg/CORBA/doc-files/generatedfiles.html#helper">
* "Generated Files: Helper Files"</a>.
*/

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
* 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 @@ package org.omg.CORBA.ORBPackage;
* This Helper class is used to facilitate the marshalling of
* {@code ORBPackage/InvalidName}.
* For more information on Helper files, see
* <a href="doc-files/generatedfiles.html#helper">
* <a href="{@docRoot}/org/omg/CORBA/doc-files/generatedfiles.html#helper">
* "Generated Files: Helper Files"</a>.
*/

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
* 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 @@ package org.omg.CORBA.TypeCodePackage;
* This Helper class is used to facilitate the marshalling of
* {@code TypeCodePackage/BadKind}.
* For more information on Helper files, see
* <a href="doc-files/generatedfiles.html#helper">
* <a href="{@docRoot}/org/omg/CORBA/doc-files/generatedfiles.html#helper">
* "Generated Files: Helper Files"</a>.
*/

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
* 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 @@ package org.omg.CORBA.TypeCodePackage;
* This Helper class is used to facilitate the marshalling of
* {@code TypeCodePackage/Bounds}.
* For more information on Helper files, see
* <a href="doc-files/generatedfiles.html#helper">
* <a href="{@docRoot}/org/omg/CORBA/doc-files/generatedfiles.html#helper">
* "Generated Files: Helper Files"</a>.
*/

View file

@ -588,3 +588,7 @@ c6cd3ec8d46b034e57c86399380ffcf7f25706e4 jdk-10+10
1ae9e84f68b359420d2d153ecfe5ee2903e33a2e jdk-9+172
7f14e550f1e8abea41c223e5fdad2261e99ba929 jdk-10+11
e64b1cb48d6e7703928a9d1da106fc27f8cb65fd jdk-9+173
944791f8160185bffa13fbb821fc09b6198f1f25 jdk-9+174
070aa7a2eb14c4645f7eb31384cba0a2ba72a4b5 jdk-10+12
8f04d457168b9f1f4a1b2c37f49e0513ca9d33a7 jdk-9+175
a9da03357f190807591177fe9846d6e68ad64fc0 jdk-10+13

View file

@ -1 +1,2 @@
project=jdk10
bugids=dup

View file

@ -188,7 +188,6 @@ JVM_Yield
JVM_AddModuleExports
JVM_AddModuleExportsToAll
JVM_AddModuleExportsToAllUnnamed
JVM_AddModulePackage
JVM_AddReadsModule
JVM_DefineModule
JVM_SetBootLoaderUnnamedModule

View file

@ -56,6 +56,7 @@ BUILD_HOTSPOT_JTREG_NATIVE_SRC := \
$(HOTSPOT_TOPDIR)/test/compiler/floatingpoint/ \
$(HOTSPOT_TOPDIR)/test/compiler/calls \
$(HOTSPOT_TOPDIR)/test/serviceability/jvmti/GetNamedModule \
$(HOTSPOT_TOPDIR)/test/serviceability/jvmti/IsModifiableModule \
$(HOTSPOT_TOPDIR)/test/serviceability/jvmti/AddModuleReads \
$(HOTSPOT_TOPDIR)/test/serviceability/jvmti/AddModuleExportsAndOpens \
$(HOTSPOT_TOPDIR)/test/serviceability/jvmti/AddModuleUsesAndProvides \
@ -85,6 +86,7 @@ ifeq ($(TOOLCHAIN_TYPE), solstudio)
BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_liboverflow := -lc
BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libSimpleClassFileLoadHook := -lc
BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libGetNamedModuleTest := -lc
BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libIsModifiableModuleTest := -lc
BUILD_HOTSPOT_JTREG_LIBRARIES_LDFLAGS_libAddModuleReadsTest := -lc
BUILD_HOTSPOT_JTREG_LIBRARIES_LDFLAGS_libAddModuleExportsAndOpensTest := -lc
BUILD_HOTSPOT_JTREG_LIBRARIES_LDFLAGS_libAddModuleUsesAndProvidesTest := -lc

View file

@ -109,9 +109,15 @@ int AbstractInterpreter::size_activation(int max_stack,
// for the callee's params we only need to account for the extra
// locals.
int size = overhead +
(callee_locals - callee_params)*Interpreter::stackElementWords +
(callee_locals - callee_params) +
monitors * frame::interpreter_frame_monitor_size() +
temps* Interpreter::stackElementWords + extra_args;
// On the top frame, at all times SP <= ESP, and SP is
// 16-aligned. We ensure this by adjusting SP on method
// entry and re-entry to allow room for the maximum size of
// the expression stack. When we call another method we bump
// SP so that no stack space is wasted. So, only on the top
// frame do we need to allow max_stack words.
(is_top_frame ? max_stack : temps + extra_args);
// On AArch64 we always keep the stack pointer 16-aligned, so we
// must round up here.

View file

@ -598,12 +598,12 @@ void LIRGenerator::do_ArithmeticOp_Int(ArithmeticOp* x) {
} else {
assert (x->op() == Bytecodes::_imul, "expect imul");
if (right.is_constant()) {
int c = right.get_jint_constant();
if (! is_power_of_2(c) && ! is_power_of_2(c + 1) && ! is_power_of_2(c - 1)) {
// Cannot use constant op.
right.load_item();
jint c = right.get_jint_constant();
if (c > 0 && c < max_jint && (is_power_of_2(c) || is_power_of_2(c - 1) || is_power_of_2(c + 1))) {
right_arg->dont_load_item();
} else {
right.dont_load_item();
// Cannot use constant op.
right_arg->load_item();
}
} else {
right.load_item();

View file

@ -51,6 +51,11 @@ extern "C" void bad_compiled_vtable_index(JavaThread* thread,
VtableStub* VtableStubs::create_vtable_stub(int vtable_index) {
const int aarch64_code_length = VtableStub::pd_code_size_limit(true);
VtableStub* s = new(aarch64_code_length) VtableStub(true, vtable_index);
// Can be NULL if there is no free space in the code cache.
if (s == NULL) {
return NULL;
}
ResourceMark rm;
CodeBuffer cb(s->entry_point(), aarch64_code_length);
MacroAssembler* masm = new MacroAssembler(&cb);

View file

@ -923,8 +923,8 @@ void LIRGenerator::do_ArithmeticOp_Int(ArithmeticOp* x) {
} else {
left_arg->load_item();
if (x->op() == Bytecodes::_imul && right_arg->is_constant()) {
int c = right_arg->get_jint_constant();
if (c > 0 && (is_power_of_2(c) || is_power_of_2(c - 1) || is_power_of_2(c + 1))) {
jint c = right_arg->get_jint_constant();
if (c > 0 && c < max_jint && (is_power_of_2(c) || is_power_of_2(c - 1) || is_power_of_2(c + 1))) {
right_arg->dont_load_item();
} else {
right_arg->load_item();

View file

@ -234,8 +234,8 @@ void LIRGenerator::cmp_reg_mem(LIR_Condition condition, LIR_Opr reg, LIR_Opr bas
}
bool LIRGenerator::strength_reduce_multiply(LIR_Opr left, int c, LIR_Opr result, LIR_Opr tmp) {
if (tmp->is_valid()) {
bool LIRGenerator::strength_reduce_multiply(LIR_Opr left, jint c, LIR_Opr result, LIR_Opr tmp) {
if (tmp->is_valid() && c > 0 && c < max_jint) {
if (is_power_of_2(c + 1)) {
__ move(left, tmp);
__ shift_left(left, log2_intptr(c + 1), left);
@ -603,8 +603,8 @@ void LIRGenerator::do_ArithmeticOp_Int(ArithmeticOp* x) {
bool use_constant = false;
bool use_tmp = false;
if (right_arg->is_constant()) {
int iconst = right_arg->get_jint_constant();
if (iconst > 0) {
jint iconst = right_arg->get_jint_constant();
if (iconst > 0 && iconst < max_jint) {
if (is_power_of_2(iconst)) {
use_constant = true;
} else if (is_power_of_2(iconst - 1) || is_power_of_2(iconst + 1)) {

View file

@ -23,8 +23,15 @@
* questions.
*/
/**
* Defines the Ahead-of-Time (AOT) compiler, <em>{@index jaotc jaotc tool}</em>,
* for compiling Java classes into AOT library.
*
* @moduleGraph
* @since 9
*/
module jdk.aot {
requires jdk.management;
requires jdk.internal.vm.ci;
requires jdk.internal.vm.compiler;
requires jdk.management;
}

View file

@ -26,6 +26,15 @@
/**
* Defines the implementation of the HotSpot Serviceability Agent.
*
* <p> This module includes the <em>{@index jhsdb jhsdb tool}</em> tool to
* attach to a running Java Virtual Machine (JVM) or launch a postmortem
* debugger to analyze the content of a core-dump from a crashed JVM.
*
* <dl style="font-family:'DejaVu Sans', Arial, Helvetica, sans serif">
* <dt class="simpleTagLabel">Tool Guides:</dt>
* <dd> {@extLink jhsdb_tool_reference jhsdb}</dd>
* </dl>
*
* @moduleGraph
* @since 9
*/

View file

@ -644,4 +644,9 @@ final class CompilerToVM {
* {@link Long}
*/
native Object getFlagValue(String name);
/**
* Gets the host class for {@code type}.
*/
native HotSpotResolvedObjectTypeImpl getHostClass(HotSpotResolvedObjectTypeImpl type);
}

View file

@ -411,6 +411,14 @@ final class HotSpotResolvedObjectTypeImpl extends HotSpotResolvedJavaType implem
return false;
}
@Override
public ResolvedJavaType getHostClass() {
if (isArray()) {
return null;
}
return compilerToVM().getHostClass(this);
}
@Override
public boolean isJavaLangObject() {
return javaClass.equals(Object.class);

View file

@ -153,6 +153,11 @@ public final class HotSpotResolvedPrimitiveType extends HotSpotResolvedJavaType
return other.equals(this);
}
@Override
public ResolvedJavaType getHostClass() {
return null;
}
@Override
public JavaKind getJavaKind() {
return kind;

View file

@ -104,6 +104,13 @@ public interface ResolvedJavaType extends JavaType, ModifiersProvider, Annotated
*/
boolean isAssignableFrom(ResolvedJavaType other);
/**
* Returns the {@link ResolvedJavaType} object representing the host class of this VM anonymous
* class (as opposed to the unrelated concept specified by {@link Class#isAnonymousClass()}) or
* {@code null} if this object does not represent a VM anonymous class.
*/
ResolvedJavaType getHostClass();
/**
* Returns true if this type is exactly the type {@link java.lang.Object}.
*/

View file

@ -26,11 +26,9 @@
module jdk.internal.vm.compiler {
requires java.instrument;
requires java.management;
requires jdk.management;
requires jdk.internal.vm.ci;
// sun.misc.Unsafe is used
requires jdk.unsupported;
requires jdk.management;
requires jdk.unsupported; // sun.misc.Unsafe is used
uses org.graalvm.compiler.code.DisassemblerProvider;
uses org.graalvm.compiler.core.match.MatchStatementSet;

View file

@ -251,7 +251,13 @@ public class StandardGraphBuilderPlugins {
for (JavaKind kind : new JavaKind[]{JavaKind.Int, JavaKind.Long, JavaKind.Object}) {
Class<?> javaClass = kind == JavaKind.Object ? Object.class : kind.toJavaClass();
r.register5("compareAndSwap" + kind.name(), Receiver.class, Object.class, long.class, javaClass, javaClass, new InvocationPlugin() {
String casName;
if (Java8OrEarlier) {
casName = "compareAndSwap";
} else {
casName = "compareAndSet";
}
r.register5(casName + kind.name(), Receiver.class, Object.class, long.class, javaClass, javaClass, new InvocationPlugin() {
@Override
public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver unsafe, ValueNode object, ValueNode offset, ValueNode expected, ValueNode x) {
// Emits a null-check for the otherwise unused receiver

View file

@ -548,8 +548,8 @@ void LIRGenerator::arithmetic_op(Bytecodes::Code code, LIR_Opr result, LIR_Opr l
bool did_strength_reduce = false;
if (right->is_constant()) {
int c = right->as_jint();
if (is_power_of_2(c)) {
jint c = right->as_jint();
if (c > 0 && is_power_of_2(c)) {
// do not need tmp here
__ shift_left(left_op, exact_log2(c), result_op);
did_strength_reduce = true;

View file

@ -313,7 +313,7 @@ class LIRGenerator: public InstructionVisitor, public BlockClosure {
// is_strictfp is only needed for mul and div (and only generates different code on i486)
void arithmetic_op(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, bool is_strictfp, LIR_Opr tmp, CodeEmitInfo* info = NULL);
// machine dependent. returns true if it emitted code for the multiply
bool strength_reduce_multiply(LIR_Opr left, int constant, LIR_Opr result, LIR_Opr tmp);
bool strength_reduce_multiply(LIR_Opr left, jint constant, LIR_Opr result, LIR_Opr tmp);
void store_stack_parameter (LIR_Opr opr, ByteSize offset_from_sp_in_bytes);

View file

@ -722,74 +722,6 @@ jobject Modules::get_module(Symbol* package_name, Handle h_loader, TRAPS) {
return NULL;
}
void Modules::add_module_package(jobject module, const char* package_name, TRAPS) {
ResourceMark rm(THREAD);
if (module == NULL) {
THROW_MSG(vmSymbols::java_lang_NullPointerException(),
"module is null");
}
if (package_name == NULL) {
THROW_MSG(vmSymbols::java_lang_NullPointerException(),
"package is null");
}
ModuleEntry* module_entry = get_module_entry(module, CHECK);
if (module_entry == NULL) {
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
"module is invalid");
}
if (!module_entry->is_named()) {
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
"module cannot be an unnamed module");
}
if (!verify_package_name(package_name)) {
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
err_msg("Invalid package name: %s", package_name));
}
ClassLoaderData *loader_data = module_entry->loader_data();
// Only modules defined to either the boot or platform class loader, can define a "java/" package.
if (!loader_data->is_the_null_class_loader_data() &&
!loader_data->is_platform_class_loader_data() &&
(strncmp(package_name, JAVAPKG, JAVAPKG_LEN) == 0 &&
(package_name[JAVAPKG_LEN] == '/' || package_name[JAVAPKG_LEN] == '\0'))) {
const char* class_loader_name = SystemDictionary::loader_name(loader_data);
size_t pkg_len = strlen(package_name);
char* pkg_name = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, pkg_len);
strncpy(pkg_name, package_name, pkg_len);
StringUtils::replace_no_expand(pkg_name, "/", ".");
const char* msg_text1 = "Class loader (instance of): ";
const char* msg_text2 = " tried to define prohibited package name: ";
size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + pkg_len + 1;
char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, pkg_name);
THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), message);
}
log_debug(module)("add_module_package(): Adding package %s to module %s",
package_name, module_entry->name()->as_C_string());
TempNewSymbol pkg_symbol = SymbolTable::new_symbol(package_name, CHECK);
PackageEntryTable* package_table = loader_data->packages();
assert(package_table != NULL, "Missing package_table");
PackageEntry* existing_pkg = NULL;
{
MutexLocker ml(Module_lock, THREAD);
// Check that the package does not exist in the class loader's package table.
existing_pkg = package_table->lookup_only(pkg_symbol);
if (existing_pkg == NULL) {
PackageEntry* pkg = package_table->locked_create_entry_or_null(pkg_symbol, module_entry);
assert(pkg != NULL, "Unable to create a module's package entry");
}
}
if (existing_pkg != NULL) {
throw_dup_pkg_exception(module_entry->name()->as_C_string(), existing_pkg, CHECK);
}
}
// Export package in module to all unnamed modules.
void Modules::add_module_exports_to_all_unnamed(jobject module, const char* package_name, TRAPS) {
if (module == NULL) {

View file

@ -113,14 +113,6 @@ public:
// Returns NULL if package is invalid or not defined by loader.
static jobject get_module(Symbol* package_name, Handle h_loader, TRAPS);
// This adds package to module.
// It throws IllegalArgumentException if:
// * Module is bad
// * Module is unnamed
// * Package is not syntactically correct
// * Package is already defined for module's class loader.
static void add_module_package(jobject module, const char* package, TRAPS);
// Marks the specified package as exported to all unnamed modules.
// If either module or package is null then NullPointerException is thrown.
// If module or package is bad, or module is unnamed, or package is not in

View file

@ -130,6 +130,7 @@ class CodeBlob_sizes {
// Iterate over all CodeHeaps
#define FOR_ALL_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _heaps->begin(); heap != _heaps->end(); ++heap)
#define FOR_ALL_NMETHOD_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _nmethod_heaps->begin(); heap != _nmethod_heaps->end(); ++heap)
#define FOR_ALL_ALLOCABLE_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _allocable_heaps->begin(); heap != _allocable_heaps->end(); ++heap)
// Iterate over all CodeBlobs (cb) on the given CodeHeap
#define FOR_ALL_BLOBS(cb, heap) for (CodeBlob* cb = first_blob(heap); cb != NULL; cb = next_blob(heap, cb))
@ -140,10 +141,11 @@ int CodeCache::_number_of_nmethods_with_dependencies = 0;
bool CodeCache::_needs_cache_clean = false;
nmethod* CodeCache::_scavenge_root_nmethods = NULL;
// Initialize array of CodeHeaps
// Initialize arrays of CodeHeap subsets
GrowableArray<CodeHeap*>* CodeCache::_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, true);
GrowableArray<CodeHeap*>* CodeCache::_compiled_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, true);
GrowableArray<CodeHeap*>* CodeCache::_nmethod_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, true);
GrowableArray<CodeHeap*>* CodeCache::_allocable_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, true);
void CodeCache::check_heap_sizes(size_t non_nmethod_size, size_t profiled_size, size_t non_profiled_size, size_t cache_size, bool all_set) {
size_t total_size = non_nmethod_size + profiled_size + non_profiled_size;
@ -338,6 +340,7 @@ ReservedCodeSpace CodeCache::reserve_heap_memory(size_t size) {
return rs;
}
// Heaps available for allocation
bool CodeCache::heap_available(int code_blob_type) {
if (!SegmentedCodeCache) {
// No segmentation: use a single code heap
@ -391,6 +394,9 @@ void CodeCache::add_heap(CodeHeap* heap) {
if (code_blob_type_accepts_nmethod(type)) {
_nmethod_heaps->insert_sorted<code_heap_compare>(heap);
}
if (code_blob_type_accepts_allocable(type)) {
_allocable_heaps->insert_sorted<code_heap_compare>(heap);
}
}
void CodeCache::add_heap(ReservedSpace rs, const char* name, int code_blob_type) {
@ -620,7 +626,7 @@ nmethod* CodeCache::find_nmethod(void* start) {
void CodeCache::blobs_do(void f(CodeBlob* nm)) {
assert_locked_or_safepoint(CodeCache_lock);
FOR_ALL_NMETHOD_HEAPS(heap) {
FOR_ALL_HEAPS(heap) {
FOR_ALL_BLOBS(cb, *heap) {
f(cb);
}
@ -663,7 +669,7 @@ void CodeCache::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurre
void CodeCache::blobs_do(CodeBlobClosure* f) {
assert_locked_or_safepoint(CodeCache_lock);
FOR_ALL_NMETHOD_HEAPS(heap) {
FOR_ALL_ALLOCABLE_HEAPS(heap) {
FOR_ALL_BLOBS(cb, *heap) {
if (cb->is_alive()) {
f->do_code_blob(cb);
@ -960,7 +966,7 @@ address CodeCache::high_bound(int code_blob_type) {
size_t CodeCache::capacity() {
size_t cap = 0;
FOR_ALL_NMETHOD_HEAPS(heap) {
FOR_ALL_ALLOCABLE_HEAPS(heap) {
cap += (*heap)->capacity();
}
return cap;
@ -973,7 +979,7 @@ size_t CodeCache::unallocated_capacity(int code_blob_type) {
size_t CodeCache::unallocated_capacity() {
size_t unallocated_cap = 0;
FOR_ALL_NMETHOD_HEAPS(heap) {
FOR_ALL_ALLOCABLE_HEAPS(heap) {
unallocated_cap += (*heap)->unallocated_capacity();
}
return unallocated_cap;
@ -981,7 +987,7 @@ size_t CodeCache::unallocated_capacity() {
size_t CodeCache::max_capacity() {
size_t max_cap = 0;
FOR_ALL_NMETHOD_HEAPS(heap) {
FOR_ALL_ALLOCABLE_HEAPS(heap) {
max_cap += (*heap)->max_capacity();
}
return max_cap;
@ -1007,7 +1013,7 @@ double CodeCache::reverse_free_ratio(int code_blob_type) {
size_t CodeCache::bytes_allocated_in_freelists() {
size_t allocated_bytes = 0;
FOR_ALL_NMETHOD_HEAPS(heap) {
FOR_ALL_ALLOCABLE_HEAPS(heap) {
allocated_bytes += (*heap)->allocated_in_freelist();
}
return allocated_bytes;
@ -1015,7 +1021,7 @@ size_t CodeCache::bytes_allocated_in_freelists() {
int CodeCache::allocated_segments() {
int number_of_segments = 0;
FOR_ALL_NMETHOD_HEAPS(heap) {
FOR_ALL_ALLOCABLE_HEAPS(heap) {
number_of_segments += (*heap)->allocated_segments();
}
return number_of_segments;
@ -1023,7 +1029,7 @@ int CodeCache::allocated_segments() {
size_t CodeCache::freelists_length() {
size_t length = 0;
FOR_ALL_NMETHOD_HEAPS(heap) {
FOR_ALL_ALLOCABLE_HEAPS(heap) {
length += (*heap)->freelist_length();
}
return length;
@ -1354,7 +1360,7 @@ void CodeCache::report_codemem_full(int code_blob_type, bool print) {
void CodeCache::print_memory_overhead() {
size_t wasted_bytes = 0;
FOR_ALL_NMETHOD_HEAPS(heap) {
FOR_ALL_ALLOCABLE_HEAPS(heap) {
CodeHeap* curr_heap = *heap;
for (CodeBlob* cb = (CodeBlob*)curr_heap->first(); cb != NULL; cb = (CodeBlob*)curr_heap->next(cb)) {
HeapBlock* heap_block = ((HeapBlock*)cb) - 1;
@ -1400,7 +1406,7 @@ void CodeCache::print_internals() {
ResourceMark rm;
int i = 0;
FOR_ALL_NMETHOD_HEAPS(heap) {
FOR_ALL_ALLOCABLE_HEAPS(heap) {
if ((_nmethod_heaps->length() >= 1) && Verbose) {
tty->print_cr("-- %s --", (*heap)->name());
}
@ -1497,7 +1503,7 @@ void CodeCache::print() {
CodeBlob_sizes live;
CodeBlob_sizes dead;
FOR_ALL_NMETHOD_HEAPS(heap) {
FOR_ALL_ALLOCABLE_HEAPS(heap) {
FOR_ALL_BLOBS(cb, *heap) {
if (!cb->is_alive()) {
dead.add(cb);
@ -1523,7 +1529,7 @@ void CodeCache::print() {
int number_of_blobs = 0;
int number_of_oop_maps = 0;
int map_size = 0;
FOR_ALL_NMETHOD_HEAPS(heap) {
FOR_ALL_ALLOCABLE_HEAPS(heap) {
FOR_ALL_BLOBS(cb, *heap) {
if (cb->is_alive()) {
number_of_blobs++;

View file

@ -85,6 +85,7 @@ class CodeCache : AllStatic {
static GrowableArray<CodeHeap*>* _heaps;
static GrowableArray<CodeHeap*>* _compiled_heaps;
static GrowableArray<CodeHeap*>* _nmethod_heaps;
static GrowableArray<CodeHeap*>* _allocable_heaps;
static address _low_bound; // Lower bound of CodeHeap addresses
static address _high_bound; // Upper bound of CodeHeap addresses
@ -237,6 +238,11 @@ class CodeCache : AllStatic {
return type == CodeBlobType::All || type <= CodeBlobType::MethodProfiled;
}
static bool code_blob_type_accepts_allocable(int type) {
return type <= CodeBlobType::All;
}
// Returns the CodeBlobType for the given compilation level
static int get_code_blob_type(int comp_level) {
if (comp_level == CompLevel_none ||

View file

@ -1557,7 +1557,7 @@ void CompileBroker::compiler_thread_loop() {
// First thread to get here will initialize the compiler interface
if (!ciObjectFactory::is_initialized()) {
{
ASSERT_IN_VM;
MutexLocker only_one (CompileThread_lock, thread);
if (!ciObjectFactory::is_initialized()) {

View file

@ -1687,6 +1687,13 @@ C2V_VMENTRY(jlong, getFingerprint, (JNIEnv*, jobject, jlong metaspace_klass))
}
C2V_END
C2V_VMENTRY(jobject, getHostClass, (JNIEnv*, jobject, jobject jvmci_type))
InstanceKlass* k = InstanceKlass::cast(CompilerToVM::asKlass(jvmci_type));
InstanceKlass* host = k->host_klass();
oop result = CompilerToVM::get_jvmci_type(host, CHECK_NULL);
return JNIHandles::make_local(THREAD, result);
C2V_END
C2V_VMENTRY(int, interpreterFrameSize, (JNIEnv*, jobject, jobject bytecode_frame_handle))
if (bytecode_frame_handle == NULL) {
THROW_0(vmSymbols::java_lang_NullPointerException());
@ -1817,6 +1824,7 @@ JNINativeMethod CompilerToVM::methods[] = {
{CC "flushDebugOutput", CC "()V", FN_PTR(flushDebugOutput)},
{CC "methodDataProfileDataSize", CC "(JI)I", FN_PTR(methodDataProfileDataSize)},
{CC "getFingerprint", CC "(J)J", FN_PTR(getFingerprint)},
{CC "getHostClass", CC "(" HS_RESOLVED_KLASS ")" HS_RESOLVED_KLASS, FN_PTR(getHostClass)},
{CC "interpreterFrameSize", CC "(" BYTECODE_FRAME ")I", FN_PTR(interpreterFrameSize)},
{CC "compileToBytecode", CC "(" OBJECT ")V", FN_PTR(compileToBytecode)},
{CC "getFlagValue", CC "(" STRING ")" OBJECT, FN_PTR(getFlagValue)},

View file

@ -1039,11 +1039,6 @@ JVM_ENTRY (void, JVM_AddReadsModule(JNIEnv *env, jobject from_module, jobject so
Modules::add_reads_module(from_module, source_module, CHECK);
JVM_END
JVM_ENTRY (void, JVM_AddModulePackage(JNIEnv *env, jobject module, const char* package))
JVMWrapper("JVM_AddModulePackage");
Modules::add_module_package(module, package, CHECK);
JVM_END
// Reflection support //////////////////////////////////////////////////////////////////////////////
JVM_ENTRY(jstring, JVM_GetClassName(JNIEnv *env, jclass cls))

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -466,14 +466,6 @@ JVM_AddModuleExportsToAll(JNIEnv *env, jobject from_module, const char* package)
JNIEXPORT void JNICALL
JVM_AddReadsModule(JNIEnv *env, jobject from_module, jobject source_module);
/*
* Add a package to a module.
* module: module that will contain the package
* package: package to add to the module
*/
JNIEXPORT void JNICALL
JVM_AddModulePackage(JNIEnv* env, jobject module, const char* package);
/*
* Reflection support functions
*/

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -1457,15 +1457,6 @@ WB_ENTRY(void, WB_AddReadsModule(JNIEnv* env, jobject o, jobject from_module, jo
Modules::add_reads_module(from_module, source_module, CHECK);
WB_END
WB_ENTRY(void, WB_AddModulePackage(JNIEnv* env, jobject o, jclass module, jstring package))
ResourceMark rm(THREAD);
char* package_name = NULL;
if (package != NULL) {
package_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
}
Modules::add_module_package(module, package_name, CHECK);
WB_END
WB_ENTRY(jobject, WB_GetModuleByPackageName(JNIEnv* env, jobject o, jobject loader, jstring package))
ResourceMark rm(THREAD);
char* package_name = NULL;
@ -1910,8 +1901,6 @@ static JNINativeMethod methods[] = {
(void*)&WB_AddModuleExports },
{CC"AddReadsModule", CC"(Ljava/lang/Object;Ljava/lang/Object;)V",
(void*)&WB_AddReadsModule },
{CC"AddModulePackage", CC"(Ljava/lang/Object;Ljava/lang/String;)V",
(void*)&WB_AddModulePackage },
{CC"GetModuleByPackageName", CC"(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;",
(void*)&WB_GetModuleByPackageName },
{CC"AddModuleExportsToAllUnnamed", CC"(Ljava/lang/Object;Ljava/lang/String;)V",

View file

@ -2861,8 +2861,8 @@ jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_m
if (res != JNI_OK) {
return res;
}
} else if (match_option(option, "--permit-illegal-access")) {
if (!create_property("jdk.module.permitIllegalAccess", "true", ExternalProperty)) {
} else if (match_option(option, "--illegal-access=", &tail)) {
if (!create_property("jdk.module.illegalAccess", tail, ExternalProperty)) {
return JNI_ENOMEM;
}
// -agentlib and -agentpath

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -296,19 +296,41 @@ void SensorInfo::trigger(int count, TRAPS) {
Klass* k = Management::sun_management_Sensor_klass(CHECK);
instanceKlassHandle sensorKlass (THREAD, k);
Handle sensor_h(THREAD, _sensor_obj);
Handle usage_h = MemoryService::create_MemoryUsage_obj(_usage, CHECK);
Symbol* trigger_method_signature;
JavaValue result(T_VOID);
JavaCallArguments args(sensor_h);
args.push_int((int) count);
Handle usage_h = MemoryService::create_MemoryUsage_obj(_usage, THREAD);
// Call Sensor::trigger(int, MemoryUsage) to send notification to listeners.
// When OOME occurs and fails to allocate MemoryUsage object, call
// Sensor::trigger(int) instead. The pending request will be processed
// but no notification will be sent.
if (HAS_PENDING_EXCEPTION) {
assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOME here");
CLEAR_PENDING_EXCEPTION;
trigger_method_signature = vmSymbols::int_void_signature();
} else {
trigger_method_signature = vmSymbols::trigger_method_signature();
args.push_oop(usage_h);
}
JavaCalls::call_virtual(&result,
sensorKlass,
vmSymbols::trigger_name(),
vmSymbols::trigger_method_signature(),
trigger_method_signature,
&args,
CHECK);
THREAD);
if (HAS_PENDING_EXCEPTION) {
// We just clear the OOM pending exception that we might have encountered
// in Java's tiggerAction(), and continue with updating the counters since
// the Java counters have been updated too.
assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOME here");
CLEAR_PENDING_EXCEPTION;
}
}
{

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -1095,8 +1095,11 @@ inline intptr_t bitfield(intptr_t x, int start_bit_no, int field_length) {
#undef min
#endif
#define max(a,b) Do_not_use_max_use_MAX2_instead
#define min(a,b) Do_not_use_min_use_MIN2_instead
// The following defines serve the purpose of preventing use of accidentally
// included min max macros from compiling, while continuing to allow innocent
// min and max identifiers in the code to compile as intended.
#define max max
#define min min
// It is necessary to use templates here. Having normal overloaded
// functions does not work because it is necessary to provide both 32-

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* 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,18 +23,31 @@
/*
* @test
* @bug 4983023
* @summary A bad superclass shouldn't throw the standard doclet into a loop
* @modules jdk.javadoc
* @bug 8181872
*
* @run main/othervm -XX:+IgnoreUnrecognizedVMOptions
* -XX:CompileThreshold=100 -XX:+TieredCompilation -XX:TieredStopAtLevel=1
* -XX:-BackgroundCompilation -XX:CompileCommand=dontinline,compiler.c1.MultiplyByMaxInt::test
* compiler.c1.MultiplyByMaxInt
* @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-BackgroundCompilation
* -XX:CompileThreshold=100 -XX:+TieredCompilation -XX:TieredStopAtLevel=3
* -XX:CompileCommand=dontinline,compiler.c1.MultiplyByMaxInt::test
* compiler.c1.MultiplyByMaxInt
*/
package compiler.c1;
public class BadSuper {
public class MultiplyByMaxInt {
static int test(int x) {
int loops = (x >>> 4) & 7;
while (loops-- > 0) {
x = (x * 2147483647) % 16807;
}
return x;
}
public static void main(String[] args) {
String srcpath = System.getProperty("test.src", ".");
if (com.sun.tools.javadoc.Main.execute(
new String[] {"-d", "doc", "-sourcepath", srcpath, "p"}) != 0)
throw new Error("Javadoc encountered warnings or errors.");
for (int i = 0; i < 20000; i++) {
test(i);
}
}
}

View file

@ -773,221 +773,221 @@ public class TestIntUnsafeCAS {
static void test_ci(int[] a) {
for (int i = 0; i < ARRLEN; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i), -1, -123);
unsafe.compareAndSetInt(a, byte_offset(i), -1, -123);
}
}
static void test_vi(int[] a, int b, int old) {
for (int i = 0; i < ARRLEN; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i), old, b);
unsafe.compareAndSetInt(a, byte_offset(i), old, b);
}
}
static void test_cp(int[] a, int[] b) {
for (int i = 0; i < ARRLEN; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i), -123, b[i]);
unsafe.compareAndSetInt(a, byte_offset(i), -123, b[i]);
}
}
static void test_2ci(int[] a, int[] b) {
for (int i = 0; i < ARRLEN; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i), 123, -123);
unsafe.compareAndSwapInt(b, byte_offset(i), 123, -103);
unsafe.compareAndSetInt(a, byte_offset(i), 123, -123);
unsafe.compareAndSetInt(b, byte_offset(i), 123, -103);
}
}
static void test_2vi(int[] a, int[] b, int c, int d) {
for (int i = 0; i < ARRLEN; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i), -123, c);
unsafe.compareAndSwapInt(b, byte_offset(i), -103, d);
unsafe.compareAndSetInt(a, byte_offset(i), -123, c);
unsafe.compareAndSetInt(b, byte_offset(i), -103, d);
}
}
static void test_ci_neg(int[] a, int old) {
for (int i = ARRLEN-1; i >= 0; i-=1) {
unsafe.compareAndSwapInt(a, byte_offset(i), old, -123);
unsafe.compareAndSetInt(a, byte_offset(i), old, -123);
}
}
static void test_vi_neg(int[] a, int b, int old) {
for (int i = ARRLEN-1; i >= 0; i-=1) {
unsafe.compareAndSwapInt(a, byte_offset(i), old, b);
unsafe.compareAndSetInt(a, byte_offset(i), old, b);
}
}
static void test_cp_neg(int[] a, int[] b) {
for (int i = ARRLEN-1; i >= 0; i-=1) {
unsafe.compareAndSwapInt(a, byte_offset(i), -123, b[i]);
unsafe.compareAndSetInt(a, byte_offset(i), -123, b[i]);
}
}
static void test_2ci_neg(int[] a, int[] b) {
for (int i = ARRLEN-1; i >= 0; i-=1) {
unsafe.compareAndSwapInt(a, byte_offset(i), 123, -123);
unsafe.compareAndSwapInt(b, byte_offset(i), 123, -103);
unsafe.compareAndSetInt(a, byte_offset(i), 123, -123);
unsafe.compareAndSetInt(b, byte_offset(i), 123, -103);
}
}
static void test_2vi_neg(int[] a, int[] b, int c, int d) {
for (int i = ARRLEN-1; i >= 0; i-=1) {
unsafe.compareAndSwapInt(a, byte_offset(i), -123, c);
unsafe.compareAndSwapInt(b, byte_offset(i), -103, d);
unsafe.compareAndSetInt(a, byte_offset(i), -123, c);
unsafe.compareAndSetInt(b, byte_offset(i), -103, d);
}
}
static void test_ci_oppos(int[] a, int old) {
int limit = ARRLEN-1;
for (int i = 0; i < ARRLEN; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(limit-i), old, -123);
unsafe.compareAndSetInt(a, byte_offset(limit-i), old, -123);
}
}
static void test_vi_oppos(int[] a, int b, int old) {
int limit = ARRLEN-1;
for (int i = limit; i >= 0; i-=1) {
unsafe.compareAndSwapInt(a, byte_offset(limit-i), old, b);
unsafe.compareAndSetInt(a, byte_offset(limit-i), old, b);
}
}
static void test_cp_oppos(int[] a, int[] b) {
int limit = ARRLEN-1;
for (int i = 0; i < ARRLEN; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i), -123, b[limit-i]);
unsafe.compareAndSetInt(a, byte_offset(i), -123, b[limit-i]);
}
}
static void test_2ci_oppos(int[] a, int[] b) {
int limit = ARRLEN-1;
for (int i = 0; i < ARRLEN; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(limit-i), 123, -123);
unsafe.compareAndSwapInt(b, byte_offset(i), 123, -103);
unsafe.compareAndSetInt(a, byte_offset(limit-i), 123, -123);
unsafe.compareAndSetInt(b, byte_offset(i), 123, -103);
}
}
static void test_2vi_oppos(int[] a, int[] b, int c, int d) {
int limit = ARRLEN-1;
for (int i = limit; i >= 0; i-=1) {
unsafe.compareAndSwapInt(a, byte_offset(i), -123, c);
unsafe.compareAndSwapInt(b, byte_offset(limit-i), -103, d);
unsafe.compareAndSetInt(a, byte_offset(i), -123, c);
unsafe.compareAndSetInt(b, byte_offset(limit-i), -103, d);
}
}
static void test_ci_off(int[] a, int old) {
for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+OFFSET), old, -123);
unsafe.compareAndSetInt(a, byte_offset(i+OFFSET), old, -123);
}
}
static void test_vi_off(int[] a, int b, int old) {
for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+OFFSET), old, b);
unsafe.compareAndSetInt(a, byte_offset(i+OFFSET), old, b);
}
}
static void test_cp_off(int[] a, int[] b) {
for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+OFFSET), -123, b[i+OFFSET]);
unsafe.compareAndSetInt(a, byte_offset(i+OFFSET), -123, b[i+OFFSET]);
}
}
static void test_2ci_off(int[] a, int[] b) {
for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+OFFSET), 123, -123);
unsafe.compareAndSwapInt(b, byte_offset(i+OFFSET), 123, -103);
unsafe.compareAndSetInt(a, byte_offset(i+OFFSET), 123, -123);
unsafe.compareAndSetInt(b, byte_offset(i+OFFSET), 123, -103);
}
}
static void test_2vi_off(int[] a, int[] b, int c, int d) {
for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+OFFSET), -123, c);
unsafe.compareAndSwapInt(b, byte_offset(i+OFFSET), -103, d);
unsafe.compareAndSetInt(a, byte_offset(i+OFFSET), -123, c);
unsafe.compareAndSetInt(b, byte_offset(i+OFFSET), -103, d);
}
}
static void test_ci_inv(int[] a, int k, int old) {
for (int i = 0; i < ARRLEN-k; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+k), old, -123);
unsafe.compareAndSetInt(a, byte_offset(i+k), old, -123);
}
}
static void test_vi_inv(int[] a, int b, int k, int old) {
for (int i = 0; i < ARRLEN-k; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+k), old, b);
unsafe.compareAndSetInt(a, byte_offset(i+k), old, b);
}
}
static void test_cp_inv(int[] a, int[] b, int k) {
for (int i = 0; i < ARRLEN-k; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+k), -123, b[i+k]);
unsafe.compareAndSetInt(a, byte_offset(i+k), -123, b[i+k]);
}
}
static void test_2ci_inv(int[] a, int[] b, int k) {
for (int i = 0; i < ARRLEN-k; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+k), 123, -123);
unsafe.compareAndSwapInt(b, byte_offset(i+k), 123, -103);
unsafe.compareAndSetInt(a, byte_offset(i+k), 123, -123);
unsafe.compareAndSetInt(b, byte_offset(i+k), 123, -103);
}
}
static void test_2vi_inv(int[] a, int[] b, int c, int d, int k) {
for (int i = 0; i < ARRLEN-k; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+k), -123, c);
unsafe.compareAndSwapInt(b, byte_offset(i+k), -103, d);
unsafe.compareAndSetInt(a, byte_offset(i+k), -123, c);
unsafe.compareAndSetInt(b, byte_offset(i+k), -103, d);
}
}
static void test_ci_scl(int[] a, int old) {
for (int i = 0; i*SCALE < ARRLEN; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i*SCALE), old, -123);
unsafe.compareAndSetInt(a, byte_offset(i*SCALE), old, -123);
}
}
static void test_vi_scl(int[] a, int b, int old) {
for (int i = 0; i*SCALE < ARRLEN; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i*SCALE), old, b);
unsafe.compareAndSetInt(a, byte_offset(i*SCALE), old, b);
}
}
static void test_cp_scl(int[] a, int[] b) {
for (int i = 0; i*SCALE < ARRLEN; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i*SCALE), -123, b[i*SCALE]);
unsafe.compareAndSetInt(a, byte_offset(i*SCALE), -123, b[i*SCALE]);
}
}
static void test_2ci_scl(int[] a, int[] b) {
for (int i = 0; i*SCALE < ARRLEN; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i*SCALE), 123, -123);
unsafe.compareAndSwapInt(b, byte_offset(i*SCALE), 123, -103);
unsafe.compareAndSetInt(a, byte_offset(i*SCALE), 123, -123);
unsafe.compareAndSetInt(b, byte_offset(i*SCALE), 123, -103);
}
}
static void test_2vi_scl(int[] a, int[] b, int c, int d) {
for (int i = 0; i*SCALE < ARRLEN; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i*SCALE), -123, c);
unsafe.compareAndSwapInt(b, byte_offset(i*SCALE), -103, d);
unsafe.compareAndSetInt(a, byte_offset(i*SCALE), -123, c);
unsafe.compareAndSetInt(b, byte_offset(i*SCALE), -103, d);
}
}
static void test_cp_alndst(int[] a, int[] b) {
for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+ALIGN_OFF), -1, b[i]);
unsafe.compareAndSetInt(a, byte_offset(i+ALIGN_OFF), -1, b[i]);
}
}
static void test_cp_alnsrc(int[] a, int[] b) {
for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
int old = unsafe.getIntVolatile(a, byte_offset(i));
unsafe.compareAndSwapInt(a, byte_offset(i), old, b[i+ALIGN_OFF]);
unsafe.compareAndSetInt(a, byte_offset(i), old, b[i+ALIGN_OFF]);
}
}
static void test_2ci_aln(int[] a, int[] b) {
for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+ALIGN_OFF), -1, -123);
unsafe.compareAndSetInt(a, byte_offset(i+ALIGN_OFF), -1, -123);
int old = unsafe.getIntVolatile(b, byte_offset(i));
unsafe.compareAndSwapInt(b, byte_offset(i), old, -103);
unsafe.compareAndSetInt(b, byte_offset(i), old, -103);
}
}
static void test_2vi_aln(int[] a, int[] b, int c, int d) {
for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
int old = unsafe.getIntVolatile(a, byte_offset(i));
unsafe.compareAndSwapInt(a, byte_offset(i), old, c);
unsafe.compareAndSetInt(a, byte_offset(i), old, c);
old = unsafe.getIntVolatile(b, byte_offset(i+ALIGN_OFF));
unsafe.compareAndSwapInt(b, byte_offset(i+ALIGN_OFF), old, d);
unsafe.compareAndSetInt(b, byte_offset(i+ALIGN_OFF), old, d);
}
}
static void test_cp_unalndst(int[] a, int[] b) {
for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+UNALIGN_OFF), -1, b[i]);
unsafe.compareAndSetInt(a, byte_offset(i+UNALIGN_OFF), -1, b[i]);
}
}
static void test_cp_unalnsrc(int[] a, int[] b) {
for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
int old = unsafe.getIntVolatile(a, byte_offset(i));
unsafe.compareAndSwapInt(a, byte_offset(i), old, b[i+UNALIGN_OFF]);
unsafe.compareAndSetInt(a, byte_offset(i), old, b[i+UNALIGN_OFF]);
}
}
static void test_2ci_unaln(int[] a, int[] b) {
for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
unsafe.compareAndSwapInt(a, byte_offset(i+UNALIGN_OFF), -1, -123);
unsafe.compareAndSetInt(a, byte_offset(i+UNALIGN_OFF), -1, -123);
int old = unsafe.getIntVolatile(b, byte_offset(i));
unsafe.compareAndSwapInt(b, byte_offset(i), old, -103);
unsafe.compareAndSetInt(b, byte_offset(i), old, -103);
}
}
static void test_2vi_unaln(int[] a, int[] b, int c, int d) {
for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
int old = unsafe.getIntVolatile(a, byte_offset(i));
unsafe.compareAndSwapInt(a, byte_offset(i), old, c);
unsafe.compareAndSetInt(a, byte_offset(i), old, c);
old = unsafe.getIntVolatile(b, byte_offset(i+UNALIGN_OFF));
unsafe.compareAndSwapInt(b, byte_offset(i+UNALIGN_OFF), old, d);
unsafe.compareAndSetInt(b, byte_offset(i+UNALIGN_OFF), old, d);
}
}

View file

@ -54,6 +54,7 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collections;
import java.util.function.Supplier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@ -142,6 +143,27 @@ public class TestResolvedJavaType extends TypeUniverse {
}
}
@Test
public void getHostClassTest() {
for (Class<?> c : classes) {
ResolvedJavaType type = metaAccess.lookupJavaType(c);
ResolvedJavaType host = type.getHostClass();
assertNull(host);
}
class LocalClass {}
Cloneable clone = new Cloneable() {};
assertNull(metaAccess.lookupJavaType(LocalClass.class).getHostClass());
assertNull(metaAccess.lookupJavaType(clone.getClass()).getHostClass());
Supplier<Runnable> lambda = () -> () -> System.out.println("run");
ResolvedJavaType lambdaType = metaAccess.lookupJavaType(lambda.getClass());
ResolvedJavaType nestedLambdaType = metaAccess.lookupJavaType(lambda.get().getClass());
assertNotNull(lambdaType.getHostClass());
assertNotNull(nestedLambdaType.getHostClass());
assertEquals(lambdaType.getHostClass(), nestedLambdaType.getHostClass());
}
@Test
public void getModifiersTest() {
for (Class<?> c : classes) {

View file

@ -64,7 +64,7 @@ public class UnsafeAccess {
static Object helperUnsafeLoadStore(Object o, boolean isObjArray) {
if (isObjArray) {
Object o1 = U.getObject(o, off);
U.compareAndSwapObject(o, off, o1, new Object());
U.compareAndSetObject(o, off, o1, new Object());
}
return o;
}

View file

@ -1,154 +0,0 @@
/*
* Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
* 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
* @modules java.base/jdk.internal.misc
* @library /test/lib ..
* @build sun.hotspot.WhiteBox
* @compile/module=java.base java/lang/ModuleHelper.java
* @run main ClassFileInstaller sun.hotspot.WhiteBox
* sun.hotspot.WhiteBox$WhiteBoxPermission
* @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI JVMAddModulePackage
*/
import static jdk.test.lib.Asserts.*;
import java.sql.Time;
public class JVMAddModulePackage {
public static void main(String args[]) throws Throwable {
MyClassLoader cl1 = new MyClassLoader();
MyClassLoader cl3 = new MyClassLoader();
Object module_one, module_two, module_three;
boolean result;
module_one = ModuleHelper.ModuleObject("module_one", cl1, new String[] { "mypackage" });
assertNotNull(module_one, "Module should not be null");
ModuleHelper.DefineModule(module_one, "9.0", "module_one/here", new String[] { "mypackage" });
module_two = ModuleHelper.ModuleObject("module_two", cl1, new String[] { "yourpackage" });
assertNotNull(module_two, "Module should not be null");
ModuleHelper.DefineModule(module_two, "9.0", "module_two/here", new String[] { "yourpackage" });
module_three = ModuleHelper.ModuleObject("module_three", cl3, new String[] { "apackage/num3" });
assertNotNull(module_three, "Module should not be null");
ModuleHelper.DefineModule(module_three, "9.0", "module_three/here", new String[] { "apackage/num3" });
// Simple call
ModuleHelper.AddModulePackage(module_one, "new_package");
// Add a package and export it
ModuleHelper.AddModulePackage(module_one, "apackage/num3");
ModuleHelper.AddModuleExportsToAll(module_one, "apackage/num3");
// Null module argument, expect an NPE
try {
ModuleHelper.AddModulePackage(null, "new_package");
throw new RuntimeException("Failed to get the expected NPE");
} catch(NullPointerException e) {
// Expected
}
// Bad module argument, expect an IAE
try {
ModuleHelper.AddModulePackage(cl1, "new_package");
throw new RuntimeException("Failed to get the expected IAE");
} catch(IllegalArgumentException e) {
// Expected
}
// Null package argument, expect an NPE
try {
ModuleHelper.AddModulePackage(module_one, null);
throw new RuntimeException("Failed to get the expected NPE");
} catch(NullPointerException e) {
// Expected
}
// Existing package, expect an ISE
try {
ModuleHelper.AddModulePackage(module_one, "yourpackage");
throw new RuntimeException("Failed to get the expected ISE");
} catch(IllegalStateException e) {
// Expected
}
// Invalid package name, expect an IAE
try {
ModuleHelper.AddModulePackage(module_one, "your.apackage");
throw new RuntimeException("Failed to get the expected IAE");
} catch(IllegalArgumentException e) {
// Expected
}
// Invalid package name, expect an IAE
try {
ModuleHelper.AddModulePackage(module_one, ";your/apackage");
throw new RuntimeException("Failed to get the expected IAE");
} catch(IllegalArgumentException e) {
// Expected
}
// Invalid package name, expect an IAE
try {
ModuleHelper.AddModulePackage(module_one, "7[743");
throw new RuntimeException("Failed to get the expected IAE");
} catch(IllegalArgumentException e) {
// Expected
}
// Empty package name, expect an IAE
try {
ModuleHelper.AddModulePackage(module_one, "");
throw new RuntimeException("Failed to get the expected IAE");
} catch(IllegalArgumentException e) {
// Expected
}
// Add package named "java" to an module defined to a class loader other than the boot or platform loader.
try {
// module_one is defined to a MyClassLoader class loader.
ModuleHelper.AddModulePackage(module_one, "java/foo");
throw new RuntimeException("Failed to get the expected IAE");
} catch(IllegalArgumentException e) {
if (!e.getMessage().contains("prohibited package name")) {
throw new RuntimeException("Failed to get expected IAE message for prohibited package name: " + e.getMessage());
}
}
// Package "javabar" should be ok
ModuleHelper.AddModulePackage(module_one, "javabar");
// Package named "java" defined to the boot class loader, should be ok
Object module_javabase = module_one.getClass().getModule();
ModuleHelper.AddModulePackage(module_javabase, "java/foo");
// Package named "java" defined to the platform class loader, should be ok
// The module java.sql is defined to the platform class loader.
java.sql.Time jst = new java.sql.Time(45000); // milliseconds
Object module_javasql = jst.getClass().getModule();
ModuleHelper.AddModulePackage(module_javasql, "java/foo");
}
static class MyClassLoader extends ClassLoader { }
}

View file

@ -49,12 +49,6 @@ public class ModuleHelper {
java.lang.ModuleHelper.addReadsNoSync((Module)from, (Module)to);
}
public static void AddModulePackage(Object m, String pkg) throws Throwable {
WhiteBox wb = WhiteBox.getWhiteBox();
wb.AddModulePackage(m, pkg);
java.lang.ModuleHelper.addPackageNoSync((Module)m, pkg);
}
public static Module GetModuleByPackageName(Object ldr, String pkg) throws Throwable {
WhiteBox wb = WhiteBox.getWhiteBox();
return (Module)wb.GetModuleByPackageName(ldr, pkg);

View file

@ -63,11 +63,4 @@ public final class ModuleHelper {
}
}
/**
* Adds a package to a module without notifying the VM.
*/
public static void addPackageNoSync(Module m, String pkg) {
m.implAddPackageNoSync(pkg);
}
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
* 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 MyPackage;
/**
* @test
* @summary Verifies the JVMTI GetNamedModule API
* @modules jdk.jdi
* @compile GetNamedModuleTest.java
* @run main/othervm/native -agentlib:GetNamedModuleTest MyPackage.GetNamedModuleTest
*/

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* 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,40 +21,37 @@
* questions.
*/
package pkg1;
import java.io.*;
package MyPackage;
/**
* A test class where the outer class is package private and the inner class is private
* and a nested inner class is protected.
*
* @author Bhavesh Patel
* @test
* @summary Verifies the JVMTI IsModifiableModule API
* @modules jdk.jdi
* @compile IsModifiableModuleTest.java
* @run main/othervm/native -agentlib:IsModifiableModuleTest MyPackage.IsModifiableModuleTest
*/
class NestedInnerClass {
import java.io.PrintStream;
private static class InnerClass {
public class IsModifiableModuleTest {
protected static class ProNestedInnerClass implements java.io.Serializable {
public final int SERIALIZABLE_CONSTANT = 1;
/**
* @param s ObjectInputStream.
* @throws IOException when there is an I/O error.
* @serial
*/
private void readObject(ObjectInputStream s) throws IOException {
static {
try {
System.loadLibrary("IsModifiableModuleTest");
} catch (UnsatisfiedLinkError ule) {
System.err.println("Could not load IsModifiableModuleTest library");
System.err.println("java.library.path: "
+ System.getProperty("java.library.path"));
throw ule;
}
}
/**
* @param s ObjectOutputStream.
* @throws IOException when there is an I/O error.
* @serial
*/
private void writeObject(ObjectOutputStream s) throws IOException {
}
native static int check();
public static void main(String args[]) {
int status = check();
if (status != 0) {
throw new RuntimeException("Non-zero status returned from the agent: " + status);
}
}
}

View file

@ -0,0 +1,215 @@
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* 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.
*/
#include <stdio.h>
#include <string.h>
#include "jvmti.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifndef JNI_ENV_ARG
#ifdef __cplusplus
#define JNI_ENV_ARG(x, y) y
#define JNI_ENV_PTR(x) x
#else
#define JNI_ENV_ARG(x,y) x, y
#define JNI_ENV_PTR(x) (*x)
#endif
#endif
#define TranslateError(err) "JVMTI error"
#define PASSED 0
#define FAILED 2
static const char *EXC_CNAME = "java/lang/AssertionError";
static jvmtiEnv *jvmti = NULL;
static jint result = PASSED;
static jboolean printdump = JNI_FALSE;
static jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved);
JNIEXPORT
jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {
return Agent_Initialize(jvm, options, reserved);
}
JNIEXPORT
jint JNICALL Agent_OnAttach(JavaVM *jvm, char *options, void *reserved) {
return Agent_Initialize(jvm, options, reserved);
}
JNIEXPORT
jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) {
return JNI_VERSION_1_8;
}
static
jint Agent_Initialize(JavaVM *jvm, char *options, void *reserved) {
jint res;
if (options != NULL && strcmp(options, "printdump") == 0) {
printdump = JNI_TRUE;
}
res = JNI_ENV_PTR(jvm)->GetEnv(JNI_ENV_ARG(jvm, (void **) &jvmti),
JVMTI_VERSION_9);
if (res != JNI_OK || jvmti == NULL) {
printf(" Error: wrong result of a valid call to GetEnv!\n");
return JNI_ERR;
}
return JNI_OK;
}
static
jclass find_class(JNIEnv *env, const char* cname) {
jclass cls = JNI_ENV_PTR(env)->FindClass(JNI_ENV_ARG(env, cname));
if (cls == NULL) {
printf("find_class: Error: FindClass(env, \"%s\") returned NULL\n", cname);
}
return cls;
}
static
jint throw_exc(JNIEnv *env, char *msg) {
jclass exc_class = find_class(env, EXC_CNAME);
if (exc_class == NULL) {
printf("throw_exc: Error in find_class(env, \"%s\")\n", EXC_CNAME);
return -1;
}
return JNI_ENV_PTR(env)->ThrowNew(JNI_ENV_ARG(env, exc_class), msg);
}
static jobject get_module_by_class_name(JNIEnv *env, const char* cname) {
jobject module = NULL;
jclass cls = find_class(env, cname);
printf(">>> getting module by class name: \"%s\"\n", cname);
if (cls == NULL) {
printf("get_module_by_class_name: Error in find_class(env, \"%s\")\n", cname);
return NULL;
}
module = JNI_ENV_PTR(env)->GetModule(JNI_ENV_ARG(env, cls));
if (module == NULL) {
printf("get_module_by_class_name: Error in GetModule for class \"%s\"\n", cname);
}
return module;
}
static
jint check_is_modifiable_error_codes(jobject module, jobject not_a_module) {
jvmtiError err = JVMTI_ERROR_NONE;
jboolean is_modifiable = JNI_FALSE;
printf(">>> passing a bad module argument to JVMTI IsModifiableModule\n");
err = (*jvmti)->IsModifiableModule(jvmti, not_a_module, &is_modifiable);
if (err != JVMTI_ERROR_INVALID_MODULE) {
printf(" Error #EC0: Did not get expected INVALID_MODULE error code from"
" IsModifiableModule: %s (%d)\n", TranslateError(err), err);
return FAILED;
}
printf(">>> passing NULL module argument to JVMTI IsModifiableModule\n");
err = (*jvmti)->IsModifiableModule(jvmti, NULL, &is_modifiable);
if (err != JVMTI_ERROR_NULL_POINTER) {
printf(" Error #EC1: Did not get expected NULL_POINTER error code from"
" IsModifiableModule: %s (%d)\n", TranslateError(err), err);
return FAILED;
}
printf(">>> passing NULL status pointer to JVMTI IsModifiableModule\n");
err = (*jvmti)->IsModifiableModule(jvmti, module, NULL);
if (err != JVMTI_ERROR_NULL_POINTER) {
printf(" Error #EC2: Did not get expected NULL_POINTER error code from"
" IsModifiableModule: %s (%d)\n", TranslateError(err), err);
return FAILED;
}
return PASSED;
}
static
jint check_is_modifiable(jobject module) {
jvmtiError err = JVMTI_ERROR_NONE;
jboolean is_modifiable = JNI_FALSE;
printf(">>> checking module %p is modifiable\n", module);
err = (*jvmti)->IsModifiableModule(jvmti, module, &is_modifiable);
if (err != JVMTI_ERROR_NONE) {
printf(" Error in IsModifiableModule for module %p: %s (%d)\n",
module, TranslateError(err), err);
return FAILED;
}
if (is_modifiable == JNI_FALSE) {
printf(" unexpected non-modifiable status for module: %p\n", module);
return FAILED;
}
return PASSED;
}
JNIEXPORT jint JNICALL
Java_MyPackage_IsModifiableModuleTest_check(JNIEnv *env, jclass cls) {
jobject module = NULL;
if (jvmti == NULL) {
throw_exc(env, "JVMTI client was not properly loaded!\n");
return FAILED;
}
printf("\n*** Testing IsModifiableModule ***\n\n");
if (check_is_modifiable_error_codes(module, cls) == FAILED) {
throw_exc(env, "check #MM0: failed to return expected error code from "
"a bad call to JVMTI IsModifiableModule");
return FAILED;
}
module = get_module_by_class_name(env, "java/lang/Class");
if (check_is_modifiable(module) == FAILED) {
throw_exc(env, "check #MM1: failed to return modifiable module status");
return FAILED;
}
module = get_module_by_class_name(env, "com/sun/jdi/VirtualMachine");
if (check_is_modifiable(module) == FAILED) {
throw_exc(env, "check #MM2: failed to return modifiable module status");
return FAILED;
}
module = get_module_by_class_name(env, "MyPackage/IsModifiableModuleTest");
if (check_is_modifiable(module) == FAILED) {
throw_exc(env, "check #MM3: failed to return modifiable module status");
return FAILED;
}
return PASSED;
}
#ifdef __cplusplus
}
#endif

View file

@ -51,8 +51,7 @@ public class TestMutuallyExclusivePlatformPredicates {
VM_TYPE("isClient", "isServer", "isGraal", "isMinimal", "isZero", "isEmbedded"),
MODE("isInt", "isMixed", "isComp"),
IGNORED("isEmulatedClient", "isDebugBuild", "isFastDebugBuild", "isSlowDebugBuild",
"shouldSAAttach", "canPtraceAttachLinux", "canAttachOSX",
"isTieredSupported");
"shouldSAAttach", "isTieredSupported");
public final List<String> methodNames;

View file

@ -428,3 +428,7 @@ bd4b2c8835f35760a51c1475b03a16cc20c62973 jdk-10+10
eedb6e54c8bd6197ecba5fc0d8568bac8ae852dd jdk-9+172
95bab8bf9201ae8bfdf28e164bf33b78e49477e7 jdk-10+11
9788347e0629d0cb3a0e55a903494ff741d4fa15 jdk-9+173
b9c0b105002272d7414c8b34af9aded151f9cad6 jdk-9+174
ff293e39e83366c40a5687dacd1ccb2305ed2c1e jdk-10+12
736412a8dccee9d439044e6b1af2e7470d0a3563 jdk-9+175
5d374af9e78d02976e0e7f8dc2706f91a020f025 jdk-10+13

View file

@ -1 +1,2 @@
project=jdk10
bugids=dup

View file

@ -1,596 +0,0 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xerces.internal.util;
import java.io.IOException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.ext.EntityResolver2;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import javax.xml.parsers.SAXParserFactory;
import com.sun.org.apache.xerces.internal.dom.DOMInputImpl;
import com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl;
import com.sun.org.apache.xerces.internal.xni.XNIException;
import com.sun.org.apache.xerces.internal.xni.XMLResourceIdentifier;
import com.sun.org.apache.xerces.internal.xni.parser.XMLEntityResolver;
import com.sun.org.apache.xerces.internal.xni.parser.XMLInputSource;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import com.sun.org.apache.xml.internal.resolver.CatalogManager;
import com.sun.org.apache.xml.internal.resolver.readers.OASISXMLCatalogReader;
import com.sun.org.apache.xml.internal.resolver.readers.SAXCatalogReader;
/**
* <p>The catalog resolver handles the resolution of external
* identifiers and URI references through XML catalogs. This
* component supports XML catalogs defined by the
* <a href="http://www.oasis-open.org/committees/entity/spec.html">
* OASIS XML Catalogs Specification</a>. It encapsulates the
* <a href="http://xml.apache.org/commons/">XML Commons</a> resolver.
* An instance of this class may be registered on the parser
* as a SAX entity resolver, as a DOM LSResourceResolver or
* as an XNI entity resolver by setting the property
* (http://apache.org/xml/properties/internal/entity-resolver).</p>
*
* <p>It is intended that this class may be used standalone to perform
* catalog resolution outside of a parsing context. It may be shared
* between several parsers and the application.</p>
*
* @deprecated This class and the JDK internal Catalog API in package
* {@code com.sun.org.apache.xml.internal.resolver}
* is encapsulated in JDK 9. The entire implementation under the package is now
* deprecated and subject to removal in a future release. Users of the API should
* migrate to the {@linkplain javax.xml.catalog new public API}.
* <p>
* The new Catalog API is supported throughout the JDK XML Processors, which allows
* the use of Catalog by simply setting a path to a Catalog file as a property.
*
* @author Michael Glavassevich, IBM
*
*/
@Deprecated(since="9", forRemoval=true)
public class XMLCatalogResolver
implements XMLEntityResolver, EntityResolver2, LSResourceResolver {
/** Internal catalog manager for Apache catalogs. **/
private CatalogManager fResolverCatalogManager = null;
/** Internal catalog structure. **/
private Catalog fCatalog = null;
/** An array of catalog URIs. **/
private String [] fCatalogsList = null;
/**
* Indicates whether the list of catalogs has
* changed since it was processed.
*/
private boolean fCatalogsChanged = true;
/** Application specified prefer public setting. **/
private boolean fPreferPublic = true;
/**
* Indicates whether the application desires that
* the parser or some other component performing catalog
* resolution should use the literal system identifier
* instead of the expanded system identifier.
*/
private boolean fUseLiteralSystemId = true;
/**
* <p>Constructs a catalog resolver with a default configuration.</p>
*/
public XMLCatalogResolver () {
this(null, true);
}
/**
* <p>Constructs a catalog resolver with the given
* list of entry files.</p>
*
* @param catalogs an ordered array list of absolute URIs
*/
public XMLCatalogResolver (String [] catalogs) {
this(catalogs, true);
}
/**
* <p>Constructs a catalog resolver with the given
* list of entry files and the preference for whether
* system or public matches are preferred.</p>
*
* @param catalogs an ordered array list of absolute URIs
* @param preferPublic the prefer public setting
*/
public XMLCatalogResolver (String [] catalogs, boolean preferPublic) {
init(catalogs, preferPublic);
}
/**
* <p>Returns the initial list of catalog entry files.</p>
*
* @return the initial list of catalog entry files
*/
public final synchronized String [] getCatalogList () {
return (fCatalogsList != null)
? (String[]) fCatalogsList.clone() : null;
}
/**
* <p>Sets the initial list of catalog entry files.
* If there were any catalog mappings cached from
* the previous list they will be replaced by catalog
* mappings from the new list the next time the catalog
* is queried.</p>
*
* @param catalogs an ordered array list of absolute URIs
*/
public final synchronized void setCatalogList (String [] catalogs) {
fCatalogsChanged = true;
fCatalogsList = (catalogs != null)
? (String[]) catalogs.clone() : null;
}
/**
* <p>Forces the cache of catalog mappings to be cleared.</p>
*/
public final synchronized void clear () {
fCatalog = null;
}
/**
* <p>Returns the preference for whether system or public
* matches are preferred. This is used in the absence
* of any occurence of the <code>prefer</code> attribute
* on the <code>catalog</code> entry of a catalog. If this
* property has not yet been explicitly set its value is
* <code>true</code>.</p>
*
* @return the prefer public setting
*/
public final boolean getPreferPublic () {
return fPreferPublic;
}
/**
* <p>Sets the preference for whether system or public
* matches are preferred. This is used in the absence
* of any occurence of the <code>prefer</code> attribute
* on the <code>catalog</code> entry of a catalog.</p>
*
* @param preferPublic the prefer public setting
*/
public final void setPreferPublic (boolean preferPublic) {
fPreferPublic = preferPublic;
fResolverCatalogManager.setPreferPublic(preferPublic);
}
/**
* <p>Returns the preference for whether the literal system
* identifier should be used when resolving system
* identifiers when both it and the expanded system
* identifier are available. If this property has not yet
* been explicitly set its value is <code>true</code>.</p>
*
* @return the preference for using literal system identifers
* for catalog resolution
*
* @see #setUseLiteralSystemId
*/
public final boolean getUseLiteralSystemId () {
return fUseLiteralSystemId;
}
/**
* <p>Sets the preference for whether the literal system
* identifier should be used when resolving system
* identifiers when both it and the expanded system
* identifier are available.</p>
*
* <p>The literal system identifier is the URI as it was
* provided before absolutization. It may be embedded within
* an entity. It may be provided externally or it may be the
* result of redirection. For example, redirection may
* have come from the protocol level through HTTP or from
* an application's entity resolver.</p>
*
* <p>The expanded system identifier is an absolute URI
* which is the result of resolving the literal system
* identifier against a base URI.</p>
*
* @param useLiteralSystemId the preference for using
* literal system identifers for catalog resolution
*/
public final void setUseLiteralSystemId (boolean useLiteralSystemId) {
fUseLiteralSystemId = useLiteralSystemId;
}
/**
* <p>Resolves an external entity. If the entity cannot be
* resolved, this method should return <code>null</code>. This
* method returns an input source if an entry was found in the
* catalog for the given external identifier. It should be
* overrided if other behaviour is required.</p>
*
* @param publicId the public identifier, or <code>null</code> if none was supplied
* @param systemId the system identifier
*
* @throws SAXException any SAX exception, possibly wrapping another exception
* @throws IOException thrown if some i/o error occurs
*/
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
String resolvedId = null;
if (publicId != null && systemId != null) {
resolvedId = resolvePublic(publicId, systemId);
}
else if (systemId != null) {
resolvedId = resolveSystem(systemId);
}
if (resolvedId != null) {
InputSource source = new InputSource(resolvedId);
source.setPublicId(publicId);
return source;
}
return null;
}
/**
* <p>Resolves an external entity. If the entity cannot be
* resolved, this method should return <code>null</code>. This
* method returns an input source if an entry was found in the
* catalog for the given external identifier. It should be
* overrided if other behaviour is required.</p>
*
* @param name the identifier of the external entity
* @param publicId the public identifier, or <code>null</code> if none was supplied
* @param baseURI the URI with respect to which relative systemIDs are interpreted.
* @param systemId the system identifier
*
* @throws SAXException any SAX exception, possibly wrapping another exception
* @throws IOException thrown if some i/o error occurs
*/
public InputSource resolveEntity(String name, String publicId,
String baseURI, String systemId) throws SAXException, IOException {
String resolvedId = null;
if (!getUseLiteralSystemId() && baseURI != null) {
// Attempt to resolve the system identifier against the base URI.
try {
URI uri = new URI(new URI(baseURI), systemId);
systemId = uri.toString();
}
// Ignore the exception. Fallback to the literal system identifier.
catch (URI.MalformedURIException ex) {}
}
if (publicId != null && systemId != null) {
resolvedId = resolvePublic(publicId, systemId);
}
else if (systemId != null) {
resolvedId = resolveSystem(systemId);
}
if (resolvedId != null) {
InputSource source = new InputSource(resolvedId);
source.setPublicId(publicId);
return source;
}
return null;
}
/**
* <p>Locates an external subset for documents which do not explicitly
* provide one. This method always returns <code>null</code>. It
* should be overrided if other behaviour is required.</p>
*
* @param name the identifier of the document root element
* @param baseURI the document's base URI
*
* @throws SAXException any SAX exception, possibly wrapping another exception
* @throws IOException thrown if some i/o error occurs
*/
public InputSource getExternalSubset(String name, String baseURI)
throws SAXException, IOException {
return null;
}
/**
* <p>Resolves a resource using the catalog. This method interprets that
* the namespace URI corresponds to uri entries in the catalog.
* Where both a namespace and an external identifier exist, the namespace
* takes precedence.</p>
*
* @param type the type of the resource being resolved
* @param namespaceURI the namespace of the resource being resolved,
* or <code>null</code> if none was supplied
* @param publicId the public identifier of the resource being resolved,
* or <code>null</code> if none was supplied
* @param systemId the system identifier of the resource being resolved,
* or <code>null</code> if none was supplied
* @param baseURI the absolute base URI of the resource being parsed,
* or <code>null</code> if there is no base URI
*/
public LSInput resolveResource(String type, String namespaceURI,
String publicId, String systemId, String baseURI) {
String resolvedId = null;
try {
// The namespace is useful for resolving namespace aware
// grammars such as XML schema. Let it take precedence over
// the external identifier if one exists.
if (namespaceURI != null) {
resolvedId = resolveURI(namespaceURI);
}
if (!getUseLiteralSystemId() && baseURI != null) {
// Attempt to resolve the system identifier against the base URI.
try {
URI uri = new URI(new URI(baseURI), systemId);
systemId = uri.toString();
}
// Ignore the exception. Fallback to the literal system identifier.
catch (URI.MalformedURIException ex) {}
}
// Resolve against an external identifier if one exists. This
// is useful for resolving DTD external subsets and other
// external entities. For XML schemas if there was no namespace
// mapping we might be able to resolve a system identifier
// specified as a location hint.
if (resolvedId == null) {
if (publicId != null && systemId != null) {
resolvedId = resolvePublic(publicId, systemId);
}
else if (systemId != null) {
resolvedId = resolveSystem(systemId);
}
}
}
// Ignore IOException. It cannot be thrown from this method.
catch (IOException ex) {}
if (resolvedId != null) {
return new DOMInputImpl(publicId, resolvedId, baseURI);
}
return null;
}
/**
* <p>Resolves an external entity. If the entity cannot be
* resolved, this method should return <code>null</code>. This
* method only calls <code>resolveIdentifier</code> and returns
* an input source if an entry was found in the catalog. It
* should be overrided if other behaviour is required.</p>
*
* @param resourceIdentifier location of the XML resource to resolve
*
* @throws XNIException thrown on general error
* @throws IOException thrown if some i/o error occurs
*/
public XMLInputSource resolveEntity(XMLResourceIdentifier resourceIdentifier)
throws XNIException, IOException {
String resolvedId = resolveIdentifier(resourceIdentifier);
if (resolvedId != null) {
return new XMLInputSource(resourceIdentifier.getPublicId(),
resolvedId, resourceIdentifier.getBaseSystemId(), false);
}
return null;
}
/**
* <p>Resolves an identifier using the catalog. This method interprets that
* the namespace of the identifier corresponds to uri entries in the catalog.
* Where both a namespace and an external identifier exist, the namespace
* takes precedence.</p>
*
* @param resourceIdentifier the identifier to resolve
*
* @throws XNIException thrown on general error
* @throws IOException thrown if some i/o error occurs
*/
public String resolveIdentifier(XMLResourceIdentifier resourceIdentifier)
throws IOException, XNIException {
String resolvedId = null;
// The namespace is useful for resolving namespace aware
// grammars such as XML schema. Let it take precedence over
// the external identifier if one exists.
String namespace = resourceIdentifier.getNamespace();
if (namespace != null) {
resolvedId = resolveURI(namespace);
}
// Resolve against an external identifier if one exists. This
// is useful for resolving DTD external subsets and other
// external entities. For XML schemas if there was no namespace
// mapping we might be able to resolve a system identifier
// specified as a location hint.
if (resolvedId == null) {
String publicId = resourceIdentifier.getPublicId();
String systemId = getUseLiteralSystemId()
? resourceIdentifier.getLiteralSystemId()
: resourceIdentifier.getExpandedSystemId();
if (publicId != null && systemId != null) {
resolvedId = resolvePublic(publicId, systemId);
}
else if (systemId != null) {
resolvedId = resolveSystem(systemId);
}
}
return resolvedId;
}
/**
* <p>Returns the URI mapping in the catalog for the given
* external identifier or <code>null</code> if no mapping
* exists. If the system identifier is an URN in the
* <code>publicid</code> namespace it is converted into
* a public identifier by URN "unwrapping" as specified
* in the XML Catalogs specification.</p>
*
* @param systemId the system identifier to locate in the catalog
*
* @return the mapped URI or <code>null</code> if no mapping
* was found in the catalog
*
* @throws IOException if an i/o error occurred while reading
* the catalog
*/
public final synchronized String resolveSystem (String systemId)
throws IOException {
if (fCatalogsChanged) {
parseCatalogs();
fCatalogsChanged = false;
}
return (fCatalog != null)
? fCatalog.resolveSystem(systemId) : null;
}
/**
* <p>Returns the URI mapping in the catalog for the given
* external identifier or <code>null</code> if no mapping
* exists. Public identifiers are normalized before
* comparison.</p>
*
* @param publicId the public identifier to locate in the catalog
* @param systemId the system identifier to locate in the catalog
*
* @return the mapped URI or <code>null</code> if no mapping
* was found in the catalog
*
* @throws IOException if an i/o error occurred while reading
* the catalog
*/
public final synchronized String resolvePublic (String publicId, String systemId)
throws IOException {
if (fCatalogsChanged) {
parseCatalogs();
fCatalogsChanged = false;
}
return (fCatalog != null)
? fCatalog.resolvePublic(publicId, systemId) : null;
}
/**
* <p>Returns the URI mapping in the catalog for the given URI
* reference or <code>null</code> if no mapping exists.
* URI comparison is case sensitive. If the URI reference
* is an URN in the <code>publicid</code> namespace
* it is converted into a public identifier by URN "unwrapping"
* as specified in the XML Catalogs specification and then
* resolution is performed following the semantics of
* external identifier resolution.</p>
*
* @param uri the URI to locate in the catalog
*
* @return the mapped URI or <code>null</code> if no mapping
* was found in the catalog
*
* @throws IOException if an i/o error occurred while reading
* the catalog
*/
public final synchronized String resolveURI (String uri)
throws IOException {
if (fCatalogsChanged) {
parseCatalogs();
fCatalogsChanged = false;
}
return (fCatalog != null)
? fCatalog.resolveURI(uri) : null;
}
/**
* Initialization. Create a CatalogManager and set all
* the properties upfront. This prevents JVM wide system properties
* or a property file somewhere in the environment from affecting
* the behaviour of this catalog resolver.
*/
private void init (String [] catalogs, boolean preferPublic) {
fCatalogsList = (catalogs != null) ? (String[]) catalogs.clone() : null;
fPreferPublic = preferPublic;
fResolverCatalogManager = new CatalogManager();
fResolverCatalogManager.setAllowOasisXMLCatalogPI(false);
fResolverCatalogManager.setCatalogClassName("com.sun.org.apache.xml.internal.resolver.Catalog");
fResolverCatalogManager.setCatalogFiles("");
fResolverCatalogManager.setIgnoreMissingProperties(true);
fResolverCatalogManager.setPreferPublic(fPreferPublic);
fResolverCatalogManager.setRelativeCatalogs(false);
fResolverCatalogManager.setUseStaticCatalog(false);
fResolverCatalogManager.setVerbosity(0);
}
/**
* Instruct the <code>Catalog</code> to parse each of the
* catalogs in the list. Only the first catalog will actually be
* parsed immediately. The others will be queued and read if
* they are needed later.
*/
private void parseCatalogs () throws IOException {
if (fCatalogsList != null) {
fCatalog = new Catalog(fResolverCatalogManager);
attachReaderToCatalog(fCatalog);
for (int i = 0; i < fCatalogsList.length; ++i) {
String catalog = fCatalogsList[i];
if (catalog != null && catalog.length() > 0) {
fCatalog.parseCatalog(catalog);
}
}
}
else {
fCatalog = null;
}
}
/**
* Attaches the reader to the catalog.
*/
private void attachReaderToCatalog (Catalog catalog) {
SAXParserFactory spf = new SAXParserFactoryImpl();
spf.setNamespaceAware(true);
spf.setValidating(false);
SAXCatalogReader saxReader = new SAXCatalogReader(spf);
saxReader.setCatalogParser(OASISXMLCatalogReader.namespaceName, "catalog",
"com.sun.org.apache.xml.internal.resolver.readers.OASISXMLCatalogReader");
catalog.addReader("application/xml", saxReader);
}
}

View file

@ -1,251 +0,0 @@
/*
* Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Represents a Catalog entry.
*
* <p>Instances of this class represent individual entries
* in a Catalog.</p>
*
* <p>Each catalog entry has a unique name and is associated with
* an arbitrary number of arguments (all strings). For example, the
* TR9401 catalog entry "PUBLIC" has two arguments, a public identifier
* and a system identifier. Each entry has a unique numeric type,
* assigned automatically when the entry type is created.</p>
*
* <p>The number and type of catalog entries is maintained
* <em>statically</em>. Catalog classes, or their subclasses, can add
* new entry types, but all Catalog objects share the same global pool
* of types.</p>
*
* <p>Initially there are no valid entries.</p>
*
* @see Catalog
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public class CatalogEntry {
/** The nextEntry is the ordinal number of the next entry type. */
static AtomicInteger nextEntry = new AtomicInteger(0);
/**
* The entryTypes vector maps catalog entry names
* (e.g., 'BASE' or 'SYSTEM') to their type (1, 2, etc.).
* Names are case sensitive.
*/
static final Map<String, Integer> entryTypes = new ConcurrentHashMap<>();
/** The entryTypes vector maps catalog entry types to the
number of arguments they're required to have. */
static final Vector entryArgs = new Vector();
/**
* Adds a new catalog entry type.
*
* @param name The name of the catalog entry type. This must be
* unique among all types and is case-sensitive. (Adding a duplicate
* name effectively replaces the old type with the new type.)
* @param numArgs The number of arguments that this entry type
* is required to have. There is no provision for variable numbers
* of arguments.
* @return The type for the new entry.
*/
static int addEntryType(String name, int numArgs) {
final int index = nextEntry.getAndIncrement();
entryTypes.put(name, index);
entryArgs.add(index, numArgs);
return index;
}
/**
* Lookup an entry type
*
* @param name The name of the catalog entry type.
* @return The type of the catalog entry with the specified name.
* @throws InvalidCatalogEntryTypeException if no entry has the
* specified name.
*/
public static int getEntryType(String name)
throws CatalogException {
if (!entryTypes.containsKey(name)) {
throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE);
}
Integer iType = entryTypes.get(name);
if (iType == null) {
throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE);
}
return iType;
}
/**
* Find out how many arguments an entry is required to have.
*
* @param name The name of the catalog entry type.
* @return The number of arguments that entry type is required to have.
* @throws InvalidCatalogEntryTypeException if no entry has the
* specified name.
*/
public static int getEntryArgCount(String name)
throws CatalogException {
return getEntryArgCount(getEntryType(name));
}
/**
* Find out how many arguments an entry is required to have.
*
* @param type A valid catalog entry type.
* @return The number of arguments that entry type is required to have.
* @throws InvalidCatalogEntryTypeException if the type is invalid.
*/
public static int getEntryArgCount(int type)
throws CatalogException {
try {
Integer iArgs = (Integer) entryArgs.get(type);
return iArgs.intValue();
} catch (ArrayIndexOutOfBoundsException e) {
throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE);
}
}
/** The entry type of this entry */
protected int entryType = 0;
/** The arguments associated with this entry */
protected Vector args = null;
/**
* Null constructor; something for subclasses to call.
*/
public CatalogEntry() {}
/**
* Construct a catalog entry of the specified type.
*
* @param name The name of the entry type
* @param args A String Vector of arguments
* @throws InvalidCatalogEntryTypeException if no such entry type
* exists.
* @throws InvalidCatalogEntryException if the wrong number of arguments
* is passed.
*/
public CatalogEntry(String name, Vector args)
throws CatalogException {
Integer iType = entryTypes.get(name);
if (iType == null) {
throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE);
}
int type = iType;
try {
Integer iArgs = (Integer) entryArgs.get(type);
if (iArgs.intValue() != args.size()) {
throw new CatalogException(CatalogException.INVALID_ENTRY);
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE);
}
entryType = type;
this.args = args;
}
/**
* Construct a catalog entry of the specified type.
*
* @param type The entry type
* @param args A String Vector of arguments
* @throws InvalidCatalogEntryTypeException if no such entry type
* exists.
* @throws InvalidCatalogEntryException if the wrong number of arguments
* is passed.
*/
public CatalogEntry(int type, Vector args)
throws CatalogException {
try {
Integer iArgs = (Integer) entryArgs.get(type);
if (iArgs.intValue() != args.size()) {
throw new CatalogException(CatalogException.INVALID_ENTRY);
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new CatalogException(CatalogException.INVALID_ENTRY_TYPE);
}
entryType = type;
this.args = args;
}
/**
* Get the entry type.
*
* @return The entry type of the CatalogEntry
*/
public int getEntryType() {
return entryType;
}
/**
* Get an entry argument.
*
* @param argNum The argument number (arguments are numbered from 0).
* @return The specified argument or null if an invalid argNum is
* provided.
*/
public String getEntryArg(int argNum) {
try {
String arg = (String) args.get(argNum);
return arg;
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
}
/**
* Set an entry argument.
*
* <p>Catalogs sometimes need to adjust the catlog entry parameters,
* for example to make a relative URI absolute with respect to the
* current base URI. But in general, this function should only be
* called shortly after object creation to do some sort of cleanup.
* Catalog entries should not mutate over time.</p>
*
* @param argNum The argument number (arguments are numbered from 0).
* @throws ArrayIndexOutOfBoundsException if an invalid argument
* number is provided.
*/
public void setEntryArg(int argNum, String newspec)
throws ArrayIndexOutOfBoundsException {
args.set(argNum, newspec);
}
}

View file

@ -1,165 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver;
/**
* Signal Catalog exception.
*
* <p>This exception is thrown if an error occurs loading a
* catalog file.</p>
*
* @see Catalog
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public class CatalogException extends Exception {
private static final long serialVersionUID = 4007157171817798450L;
/** A wrapper around another exception */
public static final int WRAPPER = 1;
/** An invalid entry */
public static final int INVALID_ENTRY = 2;
/** An invalid entry type */
public static final int INVALID_ENTRY_TYPE = 3;
/** Could not instantiate an XML parser */
public static final int NO_XML_PARSER = 4;
/** Unknown XML format */
public static final int UNKNOWN_FORMAT = 5;
/** Unparseable XML catalog (not XML)*/
public static final int UNPARSEABLE = 6;
/** XML but parse failed */
public static final int PARSE_FAILED = 7;
/** Text catalog ended in mid-comment */
public static final int UNENDED_COMMENT = 8;
/**
* The embedded exception if tunnelling, or null.
*/
private final Exception exception;
private final int exceptionType;
/**
* Create a new CatalogException.
*
* @param type The exception type
* @param message The error or warning message.
*/
public CatalogException (int type, String message) {
super(message);
this.exceptionType = type;
this.exception = null;
}
/**
* Create a new CatalogException.
*
* @param type The exception type
*/
public CatalogException (int type) {
super("Catalog Exception " + type);
this.exceptionType = type;
this.exception = null;
}
/**
* Create a new CatalogException wrapping an existing exception.
*
* <p>The existing exception will be embedded in the new
* one, and its message will become the default message for
* the CatalogException.</p>
*
* @param e The exception to be wrapped in a CatalogException.
*/
public CatalogException (Exception e) {
super();
this.exceptionType = WRAPPER;
this.exception = e;
}
/**
* Create a new CatalogException from an existing exception.
*
* <p>The existing exception will be embedded in the new
* one, but the new exception will have its own message.</p>
*
* @param message The detail message.
* @param e The exception to be wrapped in a CatalogException.
*/
public CatalogException (String message, Exception e) {
super(message);
this.exceptionType = WRAPPER;
this.exception = e;
}
/**
* Return a detail message for this exception.
*
* <p>If there is an embedded exception, and if the CatalogException
* has no detail message of its own, this method will return
* the detail message from the embedded exception.</p>
*
* @return The error or warning message.
*/
public String getMessage ()
{
String message = super.getMessage();
if (message == null && exception != null) {
return exception.getMessage();
} else {
return message;
}
}
/**
* Return the embedded exception, if any.
*
* @return The embedded exception, or null if there is none.
*/
public Exception getException ()
{
return exception;
}
/**
* Return the exception type
*
* @return The exception type
*/
public int getExceptionType ()
{
return exceptionType;
}
/**
* Override toString to pick up any embedded exception.
*
* @return A string representation of this exception.
*/
public String toString ()
{
if (exception != null) {
return exception.toString();
} else {
return super.toString();
}
}
}

View file

@ -1,870 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver;
import com.sun.org.apache.xerces.internal.utils.SecuritySupport;
import com.sun.org.apache.xml.internal.resolver.helpers.BootstrapResolver;
import com.sun.org.apache.xml.internal.resolver.helpers.Debug;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import java.util.Vector;
import sun.reflect.misc.ReflectUtil;
/**
* CatalogManager provides an interface to the catalog properties.
*
* <p>Properties can come from two places: from system properties or
* from a <i>CatalogManager.properties</i> file. This class provides a transparent
* interface to both, with system properties preferred over property file values.</p>
*
* <p>The following table summarizes the properties:</p>
*
* <table border="1">
* <thead>
* <tr>
* <td>System Property</td>
* <td>CatalogManager.properties<br/>Property</td>
* <td>Description</td>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>xml.catalog.ignoreMissing</td>
* <td>&#160;</td>
* <td>If true, a missing <i>CatalogManager.properties</i> file or missing properties
* within that file will not generate warning messages. See also the
* <i>ignoreMissingProperties</i> method.</td>
* </tr>
*
* <tr>
* <td>xml.catalog.files</td>
* <td>catalogs</td>
* <td>The <emph>semicolon-delimited</emph> list of catalog files.</td>
* </tr>
*
* <tr>
* <td>&#160;</td>
* <td>relative-catalogs</td>
* <td>If false, relative catalog URIs are made absolute with respect to the base URI of
* the <i>CatalogManager.properties</i> file. This setting only applies to catalog
* URIs obtained from the <i>catalogs</i> property <emph>in the</emph>
* <i>CatalogManager.properties</i> file</td>
* </tr>
*
* <tr>
* <td>xml.catalog.verbosity</td>
* <td>verbosity</td>
* <td>If non-zero, the Catalog classes will print informative and debugging messages.
* The higher the number, the more messages.</td>
* </tr>
*
* <tr>
* <td>xml.catalog.prefer</td>
* <td>prefer</td>
* <td>Which identifier is preferred, "public" or "system"?</td>
* </tr>
*
* <tr>
* <td>xml.catalog.staticCatalog</td>
* <td>static-catalog</td>
* <td>Should a single catalog be constructed for all parsing, or should a different
* catalog be created for each parser?</td>
* </tr>
*
* <tr>
* <td>xml.catalog.allowPI</td>
* <td>allow-oasis-xml-catalog-pi</td>
* <td>If the source document contains "oasis-xml-catalog" processing instructions,
* should they be used?</td>
* </tr>
*
* <tr>
* <td>xml.catalog.className</td>
* <td>catalog-class-name</td>
* <td>If you're using the convenience classes
* <tt>com.sun.org.apache.xml.internal.resolver.tools.*</tt>), this setting
* allows you to specify an alternate class name to use for the underlying
* catalog.</td>
* </tr>
* </tbody>
* </table>
*
* @see Catalog
* @deprecated The JDK internal Catalog API in package
* {@code com.sun.org.apache.xml.internal.resolver}
* is encapsulated in JDK 9. The entire implementation under the package is now
* deprecated and subject to removal in a future release. Users of the API
* should migrate to the {@linkplain javax.xml.catalog new public API}.
* <p>
* The new Catalog API is supported throughout the JDK XML Processors, which allows
* the use of Catalog by simply setting a path to a Catalog file as a property.
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
* @version 1.0
*/
@Deprecated(since="9", forRemoval=true)
public class CatalogManager {
private static final String pFiles = "xml.catalog.files";
private static final String pVerbosity = "xml.catalog.verbosity";
private static final String pPrefer = "xml.catalog.prefer";
private static final String pStatic = "xml.catalog.staticCatalog";
private static final String pAllowPI = "xml.catalog.allowPI";
private static final String pClassname = "xml.catalog.className";
private static final String pIgnoreMissing = "xml.catalog.ignoreMissing";
/** A static CatalogManager instance for sharing */
private static final CatalogManager staticManager = new CatalogManager();
/** The bootstrap resolver to use when loading XML Catalogs. */
private BootstrapResolver bResolver = new BootstrapResolver();
/** Flag to ignore missing property files and/or properties */
private boolean ignoreMissingProperties
= (SecuritySupport.getSystemProperty(pIgnoreMissing) != null
|| SecuritySupport.getSystemProperty(pFiles) != null);
/** Holds the resources after they are loaded from the file. */
private ResourceBundle resources;
/** The name of the CatalogManager properties file. */
private String propertyFile = "CatalogManager.properties";
/** The location of the propertyFile */
private URL propertyFileURI = null;
/** Default catalog files list. */
private String defaultCatalogFiles = "./xcatalog";
/** Current catalog files list. */
private String catalogFiles = null;
/** Did the catalogFiles come from the properties file? */
private boolean fromPropertiesFile = false;
/** Default verbosity level if there is no property setting for it. */
private int defaultVerbosity = 1;
/** Current verbosity level. */
private Integer verbosity = null;
/** Default preference setting. */
private boolean defaultPreferPublic = true;
/** Current preference setting. */
private Boolean preferPublic = null;
/** Default setting of the static catalog flag. */
private boolean defaultUseStaticCatalog = true;
/** Current setting of the static catalog flag. */
private Boolean useStaticCatalog = null;
/** The static catalog used by this manager. */
private static volatile Catalog staticCatalog = null;
/** Default setting of the oasisXMLCatalogPI flag. */
private boolean defaultOasisXMLCatalogPI = true;
/** Current setting of the oasisXMLCatalogPI flag. */
private Boolean oasisXMLCatalogPI = null;
/** Default setting of the relativeCatalogs flag. */
private boolean defaultRelativeCatalogs = true;
/** Current setting of the relativeCatalogs flag. */
private Boolean relativeCatalogs = null;
/** Current catalog class name. */
private String catalogClassName = null;
/**
* Indicates whether implementation parts should use
* service loader (or similar).
* Note the default value (false) is the safe option..
*/
private boolean useServicesMechanism;
/** The manager's debug object. Used for printing debugging messages.
*
* <p>This field is public so that objects that have access to this
* CatalogManager can use this debug object.</p>
*/
public Debug debug = null;
/** Constructor. */
public CatalogManager() {
init();
}
/** Constructor that specifies an explicit property file. */
public CatalogManager(String propertyFile) {
this.propertyFile = propertyFile;
init();
}
private void init() {
debug = new Debug();
// Note that we don't setDebug() here; we do that lazily. Either the
// user will set it explicitly, or we'll do it automagically if they
// read from the propertyFile for some other reason. That way, there's
// no attempt to read from the file before the caller has had a chance
// to avoid it.
if (System.getSecurityManager() == null) {
useServicesMechanism = true;
}
// Make sure verbosity is set by xml.catalog.verbosity sysprop
// setting, if defined.
queryVerbosityFromSysProp();
}
/** Set the bootstrap resolver
* @param resolver the bootstrap resolver
*/
public void setBootstrapResolver(BootstrapResolver resolver) {
bResolver = resolver;
}
/** Get the bootstrap resolver
* @return the bootstrap resolver
*/
public BootstrapResolver getBootstrapResolver() {
return bResolver;
}
/** Query system property for verbosity level. */
private void queryVerbosityFromSysProp() {
String verbStr = SecuritySupport.getSystemProperty(pVerbosity);
if (verbStr != null) {
try {
int verb = Integer.parseInt(verbStr.trim());
verbosity = new Integer(verb);
debug.setDebug(verb);
} catch (Exception e) {
System.err.println("Cannot parse verbosity: \"" + verbStr + "\"");
}
}
}
/**
* Load the properties from the propertyFile and build the
* resources from it.
*/
private synchronized void readProperties() {
try {
propertyFileURI = CatalogManager.class.getResource("/"+propertyFile);
InputStream in =
CatalogManager.class.getResourceAsStream("/"+propertyFile);
if (in==null) {
if (!ignoreMissingProperties) {
System.err.println("Cannot find "+propertyFile);
// there's no reason to give this warning more than once
ignoreMissingProperties = true;
}
return;
}
resources = new PropertyResourceBundle(in);
} catch (MissingResourceException mre) {
if (!ignoreMissingProperties) {
System.err.println("Cannot read "+propertyFile);
}
} catch (java.io.IOException e) {
if (!ignoreMissingProperties) {
System.err.println("Failure trying to read "+propertyFile);
}
}
// This is a bit of a hack. After we've successfully read the properties,
// use them to set the default debug level, if the user hasn't already set
// the default debug level.
if (verbosity == null) {
try {
String verbStr = resources.getString("verbosity");
int verb = Integer.parseInt(verbStr.trim());
debug.setDebug(verb);
verbosity = new Integer(verb);
} catch (Exception e) {
// nop
}
}
}
/**
* Allow access to the static CatalogManager
*/
public static CatalogManager getStaticManager() {
return staticManager;
}
/**
* How are missing properties handled?
*
* <p>If true, missing or unreadable property files will
* not be reported. Otherwise, a message will be sent to System.err.
* </p>
*/
public boolean getIgnoreMissingProperties() {
return ignoreMissingProperties;
}
/**
* How should missing properties be handled?
*
* <p>If ignore is true, missing or unreadable property files will
* not be reported. Otherwise, a message will be sent to System.err.
* </p>
*/
public void setIgnoreMissingProperties(boolean ignore) {
ignoreMissingProperties = ignore;
}
/**
* How are missing properties handled?
*
* <p>If ignore is true, missing or unreadable property files will
* not be reported. Otherwise, a message will be sent to System.err.
* </p>
*
* @deprecated No longer static; use get/set methods.
*/
public void ignoreMissingProperties(boolean ignore) {
setIgnoreMissingProperties(ignore);
}
/**
* Obtain the verbosity setting from the properties.
*
* @return The verbosity level from the propertyFile or the
* defaultVerbosity.
*/
private int queryVerbosity () {
String defaultVerbStr = Integer.toString(defaultVerbosity);
String verbStr = SecuritySupport.getSystemProperty(pVerbosity);
if (verbStr == null) {
if (resources==null) readProperties();
if (resources != null) {
try {
verbStr = resources.getString("verbosity");
} catch (MissingResourceException e) {
verbStr = defaultVerbStr;
}
} else {
verbStr = defaultVerbStr;
}
}
int verb = defaultVerbosity;
try {
verb = Integer.parseInt(verbStr.trim());
} catch (Exception e) {
System.err.println("Cannot parse verbosity: \"" + verbStr + "\"");
}
// This is a bit of a hack. After we've successfully got the verbosity,
// we have to use it to set the default debug level,
// if the user hasn't already set the default debug level.
if (verbosity == null) {
debug.setDebug(verb);
verbosity = new Integer(verb);
}
return verb;
}
/**
* What is the current verbosity?
*/
public int getVerbosity() {
if (verbosity == null) {
verbosity = new Integer(queryVerbosity());
}
return verbosity.intValue();
}
/**
* Set the current verbosity.
*/
public void setVerbosity (int verbosity) {
this.verbosity = new Integer(verbosity);
debug.setDebug(verbosity);
}
/**
* What is the current verbosity?
*
* @deprecated No longer static; use get/set methods.
*/
public int verbosity () {
return getVerbosity();
}
/**
* Obtain the relativeCatalogs setting from the properties.
*
* @return The relativeCatalogs setting from the propertyFile or the
* defaultRelativeCatalogs.
*/
private boolean queryRelativeCatalogs () {
if (resources==null) readProperties();
if (resources==null) return defaultRelativeCatalogs;
try {
String allow = resources.getString("relative-catalogs");
return (allow.equalsIgnoreCase("true")
|| allow.equalsIgnoreCase("yes")
|| allow.equalsIgnoreCase("1"));
} catch (MissingResourceException e) {
return defaultRelativeCatalogs;
}
}
/**
* Get the relativeCatalogs setting.
*
* <p>This property is used when the catalogFiles property is
* interrogated. If true, then relative catalog entry file names
* are returned. If false, relative catalog entry file names are
* made absolute with respect to the properties file before returning
* them.</p>
*
* <p>This property <emph>only applies</emph> when the catalog files
* come from a properties file. If they come from a system property or
* the default list, they are never considered relative. (What would
* they be relative to?)</p>
*
* <p>In the properties, a value of 'yes', 'true', or '1' is considered
* true, anything else is false.</p>
*
* @return The relativeCatalogs setting from the propertyFile or the
* defaultRelativeCatalogs.
*/
public boolean getRelativeCatalogs () {
if (relativeCatalogs == null) {
relativeCatalogs = queryRelativeCatalogs() ? Boolean.TRUE : Boolean.FALSE;
}
return relativeCatalogs.booleanValue();
}
/**
* Set the relativeCatalogs setting.
*
* @see #getRelativeCatalogs()
*/
public void setRelativeCatalogs (boolean relative) {
relativeCatalogs = relative ? Boolean.TRUE : Boolean.FALSE;
}
/**
* Get the relativeCatalogs setting.
*
* @deprecated No longer static; use get/set methods.
*/
public boolean relativeCatalogs () {
return getRelativeCatalogs();
}
/**
* Obtain the list of catalog files from the properties.
*
* @return A semicolon delimited list of catlog file URIs
*/
private String queryCatalogFiles () {
String catalogList = SecuritySupport.getSystemProperty(pFiles);
fromPropertiesFile = false;
if (catalogList == null) {
if (resources == null) readProperties();
if (resources != null) {
try {
catalogList = resources.getString("catalogs");
fromPropertiesFile = true;
} catch (MissingResourceException e) {
System.err.println(propertyFile + ": catalogs not found.");
catalogList = null;
}
}
}
if (catalogList == null) {
catalogList = defaultCatalogFiles;
}
return catalogList;
}
/**
* Return the current list of catalog files.
*
* @return A vector of the catalog file names or null if no catalogs
* are available in the properties.
*/
public Vector getCatalogFiles() {
if (catalogFiles == null) {
catalogFiles = queryCatalogFiles();
}
StringTokenizer files = new StringTokenizer(catalogFiles, ";");
Vector catalogs = new Vector();
while (files.hasMoreTokens()) {
String catalogFile = files.nextToken();
URL absURI = null;
if (fromPropertiesFile && !relativeCatalogs()) {
try {
absURI = new URL(propertyFileURI, catalogFile);
catalogFile = absURI.toString();
} catch (MalformedURLException mue) {
absURI = null;
}
}
catalogs.add(catalogFile);
}
return catalogs;
}
/**
* Set the list of catalog files.
*/
public void setCatalogFiles(String fileList) {
catalogFiles = fileList;
fromPropertiesFile = false;
}
/**
* Return the current list of catalog files.
*
* @return A vector of the catalog file names or null if no catalogs
* are available in the properties.
*
* @deprecated No longer static; use get/set methods.
*/
public Vector catalogFiles() {
return getCatalogFiles();
}
/**
* Obtain the preferPublic setting from the properties.
*
* <p>In the properties, a value of 'public' is true,
* anything else is false.</p>
*
* @return True if prefer is public or the
* defaultPreferSetting.
*/
private boolean queryPreferPublic () {
String prefer = SecuritySupport.getSystemProperty(pPrefer);
if (prefer == null) {
if (resources==null) readProperties();
if (resources==null) return defaultPreferPublic;
try {
prefer = resources.getString("prefer");
} catch (MissingResourceException e) {
return defaultPreferPublic;
}
}
if (prefer == null) {
return defaultPreferPublic;
}
return (prefer.equalsIgnoreCase("public"));
}
/**
* Return the current prefer public setting.
*
* @return True if public identifiers are preferred.
*/
public boolean getPreferPublic () {
if (preferPublic == null) {
preferPublic = queryPreferPublic() ? Boolean.TRUE : Boolean.FALSE;
}
return preferPublic.booleanValue();
}
/**
* Set the prefer public setting.
*/
public void setPreferPublic (boolean preferPublic) {
this.preferPublic = preferPublic ? Boolean.TRUE : Boolean.FALSE;
}
/**
* Return the current prefer public setting.
*
* @return True if public identifiers are preferred.
*
* @deprecated No longer static; use get/set methods.
*/
public boolean preferPublic () {
return getPreferPublic();
}
/**
* Obtain the static-catalog setting from the properties.
*
* <p>In the properties, a value of 'yes', 'true', or '1' is considered
* true, anything else is false.</p>
*
* @return The static-catalog setting from the propertyFile or the
* defaultUseStaticCatalog.
*/
private boolean queryUseStaticCatalog () {
String staticCatalog = SecuritySupport.getSystemProperty(pStatic);
if (staticCatalog == null) {
if (resources==null) readProperties();
if (resources==null) return defaultUseStaticCatalog;
try {
staticCatalog = resources.getString("static-catalog");
} catch (MissingResourceException e) {
return defaultUseStaticCatalog;
}
}
if (staticCatalog == null) {
return defaultUseStaticCatalog;
}
return (staticCatalog.equalsIgnoreCase("true")
|| staticCatalog.equalsIgnoreCase("yes")
|| staticCatalog.equalsIgnoreCase("1"));
}
/**
* Get the current use static catalog setting.
*/
public boolean getUseStaticCatalog() {
if (useStaticCatalog == null) {
useStaticCatalog = queryUseStaticCatalog() ? Boolean.TRUE : Boolean.FALSE;
}
return useStaticCatalog.booleanValue();
}
/**
* Set the use static catalog setting.
*/
public void setUseStaticCatalog(boolean useStatic) {
useStaticCatalog = useStatic ? Boolean.TRUE : Boolean.FALSE;
}
/**
* Get the current use static catalog setting.
*
* @deprecated No longer static; use get/set methods.
*/
public boolean staticCatalog() {
return getUseStaticCatalog();
}
/**
* Get a new catalog instance.
*
* This method always returns a new instance of the underlying catalog class.
*/
public Catalog getPrivateCatalog() {
Catalog catalog = staticCatalog;
if (useStaticCatalog == null) {
useStaticCatalog = getUseStaticCatalog() ? Boolean.TRUE : Boolean.FALSE;
}
if (catalog == null || !useStaticCatalog.booleanValue()) {
try {
String catalogClassName = getCatalogClassName();
if (catalogClassName == null) {
catalog = new Catalog();
} else {
try {
catalog = (Catalog) ReflectUtil.forName(catalogClassName).newInstance();
} catch (ClassNotFoundException cnfe) {
debug.message(1,"Catalog class named '"
+ catalogClassName
+ "' could not be found. Using default.");
catalog = new Catalog();
} catch (ClassCastException cnfe) {
debug.message(1,"Class named '"
+ catalogClassName
+ "' is not a Catalog. Using default.");
catalog = new Catalog();
}
}
catalog.setCatalogManager(this);
catalog.setupReaders();
catalog.loadSystemCatalogs();
} catch (Exception ex) {
ex.printStackTrace();
}
if (useStaticCatalog.booleanValue()) {
staticCatalog = catalog;
}
}
return catalog;
}
/**
* Get a catalog instance.
*
* If this manager uses static catalogs, the same static catalog will
* always be returned. Otherwise a new catalog will be returned.
*/
public Catalog getCatalog() {
Catalog catalog = staticCatalog;
if (useStaticCatalog == null) {
useStaticCatalog = getUseStaticCatalog() ? Boolean.TRUE : Boolean.FALSE;
}
if (catalog == null || !useStaticCatalog.booleanValue()) {
catalog = getPrivateCatalog();
if (useStaticCatalog.booleanValue()) {
staticCatalog = catalog;
}
}
return catalog;
}
/**
* <p>Obtain the oasisXMLCatalogPI setting from the properties.</p>
*
* <p>In the properties, a value of 'yes', 'true', or '1' is considered
* true, anything else is false.</p>
*
* @return The oasisXMLCatalogPI setting from the propertyFile or the
* defaultOasisXMLCatalogPI.
*/
public boolean queryAllowOasisXMLCatalogPI () {
String allow = SecuritySupport.getSystemProperty(pAllowPI);
if (allow == null) {
if (resources==null) readProperties();
if (resources==null) return defaultOasisXMLCatalogPI;
try {
allow = resources.getString("allow-oasis-xml-catalog-pi");
} catch (MissingResourceException e) {
return defaultOasisXMLCatalogPI;
}
}
if (allow == null) {
return defaultOasisXMLCatalogPI;
}
return (allow.equalsIgnoreCase("true")
|| allow.equalsIgnoreCase("yes")
|| allow.equalsIgnoreCase("1"));
}
/**
* Get the current XML Catalog PI setting.
*/
public boolean getAllowOasisXMLCatalogPI () {
if (oasisXMLCatalogPI == null) {
oasisXMLCatalogPI = queryAllowOasisXMLCatalogPI() ? Boolean.TRUE : Boolean.FALSE;
}
return oasisXMLCatalogPI.booleanValue();
}
public boolean useServicesMechanism() {
return useServicesMechanism;
}
/**
* Set the XML Catalog PI setting
*/
public void setAllowOasisXMLCatalogPI(boolean allowPI) {
oasisXMLCatalogPI = allowPI ? Boolean.TRUE : Boolean.FALSE;
}
/**
* Get the current XML Catalog PI setting.
*
* @deprecated No longer static; use get/set methods.
*/
public boolean allowOasisXMLCatalogPI() {
return getAllowOasisXMLCatalogPI();
}
/**
* Obtain the Catalog class name setting from the properties.
*
*/
public String queryCatalogClassName () {
String className = SecuritySupport.getSystemProperty(pClassname);
if (className == null) {
if (resources==null) readProperties();
if (resources==null) return null;
try {
return resources.getString("catalog-class-name");
} catch (MissingResourceException e) {
return null;
}
}
return className;
}
/**
* Get the current Catalog class name.
*/
public String getCatalogClassName() {
if (catalogClassName == null) {
catalogClassName = queryCatalogClassName();
}
return catalogClassName;
}
/**
* Set the Catalog class name.
*/
public void setCatalogClassName(String className) {
catalogClassName = className;
}
/**
* Get the current Catalog class name.
*
* @deprecated No longer static; use get/set methods.
*/
public String catalogClassName() {
return getCatalogClassName();
}
}

View file

@ -1,697 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Enumeration;
import java.util.Vector;
import java.net.URL;
import java.net.URLConnection;
import java.net.MalformedURLException;
import javax.xml.parsers.SAXParserFactory;
import com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl;
import com.sun.org.apache.xerces.internal.utils.SecuritySupport;
import com.sun.org.apache.xml.internal.resolver.readers.SAXCatalogReader;
import com.sun.org.apache.xml.internal.resolver.readers.OASISXMLCatalogReader;
import com.sun.org.apache.xml.internal.resolver.readers.TR9401CatalogReader;
/**
* An extension to OASIS Open Catalog files, this class supports
* suffix-based matching and an external RFC2483 resolver.
*
* @see Catalog
* @deprecated The JDK internal Catalog API in package
* {@code com.sun.org.apache.xml.internal.resolver}
* is encapsulated in JDK 9. The entire implementation under the package is now
* deprecated and subject to removal in a future release. Users of the API
* should migrate to the {@linkplain javax.xml.catalog new public API}.
* <p>
* The new Catalog API is supported throughout the JDK XML Processors, which allows
* the use of Catalog by simply setting a path to a Catalog file as a property.
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
* @version 1.0
*/
@Deprecated(since="9", forRemoval=true)
public class Resolver extends Catalog {
/**
* The URISUFFIX Catalog Entry type.
*
* <p>URI suffix entries match URIs that end in a specified suffix.</p>
*/
public static final int URISUFFIX = CatalogEntry.addEntryType("URISUFFIX", 2);
/**
* The SYSTEMSUFFIX Catalog Entry type.
*
* <p>System suffix entries match system identifiers that end in a
* specified suffix.</p>
*/
public static final int SYSTEMSUFFIX = CatalogEntry.addEntryType("SYSTEMSUFFIX", 2);
/**
* The RESOLVER Catalog Entry type.
*
* <p>A hook for providing support for web-based backup resolvers.</p>
*/
public static final int RESOLVER = CatalogEntry.addEntryType("RESOLVER", 1);
/**
* The SYSTEMREVERSE Catalog Entry type.
*
* <p>This is a bit of a hack. There's no actual SYSTEMREVERSE entry,
* but this entry type is used to indicate that a reverse lookup is
* being performed. (This allows the Resolver to implement
* RFC2483 I2N and I2NS.)
*/
public static final int SYSTEMREVERSE
= CatalogEntry.addEntryType("SYSTEMREVERSE", 1);
/**
* Setup readers.
*/
public void setupReaders() {
SAXParserFactory spf = catalogManager.useServicesMechanism() ?
SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
spf.setNamespaceAware(true);
spf.setValidating(false);
SAXCatalogReader saxReader = new SAXCatalogReader(spf);
saxReader.setCatalogParser(null, "XCatalog",
"com.sun.org.apache.xml.internal.resolver.readers.XCatalogReader");
saxReader.setCatalogParser(OASISXMLCatalogReader.namespaceName,
"catalog",
"com.sun.org.apache.xml.internal.resolver.readers.ExtendedXMLCatalogReader");
addReader("application/xml", saxReader);
TR9401CatalogReader textReader = new TR9401CatalogReader();
addReader("text/plain", textReader);
}
/**
* Cleanup and process a Catalog entry.
*
* <p>This method processes each Catalog entry, changing mapped
* relative system identifiers into absolute ones (based on the current
* base URI), and maintaining other information about the current
* catalog.</p>
*
* @param entry The CatalogEntry to process.
*/
public void addEntry(CatalogEntry entry) {
int type = entry.getEntryType();
if (type == URISUFFIX) {
String suffix = normalizeURI(entry.getEntryArg(0));
String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(1)));
entry.setEntryArg(1, fsi);
catalogManager.debug.message(4, "URISUFFIX", suffix, fsi);
} else if (type == SYSTEMSUFFIX) {
String suffix = normalizeURI(entry.getEntryArg(0));
String fsi = makeAbsolute(normalizeURI(entry.getEntryArg(1)));
entry.setEntryArg(1, fsi);
catalogManager.debug.message(4, "SYSTEMSUFFIX", suffix, fsi);
}
super.addEntry(entry);
}
/**
* Return the applicable URI.
*
* <p>If a URI entry exists in the Catalog
* for the URI specified, return the mapped value.</p>
*
* <p>In the Resolver (as opposed to the Catalog) class, if the
* URI isn't found by the usual algorithm, URISUFFIX entries are
* considered.</p>
*
* <p>URI comparison is case sensitive.</p>
*
* @param uri The URI to locate in the catalog.
*
* @return The resolved URI.
*
* @throws MalformedURLException The system identifier of a
* subordinate catalog cannot be turned into a valid URL.
* @throws IOException Error reading subordinate catalog file.
*/
public String resolveURI(String uri)
throws MalformedURLException, IOException {
String resolved = super.resolveURI(uri);
if (resolved != null) {
return resolved;
}
Enumeration en = catalogEntries.elements();
while (en.hasMoreElements()) {
CatalogEntry e = (CatalogEntry) en.nextElement();
if (e.getEntryType() == RESOLVER) {
resolved = resolveExternalSystem(uri, e.getEntryArg(0));
if (resolved != null) {
return resolved;
}
} else if (e.getEntryType() == URISUFFIX) {
String suffix = e.getEntryArg(0);
String result = e.getEntryArg(1);
if (suffix.length() <= uri.length()
&& uri.substring(uri.length()-suffix.length()).equals(suffix)) {
return result;
}
}
}
// Otherwise, look in the subordinate catalogs
return resolveSubordinateCatalogs(Catalog.URI,
null,
null,
uri);
}
/**
* Return the applicable SYSTEM system identifier, resorting
* to external RESOLVERs if necessary.
*
* <p>If a SYSTEM entry exists in the Catalog
* for the system ID specified, return the mapped value.</p>
*
* <p>In the Resolver (as opposed to the Catalog) class, if the
* URI isn't found by the usual algorithm, SYSTEMSUFFIX entries are
* considered.</p>
*
* <p>On Windows-based operating systems, the comparison between
* the system identifier provided and the SYSTEM entries in the
* Catalog is case-insensitive.</p>
*
* @param systemId The system ID to locate in the catalog.
*
* @return The system identifier to use for systemId.
*
* @throws MalformedURLException The formal system identifier of a
* subordinate catalog cannot be turned into a valid URL.
* @throws IOException Error reading subordinate catalog file.
*/
public String resolveSystem(String systemId)
throws MalformedURLException, IOException {
String resolved = super.resolveSystem(systemId);
if (resolved != null) {
return resolved;
}
Enumeration en = catalogEntries.elements();
while (en.hasMoreElements()) {
CatalogEntry e = (CatalogEntry) en.nextElement();
if (e.getEntryType() == RESOLVER) {
resolved = resolveExternalSystem(systemId, e.getEntryArg(0));
if (resolved != null) {
return resolved;
}
} else if (e.getEntryType() == SYSTEMSUFFIX) {
String suffix = e.getEntryArg(0);
String result = e.getEntryArg(1);
if (suffix.length() <= systemId.length()
&& systemId.substring(systemId.length()-suffix.length()).equals(suffix)) {
return result;
}
}
}
return resolveSubordinateCatalogs(Catalog.SYSTEM,
null,
null,
systemId);
}
/**
* Return the applicable PUBLIC or SYSTEM identifier, resorting
* to external resolvers if necessary.
*
* <p>This method searches the Catalog and returns the system
* identifier specified for the given system or
* public identifiers. If
* no appropriate PUBLIC or SYSTEM entry is found in the Catalog,
* null is returned.</p>
*
* <p>Note that a system or public identifier in the current catalog
* (or subordinate catalogs) will be used in preference to an
* external resolver. Further, if a systemId is present, the external
* resolver(s) will be queried for that before the publicId.</p>
*
* @param publicId The public identifier to locate in the catalog.
* Public identifiers are normalized before comparison.
* @param systemId The nominal system identifier for the entity
* in question (as provided in the source document).
*
* @throws MalformedURLException The formal system identifier of a
* subordinate catalog cannot be turned into a valid URL.
* @throws IOException Error reading subordinate catalog file.
*
* @return The system identifier to use.
* Note that the nominal system identifier is not returned if a
* match is not found in the catalog, instead null is returned
* to indicate that no match was found.
*/
public String resolvePublic(String publicId, String systemId)
throws MalformedURLException, IOException {
String resolved = super.resolvePublic(publicId, systemId);
if (resolved != null) {
return resolved;
}
Enumeration en = catalogEntries.elements();
while (en.hasMoreElements()) {
CatalogEntry e = (CatalogEntry) en.nextElement();
if (e.getEntryType() == RESOLVER) {
if (systemId != null) {
resolved = resolveExternalSystem(systemId,
e.getEntryArg(0));
if (resolved != null) {
return resolved;
}
}
resolved = resolveExternalPublic(publicId, e.getEntryArg(0));
if (resolved != null) {
return resolved;
}
}
}
return resolveSubordinateCatalogs(Catalog.PUBLIC,
null,
publicId,
systemId);
}
/**
* Query an external RFC2483 resolver for a system identifier.
*
* @param systemId The system ID to locate.
* @param resolver The name of the resolver to use.
*
* @return The system identifier to use for the systemId.
*/
protected String resolveExternalSystem(String systemId, String resolver)
throws MalformedURLException, IOException {
Resolver r = queryResolver(resolver, "i2l", systemId, null);
if (r != null) {
return r.resolveSystem(systemId);
} else {
return null;
}
}
/**
* Query an external RFC2483 resolver for a public identifier.
*
* @param publicId The system ID to locate.
* @param resolver The name of the resolver to use.
*
* @return The system identifier to use for the systemId.
*/
protected String resolveExternalPublic(String publicId, String resolver)
throws MalformedURLException, IOException {
Resolver r = queryResolver(resolver, "fpi2l", publicId, null);
if (r != null) {
return r.resolvePublic(publicId, null);
} else {
return null;
}
}
/**
* Query an external RFC2483 resolver.
*
* @param resolver The URL of the RFC2483 resolver.
* @param command The command to send the resolver.
* @param arg1 The first argument to the resolver.
* @param arg2 The second argument to the resolver, usually null.
*
* @return The Resolver constructed.
*/
protected Resolver queryResolver(String resolver,
String command,
String arg1,
String arg2) {
InputStream iStream = null;
String RFC2483 = resolver + "?command=" + command
+ "&format=tr9401&uri=" + arg1
+ "&uri2=" + arg2;
String line = null;
try {
URL url = new URL(RFC2483);
URLConnection urlCon = url.openConnection();
urlCon.setUseCaches(false);
Resolver r = (Resolver) newCatalog();
String cType = urlCon.getContentType();
// I don't care about the character set or subtype
if (cType.indexOf(";") > 0) {
cType = cType.substring(0, cType.indexOf(";"));
}
r.parseCatalog(cType, urlCon.getInputStream());
return r;
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.UNPARSEABLE) {
catalogManager.debug.message(1, "Unparseable catalog: " + RFC2483);
} else if (cex.getExceptionType()
== CatalogException.UNKNOWN_FORMAT) {
catalogManager.debug.message(1, "Unknown catalog format: " + RFC2483);
}
return null;
} catch (MalformedURLException mue) {
catalogManager.debug.message(1, "Malformed resolver URL: " + RFC2483);
return null;
} catch (IOException ie) {
catalogManager.debug.message(1, "I/O Exception opening resolver: " + RFC2483);
return null;
}
}
/**
* Append two vectors, returning the result.
*
* @param vec The first vector
* @param appvec The vector to be appended
* @return The vector vec, with appvec's elements appended to it
*/
private Vector appendVector(Vector vec, Vector appvec) {
if (appvec != null) {
for (int count = 0; count < appvec.size(); count++) {
vec.addElement(appvec.elementAt(count));
}
}
return vec;
}
/**
* Find the URNs for a given system identifier in all catalogs.
*
* @param systemId The system ID to locate.
*
* @return A vector of URNs that map to the systemId.
*/
public Vector resolveAllSystemReverse(String systemId)
throws MalformedURLException, IOException {
Vector resolved = new Vector();
// If there's a SYSTEM entry in this catalog, use it
if (systemId != null) {
Vector localResolved = resolveLocalSystemReverse(systemId);
resolved = appendVector(resolved, localResolved);
}
// Otherwise, look in the subordinate catalogs
Vector subResolved = resolveAllSubordinateCatalogs(SYSTEMREVERSE,
null,
null,
systemId);
return appendVector(resolved, subResolved);
}
/**
* Find the URN for a given system identifier.
*
* @param systemId The system ID to locate.
*
* @return A (single) URN that maps to the systemId.
*/
public String resolveSystemReverse(String systemId)
throws MalformedURLException, IOException {
Vector resolved = resolveAllSystemReverse(systemId);
if (resolved != null && resolved.size() > 0) {
return (String) resolved.elementAt(0);
} else {
return null;
}
}
/**
* Return the applicable SYSTEM system identifiers.
*
* <p>If one or more SYSTEM entries exists in the Catalog
* for the system ID specified, return the mapped values.</p>
*
* <p>The caller is responsible for doing any necessary
* normalization of the system identifier before calling
* this method. For example, a relative system identifier in
* a document might be converted to an absolute system identifier
* before attempting to resolve it.</p>
*
* <p>Note that this function will force all subordinate catalogs
* to be loaded.</p>
*
* <p>On Windows-based operating systems, the comparison between
* the system identifier provided and the SYSTEM entries in the
* Catalog is case-insensitive.</p>
*
* @param systemId The system ID to locate in the catalog.
*
* @return The system identifier to use for the notation.
*
* @throws MalformedURLException The formal system identifier of a
* subordinate catalog cannot be turned into a valid URL.
* @throws IOException Error reading subordinate catalog file.
*/
public Vector resolveAllSystem(String systemId)
throws MalformedURLException, IOException {
Vector resolutions = new Vector();
// If there are SYSTEM entries in this catalog, start with them
if (systemId != null) {
Vector localResolutions = resolveAllLocalSystem(systemId);
resolutions = appendVector(resolutions, localResolutions);
}
// Then look in the subordinate catalogs
Vector subResolutions = resolveAllSubordinateCatalogs(SYSTEM,
null,
null,
systemId);
resolutions = appendVector(resolutions, subResolutions);
if (resolutions.size() > 0) {
return resolutions;
} else {
return null;
}
}
/**
* Return all applicable SYSTEM system identifiers in this
* catalog.
*
* <p>If one or more SYSTEM entries exists in the catalog file
* for the system ID specified, return the mapped values.</p>
*
* @param systemId The system ID to locate in the catalog
*
* @return A vector of the mapped system identifiers or null
*/
private Vector resolveAllLocalSystem(String systemId) {
Vector map = new Vector();
String osname = SecuritySupport.getSystemProperty("os.name");
boolean windows = (osname.indexOf("Windows") >= 0);
Enumeration en = catalogEntries.elements();
while (en.hasMoreElements()) {
CatalogEntry e = (CatalogEntry) en.nextElement();
if (e.getEntryType() == SYSTEM
&& (e.getEntryArg(0).equals(systemId)
|| (windows
&& e.getEntryArg(0).equalsIgnoreCase(systemId)))) {
map.addElement(e.getEntryArg(1));
}
}
if (map.size() == 0) {
return null;
} else {
return map;
}
}
/**
* Find the URNs for a given system identifier in the current catalog.
*
* @param systemId The system ID to locate.
*
* @return A vector of URNs that map to the systemId.
*/
private Vector resolveLocalSystemReverse(String systemId) {
Vector map = new Vector();
String osname = SecuritySupport.getSystemProperty("os.name");
boolean windows = (osname.indexOf("Windows") >= 0);
Enumeration en = catalogEntries.elements();
while (en.hasMoreElements()) {
CatalogEntry e = (CatalogEntry) en.nextElement();
if (e.getEntryType() == SYSTEM
&& (e.getEntryArg(1).equals(systemId)
|| (windows
&& e.getEntryArg(1).equalsIgnoreCase(systemId)))) {
map.addElement(e.getEntryArg(0));
}
}
if (map.size() == 0) {
return null;
} else {
return map;
}
}
/**
* Search the subordinate catalogs, in order, looking for all
* match.
*
* <p>This method searches the Catalog and returns all of the system
* identifiers specified for the given entity type with the given
* name, public, and system identifiers. In some contexts, these
* may be null.</p>
*
* @param entityType The CatalogEntry type for which this query is
* being conducted. This is necessary in order to do the approprate
* query on a subordinate catalog.
* @param entityName The name of the entity being searched for, if
* appropriate.
* @param publicId The public identifier of the entity in question
* (as provided in the source document).
* @param systemId The nominal system identifier for the entity
* in question (as provided in the source document).
*
* @throws MalformedURLException The formal system identifier of a
* delegated catalog cannot be turned into a valid URL.
* @throws IOException Error reading delegated catalog file.
*
* @return The system identifier to use.
* Note that the nominal system identifier is not returned if a
* match is not found in the catalog, instead null is returned
* to indicate that no match was found.
*/
private synchronized Vector resolveAllSubordinateCatalogs(int entityType,
String entityName,
String publicId,
String systemId)
throws MalformedURLException, IOException {
Vector resolutions = new Vector();
for (int catPos = 0; catPos < catalogs.size(); catPos++) {
Resolver c = null;
try {
c = (Resolver) catalogs.elementAt(catPos);
} catch (ClassCastException e) {
String catfile = (String) catalogs.elementAt(catPos);
c = (Resolver) newCatalog();
try {
c.parseCatalog(catfile);
} catch (MalformedURLException mue) {
catalogManager.debug.message(1, "Malformed Catalog URL", catfile);
} catch (FileNotFoundException fnfe) {
catalogManager.debug.message(1, "Failed to load catalog, file not found",
catfile);
} catch (IOException ioe) {
catalogManager.debug.message(1, "Failed to load catalog, I/O error", catfile);
}
catalogs.setElementAt(c, catPos);
}
String resolved = null;
// Ok, now what are we supposed to call here?
if (entityType == DOCTYPE) {
resolved = c.resolveDoctype(entityName,
publicId,
systemId);
if (resolved != null) {
// Only find one DOCTYPE resolution
resolutions.addElement(resolved);
return resolutions;
}
} else if (entityType == DOCUMENT) {
resolved = c.resolveDocument();
if (resolved != null) {
// Only find one DOCUMENT resolution
resolutions.addElement(resolved);
return resolutions;
}
} else if (entityType == ENTITY) {
resolved = c.resolveEntity(entityName,
publicId,
systemId);
if (resolved != null) {
// Only find one ENTITY resolution
resolutions.addElement(resolved);
return resolutions;
}
} else if (entityType == NOTATION) {
resolved = c.resolveNotation(entityName,
publicId,
systemId);
if (resolved != null) {
// Only find one NOTATION resolution
resolutions.addElement(resolved);
return resolutions;
}
} else if (entityType == PUBLIC) {
resolved = c.resolvePublic(publicId, systemId);
if (resolved != null) {
// Only find one PUBLIC resolution
resolutions.addElement(resolved);
return resolutions;
}
} else if (entityType == SYSTEM) {
Vector localResolutions = c.resolveAllSystem(systemId);
resolutions = appendVector(resolutions, localResolutions);
break;
} else if (entityType == SYSTEMREVERSE) {
Vector localResolutions = c.resolveAllSystemReverse(systemId);
resolutions = appendVector(resolutions, localResolutions);
}
}
if (resolutions != null) {
return resolutions;
} else {
return null;
}
}
}

View file

@ -1,207 +0,0 @@
/*
* Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.helpers;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
/**
* A simple bootstrapping resolver.
*
* <p>This class is used as the entity resolver when reading XML Catalogs.
* It searches for the OASIS XML Catalog DTD, Relax NG Grammar and W3C XML Schema
* as resources (e.g., in the resolver jar file).</p>
*
* <p>If you have your own DTDs or schemas, you can extend this class and
* set the BootstrapResolver in your CatalogManager.</p>
*
* @see com.sun.org.apache.xml.internal.resolver.CatalogManager
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public class BootstrapResolver implements EntityResolver, URIResolver {
/** URI of the W3C XML Schema for OASIS XML Catalog files. */
public static final String xmlCatalogXSD = "http://www.oasis-open.org/committees/entity/release/1.0/catalog.xsd";
/** URI of the RELAX NG Grammar for OASIS XML Catalog files. */
public static final String xmlCatalogRNG = "http://www.oasis-open.org/committees/entity/release/1.0/catalog.rng";
/** Public identifier for OASIS XML Catalog files. */
public static final String xmlCatalogPubId = "-//OASIS//DTD XML Catalogs V1.0//EN";
/** System identifier for OASIS XML Catalog files. */
public static final String xmlCatalogSysId = "http://www.oasis-open.org/committees/entity/release/1.0/catalog.dtd";
/** Public identifier for legacy Apache XCatalog files. There is no official system identifier for XCatalog files. */
public static final String xCatalogPubId = "-//DTD XCatalog//EN";
/** Private hash used for public identifiers. */
private final Map<String, String> publicMap = new HashMap<>();
/** Private hash used for system identifiers. */
private final Map<String, String> systemMap = new HashMap<>();
/** Private hash used for URIs. */
private final Map<String, String> uriMap = new HashMap<>();
/** Constructor. */
public BootstrapResolver() {
URL url = this.getClass().getResource("/com/sun/org/apache/xml/internal/resolver/etc/catalog.dtd");
if (url != null) {
publicMap.put(xmlCatalogPubId, url.toString());
systemMap.put(xmlCatalogSysId, url.toString());
}
url = this.getClass().getResource("/com/sun/org/apache/xml/internal/resolver/etc/catalog.rng");
if (url != null) {
uriMap.put(xmlCatalogRNG, url.toString());
}
url = this.getClass().getResource("/com/sun/org/apache/xml/internal/resolver/etc/catalog.xsd");
if (url != null) {
uriMap.put(xmlCatalogXSD, url.toString());
}
url = this.getClass().getResource("/com/sun/org/apache/xml/internal/resolver/etc/xcatalog.dtd");
if (url != null) {
publicMap.put(xCatalogPubId, url.toString());
}
}
/** SAX resolveEntity API. */
public InputSource resolveEntity (String publicId, String systemId) {
String resolved = null;
if (systemId != null && systemMap.containsKey(systemId)) {
resolved = systemMap.get(systemId);
} else if (publicId != null && publicMap.containsKey(publicId)) {
resolved = publicMap.get(publicId);
}
if (resolved != null) {
try {
InputSource iSource = new InputSource(resolved);
iSource.setPublicId(publicId);
// Ideally this method would not attempt to open the
// InputStream, but there is a bug (in Xerces, at least)
// that causes the parser to mistakenly open the wrong
// system identifier if the returned InputSource does
// not have a byteStream.
//
// It could be argued that we still shouldn't do this here,
// but since the purpose of calling the entityResolver is
// almost certainly to open the input stream, it seems to
// do little harm.
//
URL url = new URL(resolved);
InputStream iStream = url.openStream();
iSource.setByteStream(iStream);
return iSource;
} catch (Exception e) {
// FIXME: silently fail?
return null;
}
}
return null;
}
/** Transformer resolve API. */
public Source resolve(String href, String base)
throws TransformerException {
String uri = href;
String fragment = null;
int hashPos = href.indexOf("#");
if (hashPos >= 0) {
uri = href.substring(0, hashPos);
fragment = href.substring(hashPos+1);
}
String result = null;
if (href != null && uriMap.containsKey(href)) {
result = uriMap.get(href);
}
if (result == null) {
try {
URL url = null;
if (base==null) {
url = new URL(uri);
result = url.toString();
} else {
URL baseURL = new URL(base);
url = (href.length()==0 ? baseURL : new URL(baseURL, uri));
result = url.toString();
}
} catch (java.net.MalformedURLException mue) {
// try to make an absolute URI from the current base
String absBase = makeAbsolute(base);
if (!absBase.equals(base)) {
// don't bother if the absBase isn't different!
return resolve(href, absBase);
} else {
throw new TransformerException("Malformed URL "
+ href + "(base " + base + ")",
mue);
}
}
}
SAXSource source = new SAXSource();
source.setInputSource(new InputSource(result));
return source;
}
/** Attempt to construct an absolute URI */
private String makeAbsolute(String uri) {
if (uri == null) {
uri = "";
}
try {
URL url = new URL(uri);
return url.toString();
} catch (MalformedURLException mue) {
try {
URL fileURL = FileURL.makeURL(uri);
return fileURL.toString();
} catch (MalformedURLException mue2) {
// bail
return uri;
}
}
}
}

View file

@ -1,105 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.helpers;
/**
* Static debugging/messaging class for Catalogs.
*
* <p>This class defines a set of static methods that can be called
* to produce debugging messages. Messages have an associated "debug
* level" and messages below the current setting are not displayed.</p>
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public class Debug {
/** The internal debug level. */
protected int debug = 0;
/** Constructor */
public Debug() {
// nop
}
/** Set the debug level for future messages. */
public void setDebug(int newDebug) {
debug = newDebug;
}
/** Get the current debug level. */
public int getDebug() {
return debug;
}
/**
* Print debug message (if the debug level is high enough).
*
* <p>Prints "the message"</p>
*
* @param level The debug level of this message. This message
* will only be
* displayed if the current debug level is at least equal to this
* value.
* @param message The text of the message.
*/
public void message(int level, String message) {
if (debug >= level) {
System.out.println(message);
}
}
/**
* Print debug message (if the debug level is high enough).
*
* <p>Prints "the message: spec"</p>
*
* @param level The debug level of this message. This message
* will only be
* displayed if the current debug level is at least equal to this
* value.
* @param message The text of the message.
* @param spec An argument to the message.
*/
public void message(int level, String message, String spec) {
if (debug >= level) {
System.out.println(message + ": " + spec);
}
}
/**
* Print debug message (if the debug level is high enough).
*
* <p>Prints "the message: spec1" and "spec2" indented on the next line.</p>
*
* @param level The debug level of this message. This message
* will only be
* displayed if the current debug level is at least equal to this
* value.
* @param message The text of the message.
* @param spec1 An argument to the message.
* @param spec2 Another argument to the message.
*/
public void message(int level, String message,
String spec1, String spec2) {
if (debug >= level) {
System.out.println(message + ": " + spec1);
System.out.println("\t" + spec2);
}
}
}

View file

@ -1,87 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.helpers;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.File;
/**
* Static method for dealing with file: URLs.
*
* <p>This class defines a static method that can be used to construct
* an appropriate file: URL from parts. It's defined here so that it
* can be reused throught the resolver.</p>
*
* <p>(Yes, I'd rather have called this class FileUR<b>I</b>, but
* given that a jave.net.URL is returned, it seemed...even more
* confusing.)</p>
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
* @version 1.0
*/
public abstract class FileURL {
protected FileURL() { }
/**
* Construct a file: URL for a path name.
*
* <p>URLs in the file: scheme can be constructed for paths on
* the local file system. Several possibilities need to be considered:
* </p>
*
* <ul>
* <li>If the path does not begin with a slash, then it is assumed
* to reside in the users current working directory
* (System.getProperty("user.dir")).</li>
* <li>On Windows machines, the current working directory uses
* backslashes (\\, instead of /).</li>
* <li>If the current working directory is "/", don't add an extra
* slash before the base name.</li>
* </ul>
*
* <p>This method is declared static so that other classes
* can use it directly.</p>
*
* @param pathname The path name component for which to construct a URL.
*
* @return The appropriate file: URL.
*
* @throws MalformedURLException if the pathname can't be turned into
* a proper URL.
*/
public static URL makeURL(String pathname) throws MalformedURLException {
/*if (pathname.startsWith("/")) {
return new URL("file://" + pathname);
}
String userdir = System.getProperty("user.dir");
userdir.replace('\\', '/');
if (userdir.endsWith("/")) {
return new URL("file:///" + userdir + pathname);
} else {
return new URL("file:///" + userdir + "/" + pathname);
}
*/
File file = new File(pathname);
return file.toURI().toURL();
}
}

View file

@ -1,110 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.helpers;
import org.w3c.dom.*;
/**
* Static Namespace query methods.
*
* <p>This class defines a set of static methods that can be called
* to analyze the namespace properties of DOM nodes.</p>
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public class Namespaces {
/**
* Returns the "prefix" part of a QName or the empty string (not
* null) if the name has no prefix.
*
* @param element The QName of an element.
* @return The prefix part of the element name.
*/
public static String getPrefix(Element element) {
String name = element.getTagName();
String prefix = "";
final int indexOfColon = name.indexOf(':');
if (indexOfColon > 0) {
prefix = name.substring(0, indexOfColon);
}
return prefix;
}
/**
* Returns the "localname" part of a QName, which is the whole
* name if it has no prefix.
*
* @param element The QName of an element.
* @return The local part of a QName.
*/
public static String getLocalName(Element element) {
String name = element.getTagName();
final int indexOfColon = name.indexOf(':');
if (indexOfColon > 0) {
name = name.substring(indexOfColon + 1);
}
return name;
}
/**
* Returns the namespace URI for the specified prefix at the
* specified context node.
*
* @param node The context node.
* @param prefix The prefix.
* @return The namespace URI associated with the prefix, or
* null if no namespace declaration exists for the prefix.
*/
public static String getNamespaceURI(Node node, String prefix) {
if (node == null || node.getNodeType() != Node.ELEMENT_NODE) {
return null;
}
if (prefix.length() == 0) {
if (((Element) node).hasAttribute("xmlns")) {
return ((Element) node).getAttribute("xmlns");
}
} else {
String nsattr = "xmlns:" + prefix;
if (((Element) node).hasAttribute(nsattr)) {
return ((Element) node).getAttribute(nsattr);
}
}
return getNamespaceURI(node.getParentNode(), prefix);
}
/**
* Returns the namespace URI for the namespace to which the
* element belongs.
*
* @param element The element.
* @return The namespace URI associated with the namespace of the
* element, or null if no namespace declaration exists for it.
*/
public static String getNamespaceURI(Element element) {
String prefix = getPrefix(element);
return getNamespaceURI(element, prefix);
}
}

View file

@ -1,169 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.helpers;
/**
* Static methods for dealing with public identifiers.
*
* <p>This class defines a set of static methods that can be called
* to handle public identifiers.</p>
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public abstract class PublicId {
protected PublicId() {}
/**
* Normalize a public identifier.
*
* <p>Public identifiers must be normalized according to the following
* rules before comparisons between them can be made:</p>
*
* <ul>
* <li>Whitespace characters are normalized to spaces (e.g., line feeds,
* tabs, etc. become spaces).</li>
* <li>Leading and trailing whitespace is removed.</li>
* <li>Multiple internal whitespaces are normalized to a single
* space.</li>
* </ul>
*
* <p>This method is declared static so that other classes
* can use it directly.</p>
*
* @param publicId The unnormalized public identifier.
*
* @return The normalized identifier.
*/
public static String normalize(String publicId) {
String normal = publicId.replace('\t', ' ');
normal = normal.replace('\r', ' ');
normal = normal.replace('\n', ' ');
normal = normal.trim();
int pos;
while ((pos = normal.indexOf(" ")) >= 0) {
normal = normal.substring(0, pos) + normal.substring(pos+1);
}
return normal;
}
/**
* Encode a public identifier as a "publicid" URN.
*
* <p>This method is declared static so that other classes
* can use it directly.</p>
*
* @param publicId The unnormalized public identifier.
*
* @return The normalized identifier.
*/
public static String encodeURN(String publicId) {
String urn = PublicId.normalize(publicId);
urn = PublicId.stringReplace(urn, "%", "%25");
urn = PublicId.stringReplace(urn, ";", "%3B");
urn = PublicId.stringReplace(urn, "'", "%27");
urn = PublicId.stringReplace(urn, "?", "%3F");
urn = PublicId.stringReplace(urn, "#", "%23");
urn = PublicId.stringReplace(urn, "+", "%2B");
urn = PublicId.stringReplace(urn, " ", "+");
urn = PublicId.stringReplace(urn, "::", ";");
urn = PublicId.stringReplace(urn, ":", "%3A");
urn = PublicId.stringReplace(urn, "//", ":");
urn = PublicId.stringReplace(urn, "/", "%2F");
StringBuilder buffer = new StringBuilder(13 + urn.length());
buffer.append("urn:publicid:");
buffer.append(urn);
return buffer.toString();
}
/**
* Decode a "publicid" URN into a public identifier.
*
* <p>This method is declared static so that other classes
* can use it directly.</p>
*
* @param urn The urn:publicid: URN
*
* @return The normalized identifier.
*/
public static String decodeURN(String urn) {
String publicId;
if (urn.startsWith("urn:publicid:")) {
publicId = urn.substring(13);
}
else {
return urn;
}
final boolean hasEscape = (publicId.indexOf('%') >= 0);
if (hasEscape) {
publicId = PublicId.stringReplace(publicId, "%2F", "/");
}
publicId = PublicId.stringReplace(publicId, ":", "//");
if (hasEscape) {
publicId = PublicId.stringReplace(publicId, "%3A", ":");
}
publicId = PublicId.stringReplace(publicId, ";", "::");
publicId = PublicId.stringReplace(publicId, "+", " ");
if (hasEscape) {
publicId = PublicId.stringReplace(publicId, "%2B", "+");
publicId = PublicId.stringReplace(publicId, "%23", "#");
publicId = PublicId.stringReplace(publicId, "%3F", "?");
publicId = PublicId.stringReplace(publicId, "%27", "'");
publicId = PublicId.stringReplace(publicId, "%3B", ";");
publicId = PublicId.stringReplace(publicId, "%25", "%");
}
return publicId;
}
/**
* Replace one string with another.
*/
private static String stringReplace(String str,
String oldStr,
String newStr) {
int pos = str.indexOf(oldStr);
if (pos >= 0) {
final StringBuilder buffer = new StringBuilder();
final int oldStrLength = oldStr.length();
int start = 0;
do {
for (int i = start; i < pos; ++i) {
buffer.append(str.charAt(i));
}
buffer.append(newStr);
start = pos + oldStrLength;
pos = str.indexOf(oldStr, start);
}
while (pos >= 0);
final int strLength = str.length();
for (int i = start; i < strLength; ++i) {
buffer.append(str.charAt(i));
}
return buffer.toString();
}
return str;
}
}

View file

@ -1,75 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.readers;
import java.io.IOException;
import java.net.MalformedURLException;
import com.sun.org.apache.xml.internal.resolver.CatalogException;
import java.io.InputStream;
import com.sun.org.apache.xml.internal.resolver.Catalog;
/**
* The CatalogReader interface.
*
* <p>The Catalog class requires that classes implement this interface
* in order to be used to read catalogs. Examples of CatalogReaders
* include the TextCatalogReader, the SAXCatalogReader, and the
* DOMCatalogReader.</p>
*
* @see Catalog
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public interface CatalogReader {
/**
* Read a catalog from a file.
*
* <p>This class reads a catalog from a URL.</p>
*
* @param catalog The catalog for which this reader is called.
* @param fileUrl The URL of a document to be read.
* @throws MalformedURLException if the specified URL cannot be
* turned into a URL object.
* @throws IOException if the URL cannot be read.
* @throws UnknownCatalogFormatException if the catalog format is
* not recognized.
* @throws UnparseableCatalogException if the catalog cannot be parsed.
* (For example, if it is supposed to be XML and isn't well-formed.)
*/
public void readCatalog(Catalog catalog, String fileUrl)
throws MalformedURLException, IOException, CatalogException;
/**
* Read a catalog from an input stream.
*
* <p>This class reads a catalog from an input stream.</p>
*
* @param catalog The catalog for which this reader is called.
* @param is The input stream that is to be read.
* @throws IOException if the URL cannot be read.
* @throws UnknownCatalogFormatException if the catalog format is
* not recognized.
* @throws UnparseableCatalogException if the catalog cannot be parsed.
* (For example, if it is supposed to be XML and isn't well-formed.)
*/
public void readCatalog(Catalog catalog, InputStream is)
throws IOException, CatalogException;
}

View file

@ -1,47 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.readers;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import org.w3c.dom.Node;
/**
* The DOMCatalogParser interface.
*
* <p>This interface must be implemented in order for a class to
* participate as a parser for the DOMCatalogReader.
*
* @see Catalog
* @see DOMCatalogReader
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public interface DOMCatalogParser {
/**
* Parse a DOM node as a catalog entry.
*
* <p>This method is expected to analyze the specified node and
* construct appropriate catalog entry(ies) from it.</p>
*
* @param catalog The catalog for which this node is being considered.
* @param node The DOM Node from the catalog.
*/
public void parseCatalogEntry(Catalog catalog, Node node);
}

View file

@ -1,240 +0,0 @@
/*
* Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.readers;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import com.sun.org.apache.xml.internal.resolver.CatalogException;
import com.sun.org.apache.xml.internal.resolver.helpers.Namespaces;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import sun.reflect.misc.ReflectUtil;
/**
* A DOM-based CatalogReader.
*
* <p>This class is used to read XML Catalogs using the DOM. This reader
* has an advantage over the SAX-based reader that it can analyze the
* DOM tree rather than simply a series of SAX events. It has the disadvantage
* that it requires all of the code necessary to build and walk a DOM
* tree.</p>
*
* <p>Since the choice of CatalogReaders (in the InputStream case) can only
* be made on the basis of MIME type, the following problem occurs: only
* one CatalogReader can exist for all XML mime types. In order to get
* around this problem, the DOMCatalogReader relies on a set of external
* CatalogParsers to actually build the catalog.</p>
*
* <p>The selection of CatalogParsers is made on the basis of the QName
* of the root element of the document.</p>
*
*
* @see Catalog
* @see CatalogReader
* @see SAXCatalogReader
* @see TextCatalogReader
* @see DOMCatalogParser
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public class DOMCatalogReader implements CatalogReader {
/**
* Mapping table from QNames to CatalogParser classes.
*
* <p>Each key in this hash table has the form "elementname"
* or "{namespaceuri}elementname". The former is used if the
* namespace URI is null.</p>
*/
protected Map<String, String> namespaceMap = new HashMap<>();
/**
* Add a new parser to the reader.
*
* <p>This method associates the specified parserClass with the
* namespaceURI/rootElement names specified.</p>
*
* @param namespaceURI The namespace URI. <em>Not</em> the prefix.
* @param rootElement The name of the root element.
* @param parserClass The name of the parserClass to instantiate
* for this kind of catalog.
*/
public void setCatalogParser(String namespaceURI,
String rootElement,
String parserClass) {
if (namespaceURI == null) {
namespaceMap.put(rootElement, parserClass);
} else {
namespaceMap.put("{"+namespaceURI+"}"+rootElement, parserClass);
}
}
/**
* Get the name of the parser class for a given catalog type.
*
* <p>This method returns the parserClass associated with the
* namespaceURI/rootElement names specified.</p>
*
* @param namespaceURI The namespace URI. <em>Not</em> the prefix.
* @param rootElement The name of the root element.
* @return The parser class.
*/
public String getCatalogParser(String namespaceURI,
String rootElement) {
if (namespaceURI == null) {
return namespaceMap.get(rootElement);
} else {
return namespaceMap.get("{"+namespaceURI+"}"+rootElement);
}
}
/**
* Null constructor; something for subclasses to call.
*/
public DOMCatalogReader() { }
/**
* Read a catalog from an input stream.
*
* <p>This class reads a catalog from an input stream:</p>
*
* <ul>
* <li>Based on the QName of the root element, it determines which
* parser to instantiate for this catalog.</li>
* <li>It constructs a DOM Document from the catalog and</li>
* <li>For each child of the root node, it calls the parser's
* parseCatalogEntry method. This method is expected to make
* appropriate calls back into the catalog to add entries for the
* entries in the catalog. It is free to do this in whatever manner
* is appropriate (perhaps using just the node passed in, perhaps
* wandering arbitrarily throughout the tree).</li>
* </ul>
*
* @param catalog The catalog for which this reader is called.
* @param is The input stream that is to be read.
* @throws IOException if the URL cannot be read.
* @throws UnknownCatalogFormatException if the catalog format is
* not recognized.
* @throws UnparseableCatalogException if the catalog cannot be parsed.
* (For example, if it is supposed to be XML and isn't well-formed or
* if the parser class cannot be instantiated.)
*/
public void readCatalog(Catalog catalog, InputStream is)
throws IOException, CatalogException {
DocumentBuilderFactory factory = null;
DocumentBuilder builder = null;
factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
throw new CatalogException(CatalogException.UNPARSEABLE);
}
Document doc = null;
try {
doc = builder.parse(is);
} catch (SAXException se) {
throw new CatalogException(CatalogException.UNKNOWN_FORMAT);
}
Element root = doc.getDocumentElement();
String namespaceURI = Namespaces.getNamespaceURI(root);
String localName = Namespaces.getLocalName(root);
String domParserClass = getCatalogParser(namespaceURI,
localName);
if (domParserClass == null) {
if (namespaceURI == null) {
catalog.getCatalogManager().debug.message(1, "No Catalog parser for "
+ localName);
} else {
catalog.getCatalogManager().debug.message(1, "No Catalog parser for "
+ "{" + namespaceURI + "}"
+ localName);
}
return;
}
DOMCatalogParser domParser = null;
try {
domParser = (DOMCatalogParser) ReflectUtil.forName(domParserClass).newInstance();
} catch (ClassNotFoundException cnfe) {
catalog.getCatalogManager().debug.message(1, "Cannot load XML Catalog Parser class", domParserClass);
throw new CatalogException(CatalogException.UNPARSEABLE);
} catch (InstantiationException ie) {
catalog.getCatalogManager().debug.message(1, "Cannot instantiate XML Catalog Parser class", domParserClass);
throw new CatalogException(CatalogException.UNPARSEABLE);
} catch (IllegalAccessException iae) {
catalog.getCatalogManager().debug.message(1, "Cannot access XML Catalog Parser class", domParserClass);
throw new CatalogException(CatalogException.UNPARSEABLE);
} catch (ClassCastException cce ) {
catalog.getCatalogManager().debug.message(1, "Cannot cast XML Catalog Parser class", domParserClass);
throw new CatalogException(CatalogException.UNPARSEABLE);
}
Node node = root.getFirstChild();
while (node != null) {
domParser.parseCatalogEntry(catalog, node);
node = node.getNextSibling();
}
}
/**
* Read the catalog behind the specified URL.
*
* @see #readCatalog(Catalog, InputStream)
*
* @param catalog The catalog for which we are reading.
* @param fileUrl The URL of the document that should be read.
*
* @throws MalformedURLException if the specified URL cannot be
* turned into a URL object.
* @throws IOException if the URL cannot be read.
* @throws UnknownCatalogFormatException if the catalog format is
* not recognized.
* @throws UnparseableCatalogException if the catalog cannot be parsed.
* (For example, if it is supposed to be XML and isn't well-formed.)
*/
public void readCatalog(Catalog catalog, String fileUrl)
throws MalformedURLException, IOException, CatalogException {
URL url = new URL(fileUrl);
URLConnection urlCon = url.openConnection();
readCatalog(catalog, urlCon.getInputStream());
}
}

View file

@ -1,181 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.readers;
import java.util.Vector;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import com.sun.org.apache.xml.internal.resolver.Resolver;
import com.sun.org.apache.xml.internal.resolver.CatalogEntry;
import com.sun.org.apache.xml.internal.resolver.CatalogException;
import org.xml.sax.*;
import org.w3c.dom.*;
/**
* Parse Extended OASIS Entity Resolution Technical Committee
* XML Catalog files.
*
* @see Catalog
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public class ExtendedXMLCatalogReader extends OASISXMLCatalogReader {
/** The namespace name of extended catalog elements */
public static final String extendedNamespaceName = "http://nwalsh.com/xcatalog/1.0";
/**
* The SAX <code>startElement</code> method recognizes elements
* from the plain catalog format and instantiates CatalogEntry
* objects for them.
*
* @param namespaceURI The namespace name of the element.
* @param localName The local name of the element.
* @param qName The QName of the element.
* @param atts The list of attributes on the element.
*
* @see CatalogEntry
*/
public void startElement (String namespaceURI,
String localName,
String qName,
Attributes atts)
throws SAXException {
// Check before calling the super because super will report our
// namespace as an extension namespace, but that doesn't count
// for this element.
boolean inExtension = inExtensionNamespace();
super.startElement(namespaceURI, localName, qName, atts);
int entryType = -1;
Vector entryArgs = new Vector();
if (namespaceURI != null && extendedNamespaceName.equals(namespaceURI)
&& !inExtension) {
// This is an Extended XML Catalog entry
if (atts.getValue("xml:base") != null) {
String baseURI = atts.getValue("xml:base");
entryType = Catalog.BASE;
entryArgs.add(baseURI);
baseURIStack.push(baseURI);
debug.message(4, "xml:base", baseURI);
try {
CatalogEntry ce = new CatalogEntry(entryType, entryArgs);
catalog.addEntry(ce);
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) {
debug.message(1, "Invalid catalog entry type", localName);
} else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) {
debug.message(1, "Invalid catalog entry (base)", localName);
}
}
entryType = -1;
entryArgs = new Vector();
} else {
baseURIStack.push(baseURIStack.peek());
}
if (localName.equals("uriSuffix")) {
if (checkAttributes(atts, "suffix", "uri")) {
entryType = Resolver.URISUFFIX;
entryArgs.add(atts.getValue("suffix"));
entryArgs.add(atts.getValue("uri"));
debug.message(4, "uriSuffix",
atts.getValue("suffix"),
atts.getValue("uri"));
}
} else if (localName.equals("systemSuffix")) {
if (checkAttributes(atts, "suffix", "uri")) {
entryType = Resolver.SYSTEMSUFFIX;
entryArgs.add(atts.getValue("suffix"));
entryArgs.add(atts.getValue("uri"));
debug.message(4, "systemSuffix",
atts.getValue("suffix"),
atts.getValue("uri"));
}
} else {
// This is equivalent to an invalid catalog entry type
debug.message(1, "Invalid catalog entry type", localName);
}
if (entryType >= 0) {
try {
CatalogEntry ce = new CatalogEntry(entryType, entryArgs);
catalog.addEntry(ce);
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) {
debug.message(1, "Invalid catalog entry type", localName);
} else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) {
debug.message(1, "Invalid catalog entry", localName);
}
}
}
}
}
/** The SAX <code>endElement</code> method does nothing. */
public void endElement (String namespaceURI,
String localName,
String qName)
throws SAXException {
super.endElement(namespaceURI, localName, qName);
// Check after popping the stack so we don't erroneously think we
// are our own extension namespace...
boolean inExtension = inExtensionNamespace();
int entryType = -1;
Vector entryArgs = new Vector();
if (namespaceURI != null
&& (extendedNamespaceName.equals(namespaceURI))
&& !inExtension) {
String popURI = (String) baseURIStack.pop();
String baseURI = (String) baseURIStack.peek();
if (!baseURI.equals(popURI)) {
entryType = Catalog.BASE;
entryArgs.add(baseURI);
debug.message(4, "(reset) xml:base", baseURI);
try {
CatalogEntry ce = new CatalogEntry(entryType, entryArgs);
catalog.addEntry(ce);
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) {
debug.message(1, "Invalid catalog entry type", localName);
} else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) {
debug.message(1, "Invalid catalog entry (rbase)", localName);
}
}
}
}
}
}

View file

@ -1,546 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.readers;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import com.sun.org.apache.xml.internal.resolver.CatalogEntry;
import com.sun.org.apache.xml.internal.resolver.CatalogException;
import com.sun.org.apache.xml.internal.resolver.helpers.PublicId;
import java.util.Enumeration;
import java.util.Stack;
import java.util.Vector;
import javax.xml.parsers.SAXParserFactory;
import org.w3c.dom.*;
import org.xml.sax.*;
/**
* Parse OASIS Entity Resolution Technical Committee
* XML Catalog files.
*
* @see Catalog
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public class OASISXMLCatalogReader extends SAXCatalogReader implements SAXCatalogParser {
/** The catalog object needs to be stored by the object so that
* SAX callbacks can use it.
*/
protected Catalog catalog = null;
/** The namespace name of OASIS ERTC catalogs */
public static final String namespaceName = "urn:oasis:names:tc:entity:xmlns:xml:catalog";
/** The namespace name of OASIS ERTC TR9401 catalog extension */
public static final String tr9401NamespaceName = "urn:oasis:names:tc:entity:xmlns:tr9401:catalog";
protected Stack baseURIStack = new Stack();
protected Stack overrideStack = new Stack();
protected Stack namespaceStack = new Stack();
/** Set the current catalog. */
public void setCatalog (Catalog catalog) {
this.catalog = catalog;
debug = catalog.getCatalogManager().debug;
}
/** Get the current catalog. */
public Catalog getCatalog () {
return catalog;
}
/** Default constructor */
public OASISXMLCatalogReader() {
super();
}
/** Constructor allowing for providing custom SAX parser factory */
public OASISXMLCatalogReader(SAXParserFactory parserFactory, Catalog catalog) {
super(parserFactory);
setCatalog(catalog);
}
/**
* Are we in an extension namespace?
*
* @return true if the current stack of open namespaces includes
* an extension namespace.
*/
protected boolean inExtensionNamespace() {
boolean inExtension = false;
Enumeration elements = namespaceStack.elements();
while (!inExtension && elements.hasMoreElements()) {
String ns = (String) elements.nextElement();
if (ns == null) {
inExtension = true;
} else {
inExtension = (!ns.equals(tr9401NamespaceName)
&& !ns.equals(namespaceName));
}
}
return inExtension;
}
// ----------------------------------------------------------------------
// Implement the SAX ContentHandler interface
/** The SAX <code>setDocumentLocator</code> method does nothing. */
public void setDocumentLocator (Locator locator) {
return;
}
/** The SAX <code>startDocument</code> */
public void startDocument ()
throws SAXException {
baseURIStack.push(catalog.getCurrentBase());
overrideStack.push(catalog.getDefaultOverride());
return;
}
/** The SAX <code>endDocument</code> method does nothing. */
public void endDocument ()
throws SAXException {
return;
}
/**
* The SAX <code>startElement</code> method recognizes elements
* from the plain catalog format and instantiates CatalogEntry
* objects for them.
*
* @param namespaceURI The namespace name of the element.
* @param localName The local name of the element.
* @param qName The QName of the element.
* @param atts The list of attributes on the element.
*
* @see CatalogEntry
*/
public void startElement (String namespaceURI,
String localName,
String qName,
Attributes atts)
throws SAXException {
int entryType = -1;
Vector entryArgs = new Vector();
namespaceStack.push(namespaceURI);
boolean inExtension = inExtensionNamespace();
if (namespaceURI != null && namespaceName.equals(namespaceURI)
&& !inExtension) {
// This is an XML Catalog entry
if (atts.getValue("xml:base") != null) {
String baseURI = atts.getValue("xml:base");
entryType = Catalog.BASE;
entryArgs.add(baseURI);
baseURIStack.push(baseURI);
debug.message(4, "xml:base", baseURI);
try {
CatalogEntry ce = new CatalogEntry(entryType, entryArgs);
catalog.addEntry(ce);
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) {
debug.message(1, "Invalid catalog entry type", localName);
} else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) {
debug.message(1, "Invalid catalog entry (base)", localName);
}
}
entryType = -1;
entryArgs = new Vector();
} else {
baseURIStack.push(baseURIStack.peek());
}
if ((localName.equals("catalog") || localName.equals("group"))
&& atts.getValue("prefer") != null) {
String override = atts.getValue("prefer");
if (override.equals("public")) {
override = "yes";
} else if (override.equals("system")) {
override = "no";
} else {
debug.message(1,
"Invalid prefer: must be 'system' or 'public'",
localName);
override = catalog.getDefaultOverride();
}
entryType = Catalog.OVERRIDE;
entryArgs.add(override);
overrideStack.push(override);
debug.message(4, "override", override);
try {
CatalogEntry ce = new CatalogEntry(entryType, entryArgs);
catalog.addEntry(ce);
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) {
debug.message(1, "Invalid catalog entry type", localName);
} else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) {
debug.message(1, "Invalid catalog entry (override)", localName);
}
}
entryType = -1;
entryArgs = new Vector();
} else {
overrideStack.push(overrideStack.peek());
}
if (localName.equals("delegatePublic")) {
if (checkAttributes(atts, "publicIdStartString", "catalog")) {
entryType = Catalog.DELEGATE_PUBLIC;
entryArgs.add(atts.getValue("publicIdStartString"));
entryArgs.add(atts.getValue("catalog"));
debug.message(4, "delegatePublic",
PublicId.normalize(atts.getValue("publicIdStartString")),
atts.getValue("catalog"));
}
} else if (localName.equals("delegateSystem")) {
if (checkAttributes(atts, "systemIdStartString", "catalog")) {
entryType = Catalog.DELEGATE_SYSTEM;
entryArgs.add(atts.getValue("systemIdStartString"));
entryArgs.add(atts.getValue("catalog"));
debug.message(4, "delegateSystem",
atts.getValue("systemIdStartString"),
atts.getValue("catalog"));
}
} else if (localName.equals("delegateURI")) {
if (checkAttributes(atts, "uriStartString", "catalog")) {
entryType = Catalog.DELEGATE_URI;
entryArgs.add(atts.getValue("uriStartString"));
entryArgs.add(atts.getValue("catalog"));
debug.message(4, "delegateURI",
atts.getValue("uriStartString"),
atts.getValue("catalog"));
}
} else if (localName.equals("rewriteSystem")) {
if (checkAttributes(atts, "systemIdStartString", "rewritePrefix")) {
entryType = Catalog.REWRITE_SYSTEM;
entryArgs.add(atts.getValue("systemIdStartString"));
entryArgs.add(atts.getValue("rewritePrefix"));
debug.message(4, "rewriteSystem",
atts.getValue("systemIdStartString"),
atts.getValue("rewritePrefix"));
}
} else if (localName.equals("systemSuffix")) {
if (checkAttributes(atts, "systemIdSuffix", "uri")) {
entryType = Catalog.SYSTEM_SUFFIX;
entryArgs.add(atts.getValue("systemIdSuffix"));
entryArgs.add(atts.getValue("uri"));
debug.message(4, "systemSuffix",
atts.getValue("systemIdSuffix"),
atts.getValue("uri"));
}
} else if (localName.equals("rewriteURI")) {
if (checkAttributes(atts, "uriStartString", "rewritePrefix")) {
entryType = Catalog.REWRITE_URI;
entryArgs.add(atts.getValue("uriStartString"));
entryArgs.add(atts.getValue("rewritePrefix"));
debug.message(4, "rewriteURI",
atts.getValue("uriStartString"),
atts.getValue("rewritePrefix"));
}
} else if (localName.equals("uriSuffix")) {
if (checkAttributes(atts, "uriSuffix", "uri")) {
entryType = Catalog.URI_SUFFIX;
entryArgs.add(atts.getValue("uriSuffix"));
entryArgs.add(atts.getValue("uri"));
debug.message(4, "uriSuffix",
atts.getValue("uriSuffix"),
atts.getValue("uri"));
}
} else if (localName.equals("nextCatalog")) {
if (checkAttributes(atts, "catalog")) {
entryType = Catalog.CATALOG;
entryArgs.add(atts.getValue("catalog"));
debug.message(4, "nextCatalog", atts.getValue("catalog"));
}
} else if (localName.equals("public")) {
if (checkAttributes(atts, "publicId", "uri")) {
entryType = Catalog.PUBLIC;
entryArgs.add(atts.getValue("publicId"));
entryArgs.add(atts.getValue("uri"));
debug.message(4, "public",
PublicId.normalize(atts.getValue("publicId")),
atts.getValue("uri"));
}
} else if (localName.equals("system")) {
if (checkAttributes(atts, "systemId", "uri")) {
entryType = Catalog.SYSTEM;
entryArgs.add(atts.getValue("systemId"));
entryArgs.add(atts.getValue("uri"));
debug.message(4, "system",
atts.getValue("systemId"),
atts.getValue("uri"));
}
} else if (localName.equals("uri")) {
if (checkAttributes(atts, "name", "uri")) {
entryType = Catalog.URI;
entryArgs.add(atts.getValue("name"));
entryArgs.add(atts.getValue("uri"));
debug.message(4, "uri",
atts.getValue("name"),
atts.getValue("uri"));
}
} else if (localName.equals("catalog")) {
// nop, start of catalog
} else if (localName.equals("group")) {
// nop, a group
} else {
// This is equivalent to an invalid catalog entry type
debug.message(1, "Invalid catalog entry type", localName);
}
if (entryType >= 0) {
try {
CatalogEntry ce = new CatalogEntry(entryType, entryArgs);
catalog.addEntry(ce);
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) {
debug.message(1, "Invalid catalog entry type", localName);
} else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) {
debug.message(1, "Invalid catalog entry", localName);
}
}
}
}
if (namespaceURI != null && tr9401NamespaceName.equals(namespaceURI)
&& !inExtension) {
// This is a TR9401 Catalog entry
if (atts.getValue("xml:base") != null) {
String baseURI = atts.getValue("xml:base");
entryType = Catalog.BASE;
entryArgs.add(baseURI);
baseURIStack.push(baseURI);
debug.message(4, "xml:base", baseURI);
try {
CatalogEntry ce = new CatalogEntry(entryType, entryArgs);
catalog.addEntry(ce);
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) {
debug.message(1, "Invalid catalog entry type", localName);
} else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) {
debug.message(1, "Invalid catalog entry (base)", localName);
}
}
entryType = -1;
entryArgs = new Vector();
} else {
baseURIStack.push(baseURIStack.peek());
}
if (localName.equals("doctype")) {
entryType = Catalog.DOCTYPE;
entryArgs.add(atts.getValue("name"));
entryArgs.add(atts.getValue("uri"));
} else if (localName.equals("document")) {
entryType = Catalog.DOCUMENT;
entryArgs.add(atts.getValue("uri"));
} else if (localName.equals("dtddecl")) {
entryType = Catalog.DTDDECL;
entryArgs.add(atts.getValue("publicId"));
entryArgs.add(atts.getValue("uri"));
} else if (localName.equals("entity")) {
entryType = Catalog.ENTITY;
entryArgs.add(atts.getValue("name"));
entryArgs.add(atts.getValue("uri"));
} else if (localName.equals("linktype")) {
entryType = Catalog.LINKTYPE;
entryArgs.add(atts.getValue("name"));
entryArgs.add(atts.getValue("uri"));
} else if (localName.equals("notation")) {
entryType = Catalog.NOTATION;
entryArgs.add(atts.getValue("name"));
entryArgs.add(atts.getValue("uri"));
} else if (localName.equals("sgmldecl")) {
entryType = Catalog.SGMLDECL;
entryArgs.add(atts.getValue("uri"));
} else {
// This is equivalent to an invalid catalog entry type
debug.message(1, "Invalid catalog entry type", localName);
}
if (entryType >= 0) {
try {
CatalogEntry ce = new CatalogEntry(entryType, entryArgs);
catalog.addEntry(ce);
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) {
debug.message(1, "Invalid catalog entry type", localName);
} else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) {
debug.message(1, "Invalid catalog entry", localName);
}
}
}
}
}
public boolean checkAttributes (Attributes atts, String attName) {
if (atts.getValue(attName) == null) {
debug.message(1, "Error: required attribute " + attName + " missing.");
return false;
} else {
return true;
}
}
public boolean checkAttributes (Attributes atts,
String attName1,
String attName2) {
return checkAttributes(atts, attName1)
&& checkAttributes(atts, attName2);
}
/** The SAX <code>endElement</code> */
public void endElement (String namespaceURI,
String localName,
String qName)
throws SAXException {
int entryType = -1;
Vector entryArgs = new Vector();
boolean inExtension = inExtensionNamespace();
if (namespaceURI != null
&& !inExtension
&& (namespaceName.equals(namespaceURI)
|| tr9401NamespaceName.equals(namespaceURI))) {
String popURI = (String) baseURIStack.pop();
String baseURI = (String) baseURIStack.peek();
if (!baseURI.equals(popURI)) {
entryType = Catalog.BASE;
entryArgs.add(baseURI);
debug.message(4, "(reset) xml:base", baseURI);
try {
CatalogEntry ce = new CatalogEntry(entryType, entryArgs);
catalog.addEntry(ce);
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) {
debug.message(1, "Invalid catalog entry type", localName);
} else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) {
debug.message(1, "Invalid catalog entry (rbase)", localName);
}
}
}
}
if (namespaceURI != null && namespaceName.equals(namespaceURI)
&& !inExtension) {
if (localName.equals("catalog") || localName.equals("group")) {
String popOverride = (String) overrideStack.pop();
String override = (String) overrideStack.peek();
if (!override.equals(popOverride)) {
entryType = Catalog.OVERRIDE;
entryArgs.add(override);
overrideStack.push(override);
debug.message(4, "(reset) override", override);
try {
CatalogEntry ce = new CatalogEntry(entryType, entryArgs);
catalog.addEntry(ce);
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) {
debug.message(1, "Invalid catalog entry type", localName);
} else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) {
debug.message(1, "Invalid catalog entry (roverride)", localName);
}
}
}
}
}
namespaceStack.pop();
return;
}
/** The SAX <code>characters</code> method does nothing. */
public void characters (char ch[], int start, int length)
throws SAXException {
return;
}
/** The SAX <code>ignorableWhitespace</code> method does nothing. */
public void ignorableWhitespace (char ch[], int start, int length)
throws SAXException {
return;
}
/** The SAX <code>processingInstruction</code> method does nothing. */
public void processingInstruction (String target, String data)
throws SAXException {
return;
}
/** The SAX <code>skippedEntity</code> method does nothing. */
public void skippedEntity (String name)
throws SAXException {
return;
}
/** The SAX <code>startPrefixMapping</code> method does nothing. */
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
return;
}
/** The SAX <code>endPrefixMapping</code> method does nothing. */
public void endPrefixMapping(String prefix)
throws SAXException {
return;
}
}

View file

@ -1,39 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.readers;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import org.xml.sax.*;
/**
* The SAXCatalogParser interface.
*
* <p>This interface must be implemented in order for a class to
* participate as a parser for the SAXCatalogReader.
*
* @see Catalog
* @see SAXCatalogReader
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public interface SAXCatalogParser extends ContentHandler, DocumentHandler {
/** Set the Catalog for which parsing is being performed. */
public void setCatalog(Catalog catalog);
}

View file

@ -1,503 +0,0 @@
/*
* Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.readers;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import com.sun.org.apache.xml.internal.resolver.CatalogException;
import com.sun.org.apache.xml.internal.resolver.CatalogManager;
import com.sun.org.apache.xml.internal.resolver.helpers.Debug;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.AttributeList;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.DocumentHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.Parser;
import org.xml.sax.SAXException;
import sun.reflect.misc.ReflectUtil;
/**
* A SAX-based CatalogReader.
*
* <p>This class is used to read XML Catalogs using the SAX. This reader
* has an advantage over the DOM-based reader in that it functions on
* the stream of SAX events. It has the disadvantage
* that it cannot look around in the tree.</p>
*
* <p>Since the choice of CatalogReaders (in the InputStream case) can only
* be made on the basis of MIME type, the following problem occurs: only
* one CatalogReader can exist for all XML mime types. In order to get
* around this problem, the SAXCatalogReader relies on a set of external
* CatalogParsers to actually build the catalog.</p>
*
* <p>The selection of CatalogParsers is made on the basis of the QName
* of the root element of the document.</p>
*
* @see Catalog
* @see CatalogReader
* @see SAXCatalogReader
* @see TextCatalogReader
* @see DOMCatalogParser
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public class SAXCatalogReader implements CatalogReader, ContentHandler, DocumentHandler {
/** The SAX Parser Factory */
protected SAXParserFactory parserFactory = null;
/** The SAX Parser Class */
protected String parserClass = null;
/**
* Mapping table from QNames to CatalogParser classes.
*
* <p>Each key in this hash table has the form "elementname"
* or "{namespaceuri}elementname". The former is used if the
* namespace URI is null.</p>
*/
protected Map<String, String> namespaceMap = new HashMap<>();
/** The parser in use for the current catalog. */
private SAXCatalogParser saxParser = null;
/** Set if something goes horribly wrong. It allows the class to
* ignore the rest of the events that are received.
*/
private boolean abandonHope = false;
/** The Catalog that we're working for. */
private Catalog catalog;
/** Set the XML SAX Parser Factory.
*/
public void setParserFactory(SAXParserFactory parserFactory) {
this.parserFactory = parserFactory;
}
/** Set the XML SAX Parser Class
*/
public void setParserClass(String parserClass) {
this.parserClass = parserClass;
}
/** Get the parser factory currently in use. */
public SAXParserFactory getParserFactory() {
return parserFactory;
}
/** Get the parser class currently in use. */
public String getParserClass() {
return parserClass;
}
/** The debug class to use for this reader.
*
* This is a bit of a hack. Anyway, whenever we read for a catalog,
* we extract the debug object
* from the catalog's manager so that we can use it to print messages.
*
* In production, we don't really expect any messages so it doesn't
* really matter. But it's still a bit of a hack.
*/
protected Debug debug = CatalogManager.getStaticManager().debug;
/** The constructor */
public SAXCatalogReader() {
parserFactory = null;
parserClass = null;
}
/** The constructor */
public SAXCatalogReader(SAXParserFactory parserFactory) {
this.parserFactory = parserFactory;
}
/** The constructor */
public SAXCatalogReader(String parserClass) {
this.parserClass = parserClass;
}
/**
* Set the SAXCatalogParser class for the given namespace/root
* element type.
*/
public void setCatalogParser(String namespaceURI,
String rootElement,
String parserClass) {
namespaceURI = namespaceURI != null ? namespaceURI.trim() : "";
namespaceMap.put("{"+namespaceURI+"}"+rootElement, parserClass);
}
/**
* Get the SAXCatalogParser class for the given namespace/root
* element type.
*/
public String getCatalogParser(String namespaceURI,
String rootElement) {
namespaceURI = namespaceURI != null ? namespaceURI.trim() : "";
return namespaceMap.get("{"+namespaceURI+"}"+rootElement);
}
/**
* Parse an XML Catalog file.
*
* @param catalog The catalog to which this catalog file belongs
* @param fileUrl The URL or filename of the catalog file to process
*
* @throws MalformedURLException Improper fileUrl
* @throws IOException Error reading catalog file
*/
public void readCatalog(Catalog catalog, String fileUrl)
throws MalformedURLException, IOException,
CatalogException {
URL url = null;
try {
url = new URL(fileUrl);
} catch (MalformedURLException e) {
url = new URL("file:///" + fileUrl);
}
debug = catalog.getCatalogManager().debug;
try {
URLConnection urlCon = url.openConnection();
readCatalog(catalog, urlCon.getInputStream());
} catch (FileNotFoundException e) {
catalog.getCatalogManager().debug.message(1, "Failed to load catalog, file not found",
url.toString());
}
}
/**
* Parse an XML Catalog stream.
*
* @param catalog The catalog to which this catalog file belongs
* @param is The input stream from which the catalog will be read
*
* @throws MalformedURLException Improper fileUrl
* @throws IOException Error reading catalog file
* @throws CatalogException A Catalog exception
*/
public void readCatalog(Catalog catalog, InputStream is)
throws IOException, CatalogException {
// Create an instance of the parser
if (parserFactory == null && parserClass == null) {
debug.message(1, "Cannot read SAX catalog without a parser");
throw new CatalogException(CatalogException.UNPARSEABLE);
}
debug = catalog.getCatalogManager().debug;
EntityResolver bResolver = catalog.getCatalogManager().getBootstrapResolver();
this.catalog = catalog;
try {
if (parserFactory != null) {
SAXParser parser = parserFactory.newSAXParser();
SAXParserHandler spHandler = new SAXParserHandler();
spHandler.setContentHandler(this);
if (bResolver != null) {
spHandler.setEntityResolver(bResolver);
}
parser.parse(new InputSource(is), spHandler);
} else {
Class<?> c = ReflectUtil.forName(parserClass);
if (!Parser.class.isAssignableFrom(c)) {
throw new ClassCastException(parserClass
+ " cannot be cast to "
+ Parser.class.getName());
}
Parser parser = (Parser) c.newInstance();
parser.setDocumentHandler(this);
if (bResolver != null) {
parser.setEntityResolver(bResolver);
}
parser.parse(new InputSource(is));
}
} catch (ClassNotFoundException cnfe) {
throw new CatalogException(CatalogException.UNPARSEABLE);
} catch (IllegalAccessException iae) {
throw new CatalogException(CatalogException.UNPARSEABLE);
} catch (InstantiationException ie) {
throw new CatalogException(CatalogException.UNPARSEABLE);
} catch (ParserConfigurationException pce) {
throw new CatalogException(CatalogException.UNKNOWN_FORMAT);
} catch (SAXException se) {
Exception e = se.getException();
// FIXME: there must be a better way
UnknownHostException uhe = new UnknownHostException();
FileNotFoundException fnfe = new FileNotFoundException();
if (e != null) {
if (e.getClass() == uhe.getClass()) {
throw new CatalogException(CatalogException.PARSE_FAILED,
e.toString());
} else if (e.getClass() == fnfe.getClass()) {
throw new CatalogException(CatalogException.PARSE_FAILED,
e.toString());
}
}
throw new CatalogException(se);
}
}
// ----------------------------------------------------------------------
// Implement the SAX ContentHandler interface
/** The SAX <code>setDocumentLocator</code> method. Does nothing. */
public void setDocumentLocator (Locator locator) {
if (saxParser != null) {
saxParser.setDocumentLocator(locator);
}
}
/** The SAX <code>startDocument</code> method. Does nothing. */
public void startDocument () throws SAXException {
saxParser = null;
abandonHope = false;
return;
}
/** The SAX <code>endDocument</code> method. Does nothing. */
public void endDocument ()throws SAXException {
if (saxParser != null) {
saxParser.endDocument();
}
}
/**
* The SAX <code>startElement</code> method.
*
* <p>The catalog parser is selected based on the namespace of the
* first element encountered in the catalog.</p>
*/
public void startElement (String name,
AttributeList atts)
throws SAXException {
if (abandonHope) {
return;
}
if (saxParser == null) {
String prefix = "";
if (name.indexOf(':') > 0) {
prefix = name.substring(0, name.indexOf(':'));
}
String localName = name;
if (localName.indexOf(':') > 0) {
localName = localName.substring(localName.indexOf(':')+1);
}
String namespaceURI = null;
if (prefix.length() == 0) {
namespaceURI = atts.getValue("xmlns");
} else {
namespaceURI = atts.getValue("xmlns:" + prefix);
}
String saxParserClass = getCatalogParser(namespaceURI,
localName);
if (saxParserClass == null) {
abandonHope = true;
if (namespaceURI == null) {
debug.message(2, "No Catalog parser for " + name);
} else {
debug.message(2, "No Catalog parser for "
+ "{" + namespaceURI + "}"
+ name);
}
return;
}
try {
saxParser = (SAXCatalogParser)
ReflectUtil.forName(saxParserClass).newInstance();
saxParser.setCatalog(catalog);
saxParser.startDocument();
saxParser.startElement(name, atts);
} catch (ClassNotFoundException cnfe) {
saxParser = null;
abandonHope = true;
debug.message(2, cnfe.toString());
} catch (InstantiationException ie) {
saxParser = null;
abandonHope = true;
debug.message(2, ie.toString());
} catch (IllegalAccessException iae) {
saxParser = null;
abandonHope = true;
debug.message(2, iae.toString());
} catch (ClassCastException cce ) {
saxParser = null;
abandonHope = true;
debug.message(2, cce.toString());
}
} else {
saxParser.startElement(name, atts);
}
}
/**
* The SAX2 <code>startElement</code> method.
*
* <p>The catalog parser is selected based on the namespace of the
* first element encountered in the catalog.</p>
*/
public void startElement (String namespaceURI,
String localName,
String qName,
Attributes atts)
throws SAXException {
if (abandonHope) {
return;
}
if (saxParser == null) {
String saxParserClass = getCatalogParser(namespaceURI,
localName);
if (saxParserClass == null) {
abandonHope = true;
if (namespaceURI == null) {
debug.message(2, "No Catalog parser for " + localName);
} else {
debug.message(2, "No Catalog parser for "
+ "{" + namespaceURI + "}"
+ localName);
}
return;
}
try {
saxParser = (SAXCatalogParser)
ReflectUtil.forName(saxParserClass).newInstance();
saxParser.setCatalog(catalog);
saxParser.startDocument();
saxParser.startElement(namespaceURI, localName, qName, atts);
} catch (ClassNotFoundException cnfe) {
saxParser = null;
abandonHope = true;
debug.message(2, cnfe.toString());
} catch (InstantiationException ie) {
saxParser = null;
abandonHope = true;
debug.message(2, ie.toString());
} catch (IllegalAccessException iae) {
saxParser = null;
abandonHope = true;
debug.message(2, iae.toString());
} catch (ClassCastException cce ) {
saxParser = null;
abandonHope = true;
debug.message(2, cce.toString());
}
} else {
saxParser.startElement(namespaceURI, localName, qName, atts);
}
}
/** The SAX <code>endElement</code> method. Does nothing. */
public void endElement (String name) throws SAXException {
if (saxParser != null) {
saxParser.endElement(name);
}
}
/** The SAX2 <code>endElement</code> method. Does nothing. */
public void endElement (String namespaceURI,
String localName,
String qName) throws SAXException {
if (saxParser != null) {
saxParser.endElement(namespaceURI, localName, qName);
}
}
/** The SAX <code>characters</code> method. Does nothing. */
public void characters (char ch[], int start, int length)
throws SAXException {
if (saxParser != null) {
saxParser.characters(ch, start, length);
}
}
/** The SAX <code>ignorableWhitespace</code> method. Does nothing. */
public void ignorableWhitespace (char ch[], int start, int length)
throws SAXException {
if (saxParser != null) {
saxParser.ignorableWhitespace(ch, start, length);
}
}
/** The SAX <code>processingInstruction</code> method. Does nothing. */
public void processingInstruction (String target, String data)
throws SAXException {
if (saxParser != null) {
saxParser.processingInstruction(target, data);
}
}
/** The SAX <code>startPrefixMapping</code> method. Does nothing. */
public void startPrefixMapping (String prefix, String uri)
throws SAXException {
if (saxParser != null) {
saxParser.startPrefixMapping (prefix, uri);
}
}
/** The SAX <code>endPrefixMapping</code> method. Does nothing. */
public void endPrefixMapping (String prefix)
throws SAXException {
if (saxParser != null) {
saxParser.endPrefixMapping (prefix);
}
}
/** The SAX <code>skippedentity</code> method. Does nothing. */
public void skippedEntity (String name)
throws SAXException {
if (saxParser != null) {
saxParser.skippedEntity(name);
}
}
}

View file

@ -1,144 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.readers;
import java.io.IOException;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
/**
* An entity-resolving DefaultHandler.
*
* <p>This class provides a SAXParser DefaultHandler that performs
* entity resolution.
* </p>
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*/
public class SAXParserHandler extends DefaultHandler {
private EntityResolver er = null;
private ContentHandler ch = null;
public SAXParserHandler() {
super();
}
public void setEntityResolver(EntityResolver er) {
this.er = er;
}
public void setContentHandler(ContentHandler ch) {
this.ch = ch;
}
// Entity Resolver
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException {
if (er != null) {
try {
return er.resolveEntity(publicId, systemId);
} catch (IOException e) {
System.out.println("resolveEntity threw IOException!");
return null;
}
} else {
return null;
}
}
// Content Handler
public void characters(char[] ch, int start, int length)
throws SAXException {
if (this.ch != null) {
this.ch.characters(ch, start, length);
}
}
public void endDocument()
throws SAXException {
if (ch != null) {
ch.endDocument();
}
}
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (ch != null) {
ch.endElement(namespaceURI, localName, qName);
}
}
public void endPrefixMapping(String prefix)
throws SAXException {
if (ch != null) {
ch.endPrefixMapping(prefix);
}
}
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
if (this.ch != null) {
this.ch.ignorableWhitespace(ch, start, length);
}
}
public void processingInstruction(String target, String data)
throws SAXException {
if (ch != null) {
ch.processingInstruction(target, data);
}
}
public void setDocumentLocator(Locator locator) {
if (ch != null) {
ch.setDocumentLocator(locator);
}
}
public void skippedEntity(String name)
throws SAXException {
if (ch != null) {
ch.skippedEntity(name);
}
}
public void startDocument()
throws SAXException {
if (ch != null) {
ch.startDocument();
}
}
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts)
throws SAXException {
if (ch != null) {
ch.startElement(namespaceURI, localName, qName, atts);
}
}
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
if (ch != null) {
ch.startPrefixMapping(prefix, uri);
}
}
}

View file

@ -1,138 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.readers;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import com.sun.org.apache.xml.internal.resolver.CatalogEntry;
import com.sun.org.apache.xml.internal.resolver.CatalogException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.Locale;
import java.util.Vector;
/**
* Parses OASIS Open Catalog files.
*
* <p>This class reads OASIS Open Catalog files, returning a stream
* of tokens.</p>
*
* <p>This code interrogates the following non-standard system properties:</p>
*
* <dl>
* <dt><b>xml.catalog.debug</b></dt>
* <dd><p>Sets the debug level. A value of 0 is assumed if the
* property is not set or is not a number.</p></dd>
* </dl>
*
* @see Catalog
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public class TR9401CatalogReader extends TextCatalogReader {
/**
* Start parsing an OASIS TR9401 Open Catalog file. The file is
* actually read and parsed
* as needed by <code>nextEntry</code>.
*
* <p>In a TR9401 Catalog the 'DELEGATE' entry delegates public
* identifiers. There is no delegate entry for system identifiers
* or URIs.</p>
*
* @param catalog The Catalog to populate
* @param is The input stream from which to read the TR9401 Catalog
*
* @throws MalformedURLException Improper fileUrl
* @throws IOException Error reading catalog file
*/
public void readCatalog(Catalog catalog, InputStream is)
throws MalformedURLException, IOException {
catfile = is;
if (catfile == null) {
return;
}
Vector unknownEntry = null;
try {
while (true) {
String token = nextToken();
if (token == null) {
if (unknownEntry != null) {
catalog.unknownEntry(unknownEntry);
unknownEntry = null;
}
catfile.close();
catfile = null;
return;
}
String entryToken = null;
if (caseSensitive) {
entryToken = token;
} else {
entryToken = token.toUpperCase(Locale.ENGLISH);
}
if (entryToken.equals("DELEGATE")) {
entryToken = "DELEGATE_PUBLIC";
}
try {
int type = CatalogEntry.getEntryType(entryToken);
int numArgs = CatalogEntry.getEntryArgCount(type);
Vector args = new Vector();
if (unknownEntry != null) {
catalog.unknownEntry(unknownEntry);
unknownEntry = null;
}
for (int count = 0; count < numArgs; count++) {
args.addElement(nextToken());
}
catalog.addEntry(new CatalogEntry(entryToken, args));
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) {
if (unknownEntry == null) {
unknownEntry = new Vector();
}
unknownEntry.addElement(token);
} else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) {
catalog.getCatalogManager().debug.message(1, "Invalid catalog entry", token);
unknownEntry = null;
} else if (cex.getExceptionType() == CatalogException.UNENDED_COMMENT) {
catalog.getCatalogManager().debug.message(1, cex.getMessage());
}
}
}
} catch (CatalogException cex2) {
if (cex2.getExceptionType() == CatalogException.UNENDED_COMMENT) {
catalog.getCatalogManager().debug.message(1, cex2.getMessage());
}
}
}
}

View file

@ -1,298 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.readers;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import com.sun.org.apache.xml.internal.resolver.CatalogEntry;
import com.sun.org.apache.xml.internal.resolver.CatalogException;
import com.sun.org.apache.xml.internal.resolver.readers.CatalogReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;
import java.util.Stack;
import java.util.Vector;
/**
* Parses plain text Catalog files.
*
* <p>This class reads plain text Open Catalog files.</p>
*
* @see Catalog
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public class TextCatalogReader implements CatalogReader {
/** The input stream used to read the catalog */
protected InputStream catfile = null;
/**
* Character lookahead stack. Reading a catalog sometimes requires
* up to two characters of lookahead.
*/
protected int[] stack = new int[3];
/**
* Token stack. Recognizing an unexpected catalog entry requires
* the ability to "push back" a token.
*/
protected Stack tokenStack = new Stack();
/** The current position on the lookahead stack */
protected int top = -1;
/** Are keywords in the catalog case sensitive? */
protected boolean caseSensitive = false;
/**
* Construct a CatalogReader object.
*/
public TextCatalogReader() { }
public void setCaseSensitive(boolean isCaseSensitive) {
caseSensitive = isCaseSensitive;
}
public boolean getCaseSensitive() {
return caseSensitive;
}
/**
* Start parsing a text catalog file. The file is
* actually read and parsed
* as needed by <code>nextEntry</code>.</p>
*
* @param fileUrl The URL or filename of the catalog file to process
*
* @throws MalformedURLException Improper fileUrl
* @throws IOException Error reading catalog file
*/
public void readCatalog(Catalog catalog, String fileUrl)
throws MalformedURLException, IOException {
URL catURL = null;
try {
catURL = new URL(fileUrl);
} catch (MalformedURLException e) {
catURL = new URL("file:///" + fileUrl);
}
URLConnection urlCon = catURL.openConnection();
try {
readCatalog(catalog, urlCon.getInputStream());
} catch (FileNotFoundException e) {
catalog.getCatalogManager().debug.message(1, "Failed to load catalog, file not found",
catURL.toString());
}
}
public void readCatalog(Catalog catalog, InputStream is)
throws MalformedURLException, IOException {
catfile = is;
if (catfile == null) {
return;
}
Vector unknownEntry = null;
try {
while (true) {
String token = nextToken();
if (token == null) {
if (unknownEntry != null) {
catalog.unknownEntry(unknownEntry);
unknownEntry = null;
}
catfile.close();
catfile = null;
return;
}
String entryToken = null;
if (caseSensitive) {
entryToken = token;
} else {
entryToken = token.toUpperCase(Locale.ENGLISH);
}
try {
int type = CatalogEntry.getEntryType(entryToken);
int numArgs = CatalogEntry.getEntryArgCount(type);
Vector args = new Vector();
if (unknownEntry != null) {
catalog.unknownEntry(unknownEntry);
unknownEntry = null;
}
for (int count = 0; count < numArgs; count++) {
args.addElement(nextToken());
}
catalog.addEntry(new CatalogEntry(entryToken, args));
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) {
if (unknownEntry == null) {
unknownEntry = new Vector();
}
unknownEntry.addElement(token);
} else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) {
catalog.getCatalogManager().debug.message(1, "Invalid catalog entry", token);
unknownEntry = null;
} else if (cex.getExceptionType() == CatalogException.UNENDED_COMMENT) {
catalog.getCatalogManager().debug.message(1, cex.getMessage());
}
}
}
} catch (CatalogException cex2) {
if (cex2.getExceptionType() == CatalogException.UNENDED_COMMENT) {
catalog.getCatalogManager().debug.message(1, cex2.getMessage());
}
}
}
/**
* The destructor.
*
* <p>Makes sure the catalog file is closed.</p>
*/
protected void finalize() {
if (catfile != null) {
try {
catfile.close();
} catch (IOException e) {
// whatever...
}
}
catfile = null;
}
// -----------------------------------------------------------------
/**
* Return the next token in the catalog file.
*
* <p>FYI: This code does not throw any sort of exception for
* a file that contains an n
*
* @return The Catalog file token from the input stream.
* @throws IOException If an error occurs reading from the stream.
*/
protected String nextToken() throws IOException, CatalogException {
String token = "";
int ch, nextch;
if (!tokenStack.empty()) {
return (String) tokenStack.pop();
}
// Skip over leading whitespace and comments
while (true) {
// skip leading whitespace
ch = catfile.read();
while (ch <= ' ') { // all ctrls are whitespace
ch = catfile.read();
if (ch < 0) {
return null;
}
}
// now 'ch' is the current char from the file
nextch = catfile.read();
if (nextch < 0) {
return null;
}
if (ch == '-' && nextch == '-') {
// we've found a comment, skip it...
ch = ' ';
nextch = nextChar();
while ((ch != '-' || nextch != '-') && nextch > 0) {
ch = nextch;
nextch = nextChar();
}
if (nextch < 0) {
throw new CatalogException(CatalogException.UNENDED_COMMENT,
"Unterminated comment in catalog file; EOF treated as end-of-comment.");
}
// Ok, we've found the end of the comment,
// loop back to the top and start again...
} else {
stack[++top] = nextch;
stack[++top] = ch;
break;
}
}
ch = nextChar();
if (ch == '"' || ch == '\'') {
int quote = ch;
while ((ch = nextChar()) != quote) {
char[] chararr = new char[1];
chararr[0] = (char) ch;
String s = new String(chararr);
token = token.concat(s);
}
return token;
} else {
// return the next whitespace or comment delimited
// string
while (ch > ' ') {
nextch = nextChar();
if (ch == '-' && nextch == '-') {
stack[++top] = ch;
stack[++top] = nextch;
return token;
} else {
char[] chararr = new char[1];
chararr[0] = (char) ch;
String s = new String(chararr);
token = token.concat(s);
ch = nextch;
}
}
return token;
}
}
/**
* Return the next logical character from the input stream.
*
* @return The next (logical) character from the input stream. The
* character may be buffered from a previous lookahead.
*
* @throws IOException If an error occurs reading from the stream.
*/
protected int nextChar() throws IOException {
if (top < 0) {
return catfile.read();
} else {
return stack[top--];
}
}
}

View file

@ -1,208 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.readers;
import java.util.Vector;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import com.sun.org.apache.xml.internal.resolver.CatalogEntry;
import com.sun.org.apache.xml.internal.resolver.CatalogException;
import com.sun.org.apache.xml.internal.resolver.helpers.PublicId;
import org.xml.sax.*;
import javax.xml.parsers.*;
/**
* Parse "XCatalog" XML Catalog files, this is the XML Catalog format
* developed by John Cowan and supported by Apache.
*
* @see Catalog
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
*/
public class XCatalogReader extends SAXCatalogReader implements SAXCatalogParser {
/** The catalog object needs to be stored by the object so that
* SAX callbacks can use it.
*/
protected Catalog catalog = null;
/** Set the current catalog. */
public void setCatalog (Catalog catalog) {
this.catalog = catalog;
debug = catalog.getCatalogManager().debug;
}
/** Get the current catalog. */
public Catalog getCatalog () {
return catalog;
}
/** Default constructor */
public XCatalogReader() {
super();
}
/** Constructor allowing for providing custom SAX parser factory */
public XCatalogReader(SAXParserFactory parserFactory, Catalog catalog) {
super(parserFactory);
setCatalog(catalog);
}
// ----------------------------------------------------------------------
// Implement the SAX ContentHandler interface
/** The SAX <code>setDocumentLocator</code> method does nothing. */
public void setDocumentLocator (Locator locator) {
return;
}
/** The SAX <code>startDocument</code> method does nothing. */
public void startDocument ()
throws SAXException {
return;
}
/** The SAX <code>endDocument</code> method does nothing. */
public void endDocument ()
throws SAXException {
return;
}
/**
* The SAX <code>startElement</code> method recognizes elements
* from the plain catalog format and instantiates CatalogEntry
* objects for them.
*
* @param namespaceURI The namespace name of the element.
* @param localName The local name of the element.
* @param qName The QName of the element.
* @param atts The list of attributes on the element.
*
* @see CatalogEntry
*/
public void startElement (String namespaceURI,
String localName,
String qName,
Attributes atts)
throws SAXException {
int entryType = -1;
Vector entryArgs = new Vector();
if (localName.equals("Base")) {
entryType = Catalog.BASE;
entryArgs.add(atts.getValue("HRef"));
debug.message(4, "Base", atts.getValue("HRef"));
} else if (localName.equals("Delegate")) {
entryType = Catalog.DELEGATE_PUBLIC;
entryArgs.add(atts.getValue("PublicID"));
entryArgs.add(atts.getValue("HRef"));
debug.message(4, "Delegate",
PublicId.normalize(atts.getValue("PublicID")),
atts.getValue("HRef"));
} else if (localName.equals("Extend")) {
entryType = Catalog.CATALOG;
entryArgs.add(atts.getValue("HRef"));
debug.message(4, "Extend", atts.getValue("HRef"));
} else if (localName.equals("Map")) {
entryType = Catalog.PUBLIC;
entryArgs.add(atts.getValue("PublicID"));
entryArgs.add(atts.getValue("HRef"));
debug.message(4, "Map",
PublicId.normalize(atts.getValue("PublicID")),
atts.getValue("HRef"));
} else if (localName.equals("Remap")) {
entryType = Catalog.SYSTEM;
entryArgs.add(atts.getValue("SystemID"));
entryArgs.add(atts.getValue("HRef"));
debug.message(4, "Remap",
atts.getValue("SystemID"),
atts.getValue("HRef"));
} else if (localName.equals("XCatalog")) {
// nop, start of catalog
} else {
// This is equivalent to an invalid catalog entry type
debug.message(1, "Invalid catalog entry type", localName);
}
if (entryType >= 0) {
try {
CatalogEntry ce = new CatalogEntry(entryType, entryArgs);
catalog.addEntry(ce);
} catch (CatalogException cex) {
if (cex.getExceptionType() == CatalogException.INVALID_ENTRY_TYPE) {
debug.message(1, "Invalid catalog entry type", localName);
} else if (cex.getExceptionType() == CatalogException.INVALID_ENTRY) {
debug.message(1, "Invalid catalog entry", localName);
}
}
}
}
/** The SAX <code>endElement</code> method does nothing. */
public void endElement (String namespaceURI,
String localName,
String qName)
throws SAXException {
return;
}
/** The SAX <code>characters</code> method does nothing. */
public void characters (char ch[], int start, int length)
throws SAXException {
return;
}
/** The SAX <code>ignorableWhitespace</code> method does nothing. */
public void ignorableWhitespace (char ch[], int start, int length)
throws SAXException {
return;
}
/** The SAX <code>processingInstruction</code> method does nothing. */
public void processingInstruction (String target, String data)
throws SAXException {
return;
}
/** The SAX <code>skippedEntity</code> method does nothing. */
public void skippedEntity (String name)
throws SAXException {
return;
}
/** The SAX <code>startPrefixMapping</code> method does nothing. */
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
return;
}
/** The SAX <code>endPrefixMapping</code> method does nothing. */
public void endPrefixMapping(String prefix)
throws SAXException {
return;
}
}

View file

@ -1,349 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.tools;
import com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.MalformedURLException;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import org.xml.sax.EntityResolver;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
import javax.xml.transform.TransformerException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import com.sun.org.apache.xml.internal.resolver.CatalogManager;
import com.sun.org.apache.xml.internal.resolver.helpers.FileURL;
/**
* A SAX EntityResolver/JAXP URIResolver that uses catalogs.
*
* <p>This class implements both a SAX EntityResolver and a JAXP URIResolver.
* </p>
*
* <p>This resolver understands OASIS TR9401 catalogs, XCatalogs, and the
* current working draft of the OASIS Entity Resolution Technical
* Committee specification.</p>
*
* @see Catalog
* @see org.xml.sax.EntityResolver
* @see javax.xml.transform.URIResolver
* @deprecated The JDK internal Catalog API in package
* {@code com.sun.org.apache.xml.internal.resolver}
* is encapsulated in JDK 9. The entire implementation under the package is now
* deprecated and subject to removal in a future release. Users of the API
* should migrate to the {@linkplain javax.xml.catalog new public API}.
* <p>
* The new Catalog API is supported throughout the JDK XML Processors, which allows
* the use of Catalog by simply setting a path to a Catalog file as a property.
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
* @version 1.0
*/
@Deprecated(since="9", forRemoval=true)
public class CatalogResolver implements EntityResolver, URIResolver {
/** Make the parser Namespace aware? */
public boolean namespaceAware = true;
/** Make the parser validating? */
public boolean validating = false;
/** The underlying catalog */
private Catalog catalog = null;
/** The catalog manager */
private CatalogManager catalogManager = CatalogManager.getStaticManager();
/** Constructor */
public CatalogResolver() {
initializeCatalogs(false);
}
/** Constructor */
public CatalogResolver(boolean privateCatalog) {
initializeCatalogs(privateCatalog);
}
/** Constructor */
public CatalogResolver(CatalogManager manager) {
catalogManager = manager;
initializeCatalogs(!catalogManager.getUseStaticCatalog());
}
/** Initialize catalog */
private void initializeCatalogs(boolean privateCatalog) {
catalog = catalogManager.getCatalog();
}
/** Return the underlying catalog */
public Catalog getCatalog() {
return catalog;
}
/**
* Implements the guts of the <code>resolveEntity</code> method
* for the SAX interface.
*
* <p>Presented with an optional public identifier and a system
* identifier, this function attempts to locate a mapping in the
* catalogs.</p>
*
* <p>If such a mapping is found, it is returned. If no mapping is
* found, null is returned.</p>
*
* @param publicId The public identifier for the entity in question.
* This may be null.
*
* @param systemId The system identifier for the entity in question.
* XML requires a system identifier on all external entities, so this
* value is always specified.
*
* @return The resolved identifier (a URI reference).
*/
public String getResolvedEntity (String publicId, String systemId) {
String resolved = null;
if (catalog == null) {
catalogManager.debug.message(1, "Catalog resolution attempted with null catalog; ignored");
return null;
}
if (systemId != null) {
try {
resolved = catalog.resolveSystem(systemId);
} catch (MalformedURLException me) {
catalogManager.debug.message(1, "Malformed URL exception trying to resolve",
publicId);
resolved = null;
} catch (IOException ie) {
catalogManager.debug.message(1, "I/O exception trying to resolve", publicId);
resolved = null;
}
}
if (resolved == null) {
if (publicId != null) {
try {
resolved = catalog.resolvePublic(publicId, systemId);
} catch (MalformedURLException me) {
catalogManager.debug.message(1, "Malformed URL exception trying to resolve",
publicId);
} catch (IOException ie) {
catalogManager.debug.message(1, "I/O exception trying to resolve", publicId);
}
}
if (resolved != null) {
catalogManager.debug.message(2, "Resolved public", publicId, resolved);
}
} else {
catalogManager.debug.message(2, "Resolved system", systemId, resolved);
}
return resolved;
}
/**
* Implements the <code>resolveEntity</code> method
* for the SAX interface.
*
* <p>Presented with an optional public identifier and a system
* identifier, this function attempts to locate a mapping in the
* catalogs.</p>
*
* <p>If such a mapping is found, the resolver attempts to open
* the mapped value as an InputSource and return it. Exceptions are
* ignored and null is returned if the mapped value cannot be opened
* as an input source.</p>
*
* <p>If no mapping is found (or an error occurs attempting to open
* the mapped value as an input source), null is returned and the system
* will use the specified system identifier as if no entityResolver
* was specified.</p>
*
* @param publicId The public identifier for the entity in question.
* This may be null.
*
* @param systemId The system identifier for the entity in question.
* XML requires a system identifier on all external entities, so this
* value is always specified.
*
* @return An InputSource for the mapped identifier, or null.
*/
public InputSource resolveEntity (String publicId, String systemId) {
String resolved = getResolvedEntity(publicId, systemId);
if (resolved != null) {
try {
InputSource iSource = new InputSource(resolved);
iSource.setPublicId(publicId);
// Ideally this method would not attempt to open the
// InputStream, but there is a bug (in Xerces, at least)
// that causes the parser to mistakenly open the wrong
// system identifier if the returned InputSource does
// not have a byteStream.
//
// It could be argued that we still shouldn't do this here,
// but since the purpose of calling the entityResolver is
// almost certainly to open the input stream, it seems to
// do little harm.
//
URL url = new URL(resolved);
InputStream iStream = url.openStream();
iSource.setByteStream(iStream);
return iSource;
} catch (Exception e) {
catalogManager.debug.message(1,
"Failed to create InputSource ("
+ e.toString()
+ ")", resolved);
return null;
}
}
return null;
}
/** JAXP URIResolver API */
public Source resolve(String href, String base)
throws TransformerException {
String uri = href;
String fragment = null;
int hashPos = href.indexOf("#");
if (hashPos >= 0) {
uri = href.substring(0, hashPos);
fragment = href.substring(hashPos+1);
}
String result = null;
try {
result = catalog.resolveURI(href);
} catch (Exception e) {
// nop;
}
if (result == null) {
try {
URL url = null;
if (base==null) {
url = new URL(uri);
result = url.toString();
} else {
URL baseURL = new URL(base);
url = (href.length()==0 ? baseURL : new URL(baseURL, uri));
result = url.toString();
}
} catch (java.net.MalformedURLException mue) {
// try to make an absolute URI from the current base
String absBase = makeAbsolute(base);
if (!absBase.equals(base)) {
// don't bother if the absBase isn't different!
return resolve(href, absBase);
} else {
throw new TransformerException("Malformed URL "
+ href + "(base " + base + ")",
mue);
}
}
}
catalogManager.debug.message(2, "Resolved URI", href, result);
SAXSource source = new SAXSource();
source.setInputSource(new InputSource(result));
setEntityResolver(source);
return source;
}
/**
* <p>Establish an entityResolver for newly resolved URIs.</p>
*
* <p>This is called from the URIResolver to set an EntityResolver
* on the SAX parser to be used for new XML documents that are
* encountered as a result of the document() function, xsl:import,
* or xsl:include. This is done because the XSLT processor calls
* out to the SAXParserFactory itself to create a new SAXParser to
* parse the new document. The new parser does not automatically
* inherit the EntityResolver of the original (although arguably
* it should). See below:</p>
*
* <tt>"If an application wants to set the ErrorHandler or
* EntityResolver for an XMLReader used during a transformation,
* it should use a URIResolver to return the SAXSource which
* provides (with getXMLReader) a reference to the XMLReader"</tt>
*
* <p>...quoted from page 118 of the Java API for XML
* Processing 1.1 specification</p>
*
*/
private void setEntityResolver(SAXSource source) throws TransformerException {
XMLReader reader = source.getXMLReader();
if (reader == null) {
SAXParserFactory spFactory = catalogManager.useServicesMechanism() ?
SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
spFactory.setNamespaceAware(true);
try {
reader = spFactory.newSAXParser().getXMLReader();
}
catch (ParserConfigurationException ex) {
throw new TransformerException(ex);
}
catch (SAXException ex) {
throw new TransformerException(ex);
}
}
reader.setEntityResolver(this);
source.setXMLReader(reader);
}
/** Attempt to construct an absolute URI */
private String makeAbsolute(String uri) {
if (uri == null) {
uri = "";
}
try {
URL url = new URL(uri);
return url.toString();
} catch (MalformedURLException mue) {
try {
URL fileURL = FileURL.makeURL(uri);
return fileURL.toString();
} catch (MalformedURLException mue2) {
// bail
return uri;
}
}
}
}

View file

@ -1,434 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.tools;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.Locale;
import org.xml.sax.Parser;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.ErrorHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.DocumentHandler;
import org.xml.sax.AttributeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.SAXException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import com.sun.org.apache.xml.internal.resolver.CatalogManager;
import com.sun.org.apache.xml.internal.resolver.helpers.FileURL;
/**
* A SAX Parser that performs catalog-based entity resolution.
*
* <p>This class implements a SAX Parser that performs entity resolution
* using the CatalogResolver. The actual, underlying parser is obtained
* from a SAXParserFactory.</p>
* </p>
*
* @deprecated This interface has been replaced by the
* {@link com.sun.org.apache.xml.internal.resolver.tools.ResolvingXMLReader} for SAX2.
* @see CatalogResolver
* @see org.xml.sax.Parser
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
* @version 1.0
*/
public class ResolvingParser
implements Parser, DTDHandler, DocumentHandler, EntityResolver {
/** Suppress explanatory message?
*
* @see #parse(InputSource)
*/
private static final boolean suppressExplanation = false;
/** The underlying parser. */
private SAXParser saxParser = null;
/** The underlying reader. */
private Parser parser = null;
/** The underlying DocumentHandler. */
private DocumentHandler documentHandler = null;
/** The underlying DTDHandler. */
private DTDHandler dtdHandler = null;
/** The manager for the underlying resolver. */
private CatalogManager catalogManager = CatalogManager.getStaticManager();
/** The underlying catalog resolver. */
private CatalogResolver catalogResolver = null;
/** A separate resolver for oasis-xml-pi catalogs. */
private CatalogResolver piCatalogResolver = null;
/** Are we in the prolog? Is an oasis-xml-catalog PI valid now? */
private boolean allowXMLCatalogPI = false;
/** The base URI of the input document, if known. */
private URL baseURL = null;
/** Constructor. */
public ResolvingParser() {
initParser();
}
/** Constructor. */
public ResolvingParser(CatalogManager manager) {
catalogManager = manager;
initParser();
}
/** Initialize the parser. */
private void initParser() {
catalogResolver = new CatalogResolver(catalogManager);
SAXParserFactory spf = catalogManager.useServicesMechanism() ?
SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
spf.setNamespaceAware(true);
spf.setValidating(false);
try {
saxParser = spf.newSAXParser();
parser = saxParser.getParser();
documentHandler = null;
dtdHandler = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** Return the Catalog being used. */
public Catalog getCatalog() {
return catalogResolver.getCatalog();
}
/**
* SAX Parser API.
*
* <p>Note that the JAXP 1.1ea2 parser crashes with an InternalError if
* it encounters a system identifier that appears to be a relative URI
* that begins with a slash. For example, the declaration:</p>
*
* <pre>
* &lt;!DOCTYPE book SYSTEM "/path/to/dtd/on/my/system/docbookx.dtd">
* </pre>
*
* <p>would cause such an error. As a convenience, this method catches
* that error and prints an explanation. (Unfortunately, it's not possible
* to identify the particular system identifier that causes the problem.)
* </p>
*
* <p>The underlying error is forwarded after printing the explanatory
* message. The message is only every printed once and if
* <code>suppressExplanation</code> is set to <code>false</code> before
* parsing, it will never be printed.</p>
*/
public void parse(InputSource input)
throws IOException,
SAXException {
setupParse(input.getSystemId());
try {
parser.parse(input);
} catch (InternalError ie) {
explain(input.getSystemId());
throw ie;
}
}
/** SAX Parser API.
*
* @see #parse(InputSource)
*/
public void parse(String systemId)
throws IOException,
SAXException {
setupParse(systemId);
try {
parser.parse(systemId);
} catch (InternalError ie) {
explain(systemId);
throw ie;
}
}
/** SAX Parser API. */
public void setDocumentHandler(DocumentHandler handler) {
documentHandler = handler;
}
/** SAX Parser API. */
public void setDTDHandler(DTDHandler handler) {
dtdHandler = handler;
}
/**
* SAX Parser API.
*
* <p>The purpose of this class is to implement an entity resolver.
* Attempting to set a different one is pointless (and ignored).</p>
*/
public void setEntityResolver(EntityResolver resolver) {
// nop
}
/** SAX Parser API. */
public void setErrorHandler(ErrorHandler handler) {
parser.setErrorHandler(handler);
}
/** SAX Parser API. */
public void setLocale(Locale locale) throws SAXException {
parser.setLocale(locale);
}
/** SAX DocumentHandler API. */
public void characters(char[] ch, int start, int length)
throws SAXException {
if (documentHandler != null) {
documentHandler.characters(ch,start,length);
}
}
/** SAX DocumentHandler API. */
public void endDocument() throws SAXException {
if (documentHandler != null) {
documentHandler.endDocument();
}
}
/** SAX DocumentHandler API. */
public void endElement(String name) throws SAXException {
if (documentHandler != null) {
documentHandler.endElement(name);
}
}
/** SAX DocumentHandler API. */
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
if (documentHandler != null) {
documentHandler.ignorableWhitespace(ch,start,length);
}
}
/** SAX DocumentHandler API. */
public void processingInstruction(String target, String pidata)
throws SAXException {
if (target.equals("oasis-xml-catalog")) {
URL catalog = null;
String data = pidata;
int pos = data.indexOf("catalog=");
if (pos >= 0) {
data = data.substring(pos+8);
if (data.length() > 1) {
String quote = data.substring(0,1);
data = data.substring(1);
pos = data.indexOf(quote);
if (pos >= 0) {
data = data.substring(0, pos);
try {
if (baseURL != null) {
catalog = new URL(baseURL, data);
} else {
catalog = new URL(data);
}
} catch (MalformedURLException mue) {
// nevermind
}
}
}
}
if (allowXMLCatalogPI) {
if (catalogManager.getAllowOasisXMLCatalogPI()) {
catalogManager.debug.message(4,"oasis-xml-catalog PI", pidata);
if (catalog != null) {
try {
catalogManager.debug.message(4,"oasis-xml-catalog", catalog.toString());
if (piCatalogResolver == null) {
piCatalogResolver = new CatalogResolver(true);
}
piCatalogResolver.getCatalog().parseCatalog(catalog.toString());
} catch (Exception e) {
catalogManager.debug.message(3, "Exception parsing oasis-xml-catalog: "
+ catalog.toString());
}
} else {
catalogManager.debug.message(3, "PI oasis-xml-catalog unparseable: " + pidata);
}
} else {
catalogManager.debug.message(4,"PI oasis-xml-catalog ignored: " + pidata);
}
} else {
catalogManager.debug.message(3, "PI oasis-xml-catalog occurred in an invalid place: "
+ pidata);
}
} else {
if (documentHandler != null) {
documentHandler.processingInstruction(target, pidata);
}
}
}
/** SAX DocumentHandler API. */
public void setDocumentLocator(Locator locator) {
if (documentHandler != null) {
documentHandler.setDocumentLocator(locator);
}
}
/** SAX DocumentHandler API. */
public void startDocument() throws SAXException {
if (documentHandler != null) {
documentHandler.startDocument();
}
}
/** SAX DocumentHandler API. */
public void startElement(String name, AttributeList atts)
throws SAXException {
allowXMLCatalogPI = false;
if (documentHandler != null) {
documentHandler.startElement(name,atts);
}
}
/** SAX DTDHandler API. */
public void notationDecl (String name, String publicId, String systemId)
throws SAXException {
allowXMLCatalogPI = false;
if (dtdHandler != null) {
dtdHandler.notationDecl(name,publicId,systemId);
}
}
/** SAX DTDHandler API. */
public void unparsedEntityDecl (String name,
String publicId,
String systemId,
String notationName)
throws SAXException {
allowXMLCatalogPI = false;
if (dtdHandler != null) {
dtdHandler.unparsedEntityDecl (name, publicId, systemId, notationName);
}
}
/**
* Implements the <code>resolveEntity</code> method
* for the SAX interface, using an underlying CatalogResolver
* to do the real work.
*/
public InputSource resolveEntity (String publicId, String systemId) {
allowXMLCatalogPI = false;
String resolved = catalogResolver.getResolvedEntity(publicId, systemId);
if (resolved == null && piCatalogResolver != null) {
resolved = piCatalogResolver.getResolvedEntity(publicId, systemId);
}
if (resolved != null) {
try {
InputSource iSource = new InputSource(resolved);
iSource.setPublicId(publicId);
// Ideally this method would not attempt to open the
// InputStream, but there is a bug (in Xerces, at least)
// that causes the parser to mistakenly open the wrong
// system identifier if the returned InputSource does
// not have a byteStream.
//
// It could be argued that we still shouldn't do this here,
// but since the purpose of calling the entityResolver is
// almost certainly to open the input stream, it seems to
// do little harm.
//
URL url = new URL(resolved);
InputStream iStream = url.openStream();
iSource.setByteStream(iStream);
return iSource;
} catch (Exception e) {
catalogManager.debug.message(1,
"Failed to create InputSource ("
+ e.toString()
+ ")", resolved);
return null;
}
} else {
return null;
}
}
/** Setup for parsing. */
private void setupParse(String systemId) {
allowXMLCatalogPI = true;
parser.setEntityResolver(this);
parser.setDocumentHandler(this);
parser.setDTDHandler(this);
URL cwd = null;
try {
cwd = FileURL.makeURL("basename");
} catch (MalformedURLException mue) {
cwd = null;
}
try {
baseURL = new URL(systemId);
} catch (MalformedURLException mue) {
if (cwd != null) {
try {
baseURL = new URL(cwd, systemId);
} catch (MalformedURLException mue2) {
// give up
baseURL = null;
}
} else {
// give up
baseURL = null;
}
}
}
/** Provide one possible explanation for an InternalError. */
private void explain(String systemId) {
if (!suppressExplanation) {
System.out.println("Parser probably encountered bad URI in " + systemId);
System.out.println("For example, replace '/some/uri' with 'file:/some/uri'.");
}
}
}

View file

@ -1,346 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.tools;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.XMLFilterImpl;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import com.sun.org.apache.xml.internal.resolver.CatalogManager;
import com.sun.org.apache.xml.internal.resolver.helpers.FileURL;
/**
* A SAX XMLFilter that performs catalog-based entity resolution.
*
* <p>This class implements a SAX XMLFilter that performs entity resolution
* using the CatalogResolver. The actual, underlying parser is obtained
* from a SAXParserFactory.</p>
* </p>
*
* @see CatalogResolver
* @see org.xml.sax.XMLFilter
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
* @version 1.0
*/
public class ResolvingXMLFilter extends XMLFilterImpl {
/**
* Suppress explanatory message?
*
* @see #parse(InputSource)
*/
private static boolean suppressExplanation = false;
/** The manager for the underlying resolver. */
CatalogManager catalogManager = CatalogManager.getStaticManager();
/** The underlying catalog resolver. */
private CatalogResolver catalogResolver = null;
/** A separate resolver for oasis-xml-pi catalogs. */
private CatalogResolver piCatalogResolver = null;
/** Are we in the prolog? Is an oasis-xml-catalog PI valid now? */
private boolean allowXMLCatalogPI = false;
/** The base URI of the input document, if known. */
private URL baseURL = null;
/** Construct an empty XML Filter with no parent. */
public ResolvingXMLFilter() {
super();
catalogResolver = new CatalogResolver(catalogManager);
}
/** Construct an XML filter with the specified parent. */
public ResolvingXMLFilter(XMLReader parent) {
super(parent);
catalogResolver = new CatalogResolver(catalogManager);
}
/** Construct an XML filter with the specified parent. */
public ResolvingXMLFilter(CatalogManager manager) {
super();
catalogManager = manager;
catalogResolver = new CatalogResolver(catalogManager);
}
/** Construct an XML filter with the specified parent. */
public ResolvingXMLFilter(XMLReader parent, CatalogManager manager) {
super(parent);
catalogManager = manager;
catalogResolver = new CatalogResolver(catalogManager);
}
/**
* Provide accessto the underlying Catalog.
*/
public Catalog getCatalog() {
return catalogResolver.getCatalog();
}
/**
* SAX XMLReader API.
*
* <p>Note that the JAXP 1.1ea2 parser crashes with an InternalError if
* it encounters a system identifier that appears to be a relative URI
* that begins with a slash. For example, the declaration:</p>
*
* <pre>
* &lt;!DOCTYPE book SYSTEM "/path/to/dtd/on/my/system/docbookx.dtd">
* </pre>
*
* <p>would cause such an error. As a convenience, this method catches
* that error and prints an explanation. (Unfortunately, it's not possible
* to identify the particular system identifier that causes the problem.)
* </p>
*
* <p>The underlying error is forwarded after printing the explanatory
* message. The message is only every printed once and if
* <code>suppressExplanation</code> is set to <code>false</code> before
* parsing, it will never be printed.</p>
*/
public void parse(InputSource input)
throws IOException, SAXException {
allowXMLCatalogPI = true;
setupBaseURI(input.getSystemId());
try {
super.parse(input);
} catch (InternalError ie) {
explain(input.getSystemId());
throw ie;
}
}
/** SAX XMLReader API.
*
* @see #parse(InputSource)
*/
public void parse(String systemId)
throws IOException, SAXException {
allowXMLCatalogPI = true;
setupBaseURI(systemId);
try {
super.parse(systemId);
} catch (InternalError ie) {
explain(systemId);
throw ie;
}
}
/**
* Implements the <code>resolveEntity</code> method
* for the SAX interface, using an underlying CatalogResolver
* to do the real work.
*/
public InputSource resolveEntity (String publicId, String systemId) {
allowXMLCatalogPI = false;
String resolved = catalogResolver.getResolvedEntity(publicId, systemId);
if (resolved == null && piCatalogResolver != null) {
resolved = piCatalogResolver.getResolvedEntity(publicId, systemId);
}
if (resolved != null) {
try {
InputSource iSource = new InputSource(resolved);
iSource.setPublicId(publicId);
// Ideally this method would not attempt to open the
// InputStream, but there is a bug (in Xerces, at least)
// that causes the parser to mistakenly open the wrong
// system identifier if the returned InputSource does
// not have a byteStream.
//
// It could be argued that we still shouldn't do this here,
// but since the purpose of calling the entityResolver is
// almost certainly to open the input stream, it seems to
// do little harm.
//
URL url = new URL(resolved);
InputStream iStream = url.openStream();
iSource.setByteStream(iStream);
return iSource;
} catch (Exception e) {
catalogManager.debug.message(1,
"Failed to create InputSource ("
+ e.toString()
+ ")", resolved);
return null;
}
} else {
return null;
}
}
/** SAX DTDHandler API.
*
* <p>Captured here only to detect the end of the prolog so that
* we can ignore subsequent oasis-xml-catalog PIs. Otherwise
* the events are just passed through.</p>
*/
public void notationDecl (String name, String publicId, String systemId)
throws SAXException {
allowXMLCatalogPI = false;
super.notationDecl(name,publicId,systemId);
}
/** SAX DTDHandler API.
*
* <p>Captured here only to detect the end of the prolog so that
* we can ignore subsequent oasis-xml-catalog PIs. Otherwise
* the events are just passed through.</p>
*/
public void unparsedEntityDecl (String name,
String publicId,
String systemId,
String notationName)
throws SAXException {
allowXMLCatalogPI = false;
super.unparsedEntityDecl (name, publicId, systemId, notationName);
}
/** SAX ContentHandler API.
*
* <p>Captured here only to detect the end of the prolog so that
* we can ignore subsequent oasis-xml-catalog PIs. Otherwise
* the events are just passed through.</p>
*/
public void startElement (String uri, String localName, String qName,
Attributes atts)
throws SAXException {
allowXMLCatalogPI = false;
super.startElement(uri,localName,qName,atts);
}
/** SAX ContentHandler API.
*
* <p>Detect and use the oasis-xml-catalog PI if it occurs.</p>
*/
public void processingInstruction(String target, String pidata)
throws SAXException {
if (target.equals("oasis-xml-catalog")) {
URL catalog = null;
String data = pidata;
int pos = data.indexOf("catalog=");
if (pos >= 0) {
data = data.substring(pos+8);
if (data.length() > 1) {
String quote = data.substring(0,1);
data = data.substring(1);
pos = data.indexOf(quote);
if (pos >= 0) {
data = data.substring(0, pos);
try {
if (baseURL != null) {
catalog = new URL(baseURL, data);
} else {
catalog = new URL(data);
}
} catch (MalformedURLException mue) {
// nevermind
}
}
}
}
if (allowXMLCatalogPI) {
if (catalogManager.getAllowOasisXMLCatalogPI()) {
catalogManager.debug.message(4,"oasis-xml-catalog PI", pidata);
if (catalog != null) {
try {
catalogManager.debug.message(4,"oasis-xml-catalog", catalog.toString());
if (piCatalogResolver == null) {
piCatalogResolver = new CatalogResolver(true);
}
piCatalogResolver.getCatalog().parseCatalog(catalog.toString());
} catch (Exception e) {
catalogManager.debug.message(3, "Exception parsing oasis-xml-catalog: "
+ catalog.toString());
}
} else {
catalogManager.debug.message(3, "PI oasis-xml-catalog unparseable: " + pidata);
}
} else {
catalogManager.debug.message(4,"PI oasis-xml-catalog ignored: " + pidata);
}
} else {
catalogManager.debug.message(3, "PI oasis-xml-catalog occurred in an invalid place: "
+ pidata);
}
} else {
super.processingInstruction(target, pidata);
}
}
/** Save the base URI of the document being parsed. */
private void setupBaseURI(String systemId) {
URL cwd = null;
try {
cwd = FileURL.makeURL("basename");
} catch (MalformedURLException mue) {
cwd = null;
}
try {
baseURL = new URL(systemId);
} catch (MalformedURLException mue) {
if (cwd != null) {
try {
baseURL = new URL(cwd, systemId);
} catch (MalformedURLException mue2) {
// give up
baseURL = null;
}
} else {
// give up
baseURL = null;
}
}
}
/** Provide one possible explanation for an InternalError. */
private void explain(String systemId) {
if (!suppressExplanation) {
System.out.println("XMLReader probably encountered bad URI in " + systemId);
System.out.println("For example, replace '/some/uri' with 'file:/some/uri'.");
}
suppressExplanation = true;
}
}

View file

@ -1,90 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xml.internal.resolver.tools;
import javax.xml.parsers.*;
import com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl;
import com.sun.org.apache.xml.internal.resolver.*;
/**
* A SAX XMLReader that performs catalog-based entity resolution.
*
* <p>This class implements a SAX XMLReader that performs entity resolution
* using the CatalogResolver. The actual, underlying parser is obtained
* from a SAXParserFactory.</p>
* </p>
*
* @see CatalogResolver
* @see org.xml.sax.XMLReader
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
* @version 1.0
*/
public class ResolvingXMLReader extends ResolvingXMLFilter {
/** Make the parser Namespace aware? */
private static final boolean namespaceAware = true;
/** Make the parser validating? */
private static final boolean validating = false;
/**
* Construct a new reader from the JAXP factory.
*
* <p>In order to do its job, a ResolvingXMLReader must in fact be
* a filter. So the only difference between this code and the filter
* code is that the constructor builds a new reader.</p>
*/
public ResolvingXMLReader() {
super();
SAXParserFactory spf = catalogManager.useServicesMechanism() ?
SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
spf.setNamespaceAware(namespaceAware);
spf.setValidating(validating);
try {
SAXParser parser = spf.newSAXParser();
setParent(parser.getXMLReader());
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Construct a new reader from the JAXP factory.
*
* <p>In order to do its job, a ResolvingXMLReader must in fact be
* a filter. So the only difference between this code and the filter
* code is that the constructor builds a new reader.</p>
*/
public ResolvingXMLReader(CatalogManager manager) {
super(manager);
SAXParserFactory spf = catalogManager.useServicesMechanism() ?
SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
spf.setNamespaceAware(namespaceAware);
spf.setValidating(validating);
try {
SAXParser parser = spf.newSAXParser();
setParent(parser.getXMLReader());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

View file

@ -27,6 +27,17 @@
* Defines the Java API for XML Processing (JAXP), the Streaming API for XML (StAX),
* the Simple API for XML (SAX), and the W3C Document Object Model (DOM) API.
*
* @uses javax.xml.datatype.DatatypeFactory
* @uses javax.xml.parsers.DocumentBuilderFactory
* @uses javax.xml.parsers.SAXParserFactory
* @uses javax.xml.stream.XMLEventFactory
* @uses javax.xml.stream.XMLInputFactory
* @uses javax.xml.stream.XMLOutputFactory
* @uses javax.xml.transform.TransformerFactory
* @uses javax.xml.validation.SchemaFactory
* @uses javax.xml.xpath.XPathFactory
* @uses org.xml.sax.XMLReader
*
* @moduleGraph
* @since 9
*/
@ -56,6 +67,7 @@ module java.xml {
exports org.xml.sax;
exports org.xml.sax.ext;
exports org.xml.sax.helpers;
exports com.sun.org.apache.xml.internal.dtm to
java.xml.crypto;
exports com.sun.org.apache.xml.internal.utils to
@ -70,8 +82,7 @@ module java.xml {
java.xml.crypto;
exports com.sun.org.apache.xpath.internal.res to
java.xml.crypto;
// reflection access from com.sun.xml.internal.ws.api.streaming.XMLStreamWriterFactory
exports com.sun.xml.internal.stream.writers to java.xml.ws;
uses javax.xml.datatype.DatatypeFactory;
uses javax.xml.parsers.DocumentBuilderFactory;
uses javax.xml.parsers.SAXParserFactory;

View file

@ -32,6 +32,7 @@
*/
module jdk.xml.dom {
requires transitive java.xml;
exports org.w3c.dom.css;
exports org.w3c.dom.html;
exports org.w3c.dom.stylesheets;

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* 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,12 +24,15 @@
*/
/**
This package contains classes that write HTML markup tags.
<p><b>This is NOT part of any supported API.
If you write code that depends on this, you do so at your own risk.
This code and its internal interfaces are subject to change or
deletion without notice.</b>
* Provides interfaces for DOM Level 2 Style Specification. Refer to the
* <a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113'>
* Document Object Model (DOM) Level 2 Style Specification</a>,
* the CSS and stylesheets modules define the Document Object Model Level 2 Style
* Sheets and Cascading Style Sheets (CSS) that allow programs and scripts to
* dynamically access and update the content of style sheets documents.
*
*
* @since 1.4
*/
package com.sun.tools.doclets.formats.html.markup;
package org.w3c.dom.css;

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,17 +23,17 @@
* questions.
*/
package com.sun.tools.doclets.internal.toolkit.util;
/**
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
* Provides interfaces for DOM Level 2 HTML Specification. Refer to the
* <a href='http://www.w3.org/TR/2000/CR-DOM-Level-2-20000510'>
* Document Object Model (DOM) Level 2 Specification</a>,
* the HTML module extends the Core API to describe objects and methods specific
* to HTML documents that comply with
* <a href='https://www.w3.org/TR/1998/REC-html40-19980424/'>
* HTML 4.0 Specification</a>.
*
*
* @since 1.4
*/
@Deprecated
public class FatalError extends Error {
private static final long serialVersionUID = -9131058909576418984L;
public FatalError() { }
}
package org.w3c.dom.html;

View file

@ -0,0 +1,38 @@
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* 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.
*/
/**
* Provides interfaces for DOM Level 2 Style Specification. Refer to the
* <a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113'>
* Document Object Model (DOM) Level 2 Style Specification</a>,
* the CSS and stylesheets modules define the Document Object Model Level 2 Style
* Sheets and Cascading Style Sheets (CSS) that allow programs and scripts to
* dynamically access and update the content of style sheets documents.
*
*
* @since 1.4
*/
package org.w3c.dom.stylesheets;

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* 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,28 +23,21 @@
* questions.
*/
package com.sun.tools.doclets.internal.toolkit.taglets;
/**
* An abstract inline taglet that outputs HTML.
* Provides interfaces for DOM Level 3 XPath Specification. The XPath module
* provides simple functionalities to access a DOM tree using
* <a href='https://www.w3.org/TR/1999/REC-xpath-19991116/'>XPath 1.0</a>.
* <p>
* The interfaces and classes in this package came from
* Document Object Model (DOM) Level 3 XPath Specification,
* Working Draft 20 August 2002. Refer to
* <a href='https://www.w3.org/TR/DOM-Level-3-XPath/'>
* Document Object Model (DOM) Level 3 XPath Specification, Version 1.0,
* W3C Working Group Note 26 February 2004</a> except that the values of
* {@link XPathException#INVALID_EXPRESSION_ERR} and {@link XPathException#TYPE_ERR}
* are 1 and 2 respectively (instead of 51 and 52).
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*
* @author Jamie Ho
* @since 1.4
*/
@Deprecated
public abstract class BaseInlineTaglet extends BaseTaglet {
/**
* Will return true since this is an inline tag.
* @return true since this is an inline tag.
*/
public boolean isInlineTag() {
return true;
}
}
package org.w3c.dom.xpath;

View file

@ -431,3 +431,7 @@ e705867d9989d00e4357f66f18b302c95e13b5e7 jdk-10+8
8c615099f3e3ca137325be34bf566b767d9e3c64 jdk-9+172
2d22d6732a73e615b9e13d6bc93bf026db3bc231 jdk-10+11
2bd967aa452c1e0e87a6173bef6fbb96ef1c521b jdk-9+173
c2296642010f1b215ac35da89e92c3ce44104e32 jdk-9+174
712a3a657654079514590d37a0f4894d43541d5c jdk-10+12
a5d361b9d1f7f78a675f3baef0d1fd32deee9ea2 jdk-9+175
46a14aad004aa0b980d5f4ff7810d894fd5a36ae jdk-10+13

View file

@ -1 +1,2 @@
project=jdk10
bugids=dup

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -118,6 +118,9 @@ public class CommandInfo {
* passed to the command.
* @param loader The ClassLoader to be used to instantiate the bean.
* @return The bean
* @exception IOException for failures reading data
* @exception ClassNotFoundException if command object class can't
* be found
* @see java.beans.Beans#instantiate
* @see javax.activation.CommandObject
*/

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -48,6 +48,7 @@ public interface CommandObject {
*
* @param verb The Command Verb this object refers to.
* @param dh The DataHandler.
* @exception IOException for failures accessing data
*/
public void setCommandContext(String verb, DataHandler dh)
throws IOException;

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -326,6 +326,7 @@ public class DataHandler implements Transferable {
* Otherwise, {@code null} is returned.
*
* @return the OutputStream
* @exception IOException for failures creating the OutputStream
*
* @see javax.activation.DataSource#getOutputStream
* @see javax.activation.URLDataSource

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* 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,6 +49,7 @@ public interface DataSource {
* positioned at the beginning of the data.
*
* @return an InputStream
* @exception IOException for failures creating the InputStream
*/
public InputStream getInputStream() throws IOException;
@ -60,6 +61,7 @@ public interface DataSource {
* be positioned at the location the data is to be written.
*
* @return an OutputStream
* @exception IOException for failures creating the OutputStream
*/
public OutputStream getOutputStream() throws IOException;

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* 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,8 @@ package javax.activation;
import java.util.*;
import java.io.*;
import java.net.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import com.sun.activation.registries.MailcapFile;
import com.sun.activation.registries.LogSupport;
@ -48,12 +50,19 @@ import com.sun.activation.registries.LogSupport;
* <ol>
* <li> Programatically added entries to the MailcapCommandMap instance.
* <li> The file {@code .mailcap} in the user's home directory.
* <li> The file {@literal <}<i>java.home</i>{@literal >}{@code /lib/mailcap}.
* <li> The file {@code mailcap} in the Java runtime.
* <li> The file or resources named {@code META-INF/mailcap}.
* <li> The file or resource named {@code META-INF/mailcap.default}
* (usually found only in the {@code activation.jar} file).
* </ol>
* <p>
* (The current implementation looks for the {@code mailcap} file
* in the Java runtime in the directory <i>java.home</i>{@code /conf}
* if it exists, and otherwise in the directory
* <i>java.home</i>{@code /lib}, where <i>java.home</i> is the value
* of the "java.home" System property. Note that the "conf" directory was
* introduced in JDK 9.)
* <p>
* <b>Mailcap file format:</b><p>
*
* Mailcap files must conform to the mailcap
@ -120,6 +129,29 @@ public class MailcapCommandMap extends CommandMap {
private MailcapFile[] DB;
private static final int PROG = 0; // programmatically added entries
private static final String confDir;
static {
String dir = null;
try {
dir = (String)AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
String home = System.getProperty("java.home");
String newdir = home + File.separator + "conf";
File conf = new File(newdir);
if (conf.exists())
return newdir + File.separator;
else
return home + File.separator + "lib" + File.separator;
}
});
} catch (Exception ex) {
// ignore any exceptions
}
confDir = dir;
}
/**
* The default Constructor.
*/
@ -144,11 +176,11 @@ public class MailcapCommandMap extends CommandMap {
LogSupport.log("MailcapCommandMap: load SYS");
try {
// check system's home
String system_mailcap = System.getProperty("java.home") +
File.separator + "lib" + File.separator + "mailcap";
mf = loadFile(system_mailcap);
if (confDir != null) {
mf = loadFile(confDir + "mailcap");
if (mf != null)
dbv.add(mf);
}
} catch (SecurityException ex) {}
LogSupport.log("MailcapCommandMap: load JAR");
@ -633,6 +665,7 @@ public class MailcapCommandMap extends CommandMap {
* entries that specify a view command for the specified
* MIME type are returned.
*
* @param mimeType the MIME type
* @return array of native command entries
* @since 1.6, JAF 1.1
*/

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -58,6 +58,7 @@ public class MimeType implements Externalizable {
* Constructor that builds a MimeType from a String.
*
* @param rawdata the MIME type string
* @exception MimeTypeParseException if the MIME type can't be parsed
*/
public MimeType(String rawdata) throws MimeTypeParseException {
parse(rawdata);
@ -258,6 +259,7 @@ public class MimeType implements Externalizable {
*
* @param rawdata the MIME type string to compare with
* @return true if they match
* @exception MimeTypeParseException if the MIME type can't be parsed
*/
public boolean match(String rawdata) throws MimeTypeParseException {
return match(new MimeType(rawdata));

Some files were not shown because too many files have changed in this diff Show more