This commit is contained in:
J. Duke 2017-07-05 21:46:28 +02:00
commit fea2b75fcd
328 changed files with 43074 additions and 831 deletions

View File

@ -362,3 +362,4 @@ f900d5afd9c83a0df8f36161c27c5e4c86a66f4c jdk-9+111
e882bcdbdac436523f3d5681611d3118a3804ea7 jdk-9+117 e882bcdbdac436523f3d5681611d3118a3804ea7 jdk-9+117
047f95de8f918d8ff5e8cd2636a2abb5c3c8adb8 jdk-9+118 047f95de8f918d8ff5e8cd2636a2abb5c3c8adb8 jdk-9+118
3463a3f14f0f0e8a68f29ac6405454f2fa2f598a jdk-9+119 3463a3f14f0f0e8a68f29ac6405454f2fa2f598a jdk-9+119
647e0142a5a52749db572b5e6638d561def6479e jdk-9+120

View File

@ -229,6 +229,7 @@ LIB_SETUP_LIBRARIES
JDKOPT_DETECT_INTREE_EC JDKOPT_DETECT_INTREE_EC
JDKOPT_ENABLE_DISABLE_FAILURE_HANDLER JDKOPT_ENABLE_DISABLE_FAILURE_HANDLER
JDKOPT_ENABLE_DISABLE_GENERATE_CLASSLIST
############################################################################### ###############################################################################
# #

View File

@ -650,6 +650,7 @@ TEST_JOBS
JOBS JOBS
MEMORY_SIZE MEMORY_SIZE
NUM_CORES NUM_CORES
ENABLE_GENERATE_CLASSLIST
BUILD_FAILURE_HANDLER BUILD_FAILURE_HANDLER
ENABLE_INTREE_EC ENABLE_INTREE_EC
STLPORT_LIB STLPORT_LIB
@ -1226,6 +1227,7 @@ with_dxsdk
with_dxsdk_lib with_dxsdk_lib
with_dxsdk_include with_dxsdk_include
enable_jtreg_failure_handler enable_jtreg_failure_handler
enable_generate_classlist
with_num_cores with_num_cores
with_memory_size with_memory_size
with_jobs with_jobs
@ -2005,6 +2007,10 @@ Optional Features:
Default is auto, where the failure handler is built Default is auto, where the failure handler is built
if all dependencies are present and otherwise just if all dependencies are present and otherwise just
disabled. disabled.
--disable-generate-classlist
forces enabling or disabling of the generation of a
CDS classlist at build time. Default is to generate
it when either the server or client JVMs are built.
--enable-sjavac use sjavac to do fast incremental compiles --enable-sjavac use sjavac to do fast incremental compiles
[disabled] [disabled]
--disable-javac-server disable javac server [enabled] --disable-javac-server disable javac server [enabled]
@ -4391,6 +4397,12 @@ VALID_JVM_VARIANTS="server client minimal core zero zeroshark custom"
# #
################################################################################
#
# Enable or disable generation of the classlist at build time
#
# #
# Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@ -5080,7 +5092,7 @@ VS_SDK_PLATFORM_NAME_2013=
#CUSTOM_AUTOCONF_INCLUDE #CUSTOM_AUTOCONF_INCLUDE
# Do not change or remove the following line, it is needed for consistency checks: # Do not change or remove the following line, it is needed for consistency checks:
DATE_WHEN_GENERATED=1463732692 DATE_WHEN_GENERATED=1464173584
############################################################################### ###############################################################################
# #
@ -64812,6 +64824,51 @@ $as_echo "yes, jtreg present" >&6; }
# Check whether --enable-generate-classlist was given.
if test "${enable_generate_classlist+set}" = set; then :
enableval=$enable_generate_classlist;
fi
# Check if it's likely that it's possible to generate the classlist. Depending
# on exact jvm configuration it could be possible anyway.
if [[ " $JVM_VARIANTS " =~ " server " ]] || [[ " $JVM_VARIANTS " =~ " client " ]] ; then
ENABLE_GENERATE_CLASSLIST_POSSIBLE="true"
else
ENABLE_GENERATE_CLASSLIST_POSSIBLE="false"
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if the CDS classlist generation should be enabled" >&5
$as_echo_n "checking if the CDS classlist generation should be enabled... " >&6; }
if test "x$enable_generate_classlist" = "xyes"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, forced" >&5
$as_echo "yes, forced" >&6; }
ENABLE_GENERATE_CLASSLIST="true"
if test "x$ENABLE_GENERATE_CLASSLIST_POSSIBLE" = "xfalse"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Generation of classlist might not be possible with JVM Variants $JVM_VARIANTS" >&5
$as_echo "$as_me: WARNING: Generation of classlist might not be possible with JVM Variants $JVM_VARIANTS" >&2;}
fi
elif test "x$enable_generate_classlist" = "xno"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no, forced" >&5
$as_echo "no, forced" >&6; }
ENABLE_GENERATE_CLASSLIST="false"
elif test "x$enable_generate_classlist" = "x"; then
if test "x$ENABLE_GENERATE_CLASSLIST_POSSIBLE" = "xtrue"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
$as_echo "yes" >&6; }
ENABLE_GENERATE_CLASSLIST="true"
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
ENABLE_GENERATE_CLASSLIST="false"
fi
else
as_fn_error $? "Invalid value for --enable-generate-classlist: $enable_generate_classlist" "$LINENO" 5
fi
############################################################################### ###############################################################################
# #
# Configure parts of the build that only affect the build performance, # Configure parts of the build that only affect the build performance,

View File

@ -491,3 +491,46 @@ AC_DEFUN_ONCE([JDKOPT_ENABLE_DISABLE_FAILURE_HANDLER],
AC_SUBST(BUILD_FAILURE_HANDLER) AC_SUBST(BUILD_FAILURE_HANDLER)
]) ])
################################################################################
#
# Enable or disable generation of the classlist at build time
#
AC_DEFUN_ONCE([JDKOPT_ENABLE_DISABLE_GENERATE_CLASSLIST],
[
AC_ARG_ENABLE([generate-classlist], [AS_HELP_STRING([--disable-generate-classlist],
[forces enabling or disabling of the generation of a CDS classlist at build time.
Default is to generate it when either the server or client JVMs are built.])])
# Check if it's likely that it's possible to generate the classlist. Depending
# on exact jvm configuration it could be possible anyway.
if HOTSPOT_CHECK_JVM_VARIANT(server) || HOTSPOT_CHECK_JVM_VARIANT(client); then
ENABLE_GENERATE_CLASSLIST_POSSIBLE="true"
else
ENABLE_GENERATE_CLASSLIST_POSSIBLE="false"
fi
AC_MSG_CHECKING([if the CDS classlist generation should be enabled])
if test "x$enable_generate_classlist" = "xyes"; then
AC_MSG_RESULT([yes, forced])
ENABLE_GENERATE_CLASSLIST="true"
if test "x$ENABLE_GENERATE_CLASSLIST_POSSIBLE" = "xfalse"; then
AC_MSG_WARN([Generation of classlist might not be possible with JVM Variants $JVM_VARIANTS])
fi
elif test "x$enable_generate_classlist" = "xno"; then
AC_MSG_RESULT([no, forced])
ENABLE_GENERATE_CLASSLIST="false"
elif test "x$enable_generate_classlist" = "x"; then
if test "x$ENABLE_GENERATE_CLASSLIST_POSSIBLE" = "xtrue"; then
AC_MSG_RESULT([yes])
ENABLE_GENERATE_CLASSLIST="true"
else
AC_MSG_RESULT([no])
ENABLE_GENERATE_CLASSLIST="false"
fi
else
AC_MSG_ERROR([Invalid value for --enable-generate-classlist: $enable_generate_classlist])
fi
AC_SUBST([ENABLE_GENERATE_CLASSLIST])
])

View File

@ -285,6 +285,8 @@ BUILD_HOTSPOT=@BUILD_HOTSPOT@
BUILD_FAILURE_HANDLER := @BUILD_FAILURE_HANDLER@ BUILD_FAILURE_HANDLER := @BUILD_FAILURE_HANDLER@
ENABLE_GENERATE_CLASSLIST := @ENABLE_GENERATE_CLASSLIST@
# The boot jdk to use. This is overridden in bootcycle-spec.gmk. Make sure to keep # The boot jdk to use. This is overridden in bootcycle-spec.gmk. Make sure to keep
# it in sync. # it in sync.
BOOT_JDK:=@BOOT_JDK@ BOOT_JDK:=@BOOT_JDK@

View File

@ -362,3 +362,4 @@ cc30faa2da498c478e89ab062ff160653ca1b170 jdk-9+113
7a1b36bf2fe55a9a7732489ccdd326c910329a7e jdk-9+117 7a1b36bf2fe55a9a7732489ccdd326c910329a7e jdk-9+117
8c2c2d17f7ce92a31c9ccb44a122ec62f5a85ace jdk-9+118 8c2c2d17f7ce92a31c9ccb44a122ec62f5a85ace jdk-9+118
daf533920b1266603b5cbdab31908d2a931c5361 jdk-9+119 daf533920b1266603b5cbdab31908d2a931c5361 jdk-9+119
5943b791e131e79b969d4cea053aecda34801723 jdk-9+120

View File

@ -522,3 +522,4 @@ b64432bae5271735fd53300b2005b713e98ef411 jdk-9+114
88170d3642905b9e6cac03e8efcc976885a7e6da jdk-9+117 88170d3642905b9e6cac03e8efcc976885a7e6da jdk-9+117
9b1075cac08dc836ec32e7b368415cbe3aceaf8c jdk-9+118 9b1075cac08dc836ec32e7b368415cbe3aceaf8c jdk-9+118
15f3fe264872766bcb205696198f0c1502420e17 jdk-9+119 15f3fe264872766bcb205696198f0c1502420e17 jdk-9+119
0be6f4f5d18671184e62583668cb1d783dffa128 jdk-9+120

View File

@ -362,3 +362,4 @@ baeb5edb38939cdb78ae0ac6f4fd368465cbf188 jdk-9+116
4da0f73ce03aaf245b92cc040cc0ab0e3fa54dc2 jdk-9+117 4da0f73ce03aaf245b92cc040cc0ab0e3fa54dc2 jdk-9+117
e1eba5cfa5cc8c66d524396a05323dc93568730a jdk-9+118 e1eba5cfa5cc8c66d524396a05323dc93568730a jdk-9+118
bad3f8a33db271a6143ba6eac0c8bd5bbd942417 jdk-9+119 bad3f8a33db271a6143ba6eac0c8bd5bbd942417 jdk-9+119
b9a518bf72516954e57ac2f6e3ef21e13008f1cd jdk-9+120

View File

@ -267,6 +267,7 @@ SUNWprivate_1.1 {
Java_jdk_internal_misc_VM_geteuid; Java_jdk_internal_misc_VM_geteuid;
Java_jdk_internal_misc_VM_getgid; Java_jdk_internal_misc_VM_getgid;
Java_jdk_internal_misc_VM_getegid; Java_jdk_internal_misc_VM_getegid;
Java_jdk_internal_misc_VM_getRuntimeArguments;
Java_jdk_internal_misc_VM_initialize; Java_jdk_internal_misc_VM_initialize;
Java_java_lang_reflect_Module_defineModule0; Java_java_lang_reflect_Module_defineModule0;

View File

@ -117,7 +117,9 @@ public final class Boolean implements java.io.Serializable,
* Parses the string argument as a boolean. The {@code boolean} * Parses the string argument as a boolean. The {@code boolean}
* returned represents the value {@code true} if the string argument * returned represents the value {@code true} if the string argument
* is not {@code null} and is equal, ignoring case, to the string * is not {@code null} and is equal, ignoring case, to the string
* {@code "true"}. <p> * {@code "true"}.
* Otherwise, a false value is returned, including for a null
* argument.<p>
* Example: {@code Boolean.parseBoolean("True")} returns {@code true}.<br> * Example: {@code Boolean.parseBoolean("True")} returns {@code true}.<br>
* Example: {@code Boolean.parseBoolean("yes")} returns {@code false}. * Example: {@code Boolean.parseBoolean("yes")} returns {@code false}.
* *
@ -165,6 +167,8 @@ public final class Boolean implements java.io.Serializable,
* specified string. The {@code Boolean} returned represents a * specified string. The {@code Boolean} returned represents a
* true value if the string argument is not {@code null} * true value if the string argument is not {@code null}
* and is equal, ignoring case, to the string {@code "true"}. * and is equal, ignoring case, to the string {@code "true"}.
* Otherwise, a false value is returned, including for a null
* argument.
* *
* @param s a string. * @param s a string.
* @return the {@code Boolean} value represented by the string. * @return the {@code Boolean} value represented by the string.
@ -241,14 +245,12 @@ public final class Boolean implements java.io.Serializable,
/** /**
* Returns {@code true} if and only if the system property named * Returns {@code true} if and only if the system property named
* by the argument exists and is equal to the string {@code * by the argument exists and is equal to, ignoring case, the
* "true"}. (Beginning with version 1.0.2 of the Java&trade; * string {@code "true"}.
* platform, the test of this string is case insensitive.) A * A system property is accessible through {@code getProperty}, a
* system property is accessible through {@code getProperty}, a * method defined by the {@code System} class. <p> If there is no
* method defined by the {@code System} class. * property with the specified name, or if the specified name is
* <p> * empty or null, then {@code false} is returned.
* If there is no property with the specified name, or if the specified
* name is empty or null, then {@code false} is returned.
* *
* @param name the system property name. * @param name the system property name.
* @return the {@code boolean} value of the system property. * @return the {@code boolean} value of the system property.

View File

@ -306,8 +306,9 @@ public final class StackWalker {
return DEFAULT_WALKER; return DEFAULT_WALKER;
} }
checkPermission(options); EnumSet<Option> optionSet = toEnumSet(options);
return new StackWalker(toEnumSet(options)); checkPermission(optionSet);
return new StackWalker(optionSet);
} }
/** /**
@ -341,8 +342,9 @@ public final class StackWalker {
if (estimateDepth <= 0) { if (estimateDepth <= 0) {
throw new IllegalArgumentException("estimateDepth must be > 0"); throw new IllegalArgumentException("estimateDepth must be > 0");
} }
checkPermission(options); EnumSet<Option> optionSet = toEnumSet(options);
return new StackWalker(toEnumSet(options), estimateDepth); checkPermission(optionSet);
return new StackWalker(optionSet, estimateDepth);
} }
// ----- private constructors ------ // ----- private constructors ------
@ -540,13 +542,11 @@ public final class StackWalker {
} }
// ---- package access ---- // ---- package access ----
static StackWalker newInstanceNoCheck(EnumSet<Option> options) {
return new StackWalker(options, 0, null);
}
static StackWalker newInstance(Set<Option> options, ExtendedOption extendedOption) { static StackWalker newInstance(Set<Option> options, ExtendedOption extendedOption) {
checkPermission(options); EnumSet<Option> optionSet = toEnumSet(options);
return new StackWalker(toEnumSet(options), 0, extendedOption); checkPermission(optionSet);
return new StackWalker(optionSet, 0, extendedOption);
} }
int estimateDepth() { int estimateDepth() {

View File

@ -46,7 +46,7 @@ package java.lang.annotation;
* {@code @Target(ElementType.FIELD)} may only be written as a modifier for a * {@code @Target(ElementType.FIELD)} may only be written as a modifier for a
* field declaration. * field declaration.
* *
* <p>The constant {@link #TYPE_USE} corresponds to the 15 type contexts in JLS * <p>The constant {@link #TYPE_USE} corresponds to the type contexts in JLS
* 4.11, as well as to two declaration contexts: type declarations (including * 4.11, as well as to two declaration contexts: type declarations (including
* annotation type declarations) and type parameter declarations. * annotation type declarations) and type parameter declarations.
* *

View File

@ -30,6 +30,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URI; import java.net.URI;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@ -163,9 +164,12 @@ public interface ModuleReader extends Closeable {
* @param bb * @param bb
* The byte buffer to release * The byte buffer to release
* *
* @implSpec The default implementation does nothing. * @implSpec The default implementation doesn't do anything except check
* if the byte buffer is null.
*/ */
default void release(ByteBuffer bb) { } default void release(ByteBuffer bb) {
Objects.requireNonNull(bb);
}
/** /**
* Closes the module reader. Once closed then subsequent calls to locate or * Closes the module reader. Once closed then subsequent calls to locate or

View File

@ -272,9 +272,9 @@ class SystemModuleFinder implements ModuleFinder {
* if not found. * if not found.
*/ */
private ImageLocation findImageLocation(String name) throws IOException { private ImageLocation findImageLocation(String name) throws IOException {
Objects.requireNonNull(name);
if (closed) if (closed)
throw new IOException("ModuleReader is closed"); throw new IOException("ModuleReader is closed");
if (imageReader != null) { if (imageReader != null) {
return imageReader.findLocation(module, name); return imageReader.findLocation(module, name);
} else { } else {
@ -322,6 +322,7 @@ class SystemModuleFinder implements ModuleFinder {
@Override @Override
public void release(ByteBuffer bb) { public void release(ByteBuffer bb) {
Objects.requireNonNull(bb);
ImageReader.releaseByteBuffer(bb); ImageReader.releaseByteBuffer(bb);
} }

View File

@ -75,11 +75,12 @@ import sun.security.util.SecurityConstants;
* *
* <p> A Java virtual machine has at least one non-empty layer, the {@link * <p> A Java virtual machine has at least one non-empty layer, the {@link
* #boot() boot} layer, that is created when the Java virtual machine is * #boot() boot} layer, that is created when the Java virtual machine is
* started. The <em>system modules</em>, including {@code java.base}, are in * started. The boot layer contains module {@code java.base} and is the only
* the boot layer. The modules in the boot layer are mapped to the bootstrap * layer in the Java virtual machine with a module named "{@code java.base}".
* class loader and other class loaders that are built-in into the Java virtual * The modules in the boot layer are mapped to the bootstrap class loader and
* machine. The boot layer will often be the {@link #parent() parent} when * other class loaders that are <a href="../ClassLoader.html#builtinLoaders">
* creating additional layers. </p> * built-in</a> into the Java virtual machine. The boot layer will often be
* the {@link #parent() parent} when creating additional layers. </p>
* *
* <p> As when creating a {@code Configuration}, * <p> As when creating a {@code Configuration},
* {@link ModuleDescriptor#isAutomatic() automatic} modules receive * {@link ModuleDescriptor#isAutomatic() automatic} modules receive
@ -204,7 +205,8 @@ public final class Layer {
* for this layer * for this layer
* @throws LayerInstantiationException * @throws LayerInstantiationException
* If all modules cannot be defined to the same class loader for any * If all modules cannot be defined to the same class loader for any
* of the reasons listed above * of the reasons listed above or the layer cannot be created because
* the configuration contains a module named "{@code java.base}"
* @throws SecurityException * @throws SecurityException
* If {@code RuntimePermission("createClassLoader")} or * If {@code RuntimePermission("createClassLoader")} or
* {@code RuntimePermission("getClassLoader")} is denied by * {@code RuntimePermission("getClassLoader")} is denied by
@ -219,14 +221,13 @@ public final class Layer {
checkCreateClassLoaderPermission(); checkCreateClassLoaderPermission();
checkGetClassLoaderPermission(); checkGetClassLoaderPermission();
Loader loader;
try { try {
loader = new Loader(cf.modules(), parentLoader); Loader loader = new Loader(cf.modules(), parentLoader);
loader.initRemotePackageMap(cf, this); loader.initRemotePackageMap(cf, this);
return new Layer(cf, this, mn -> loader);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new LayerInstantiationException(e.getMessage()); throw new LayerInstantiationException(e.getMessage());
} }
return new Layer(cf, this, mn -> loader);
} }
@ -266,6 +267,9 @@ public final class Layer {
* @throws IllegalArgumentException * @throws IllegalArgumentException
* If the parent of the given configuration is not the configuration * If the parent of the given configuration is not the configuration
* for this layer * for this layer
* @throws LayerInstantiationException
* If the layer cannot be created because the configuration contains
* a module named "{@code java.base}"
* @throws SecurityException * @throws SecurityException
* If {@code RuntimePermission("createClassLoader")} or * If {@code RuntimePermission("createClassLoader")} or
* {@code RuntimePermission("getClassLoader")} is denied by * {@code RuntimePermission("getClassLoader")} is denied by
@ -281,7 +285,11 @@ public final class Layer {
checkGetClassLoaderPermission(); checkGetClassLoaderPermission();
LoaderPool pool = new LoaderPool(cf, this, parentLoader); LoaderPool pool = new LoaderPool(cf, this, parentLoader);
return new Layer(cf, this, pool::loaderFor); try {
return new Layer(cf, this, pool::loaderFor);
} catch (IllegalArgumentException e) {
throw new LayerInstantiationException(e.getMessage());
}
} }
@ -330,7 +338,8 @@ public final class Layer {
* for this layer * for this layer
* @throws LayerInstantiationException * @throws LayerInstantiationException
* If creating the {@code Layer} fails for any of the reasons * If creating the {@code Layer} fails for any of the reasons
* listed above * listed above or the layer cannot be created because the
* configuration contains a module named "{@code java.base}"
* @throws SecurityException * @throws SecurityException
* If {@code RuntimePermission("getClassLoader")} is denied by * If {@code RuntimePermission("getClassLoader")} is denied by
* the security manager * the security manager

View File

@ -513,7 +513,7 @@ public final class Module {
* package {@code pn} to the given module. * package {@code pn} to the given module.
* *
* <p> This method has no effect if the package is already exported to the * <p> This method has no effect if the package is already exported to the
* given module. If also has no effect if invoked on an unnamed module (as * given module. It also has no effect if invoked on an unnamed module (as
* unnamed modules export all packages). </p> * unnamed modules export all packages). </p>
* *
* @param pn * @param pn
@ -866,7 +866,7 @@ public final class Module {
URI uri = mref.location().orElse(null); URI uri = mref.location().orElse(null);
Module m; Module m;
if (loader == null && name.equals("java.base")) { if (loader == null && name.equals("java.base") && Layer.boot() == null) {
m = Object.class.getModule(); m = Object.class.getModule();
} else { } else {
m = new Module(layer, loader, descriptor, uri); m = new Module(layer, loader, descriptor, uri);

View File

@ -55,7 +55,7 @@ import java.util.Arrays;
* object to the operation. In either case, eight <em>rounding * object to the operation. In either case, eight <em>rounding
* modes</em> are provided for the control of rounding. Using the * modes</em> are provided for the control of rounding. Using the
* integer fields in this class (such as {@link #ROUND_HALF_UP}) to * integer fields in this class (such as {@link #ROUND_HALF_UP}) to
* represent rounding mode is largely obsolete; the enumeration values * represent rounding mode is deprecated; the enumeration values
* of the {@code RoundingMode} {@code enum}, (such as {@link * of the {@code RoundingMode} {@code enum}, (such as {@link
* RoundingMode#HALF_UP}) should be used instead. * RoundingMode#HALF_UP}) should be used instead.
* *
@ -93,7 +93,7 @@ import java.util.Arrays;
* <p>In general the rounding modes and precision setting determine * <p>In general the rounding modes and precision setting determine
* how operations return results with a limited number of digits when * how operations return results with a limited number of digits when
* the exact result has more digits (perhaps infinitely many in the * the exact result has more digits (perhaps infinitely many in the
* case of division) than the number of digits returned. * case of division and square root) than the number of digits returned.
* *
* First, the * First, the
* total number of digits to return is specified by the * total number of digits to return is specified by the
@ -196,18 +196,19 @@ import java.util.Arrays;
* {@code BigDecimal} value; for example [19, 2] is the * {@code BigDecimal} value; for example [19, 2] is the
* {@code BigDecimal} numerically equal to 0.19 having a scale of 2. * {@code BigDecimal} numerically equal to 0.19 having a scale of 2.
* *
* <p>Note: care should be exercised if {@code BigDecimal} objects
* are used as keys in a {@link java.util.SortedMap SortedMap} or
* elements in a {@link java.util.SortedSet SortedSet} since
* {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent
* with equals</i>. See {@link Comparable}, {@link
* java.util.SortedMap} or {@link java.util.SortedSet} for more
* information.
* *
* <p>All methods and constructors for this class throw * <p>All methods and constructors for this class throw
* {@code NullPointerException} when passed a {@code null} object * {@code NullPointerException} when passed a {@code null} object
* reference for any input parameter. * reference for any input parameter.
* *
* @apiNote Care should be exercised if {@code BigDecimal} objects
* are used as keys in a {@link java.util.SortedMap SortedMap} or
* elements in a {@link java.util.SortedSet SortedSet} since
* {@code BigDecimal}'s <i>natural ordering</i> is <em>inconsistent
* with equals</em>. See {@link Comparable}, {@link
* java.util.SortedMap} or {@link java.util.SortedSet} for more
* information.
*
* @see BigInteger * @see BigInteger
* @see MathContext * @see MathContext
* @see RoundingMode * @see RoundingMode
@ -377,10 +378,10 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* same sequence of characters as the {@link #BigDecimal(String)} * same sequence of characters as the {@link #BigDecimal(String)}
* constructor, while allowing a sub-array to be specified. * constructor, while allowing a sub-array to be specified.
* *
* <p>Note that if the sequence of characters is already available * @implNote If the sequence of characters is already available
* within a character array, using this constructor is faster than * within a character array, using this constructor is faster than
* converting the {@code char} array to string and using the * converting the {@code char} array to string and using the
* {@code BigDecimal(String)} constructor . * {@code BigDecimal(String)} constructor.
* *
* @param in {@code char} array that is the source of characters. * @param in {@code char} array that is the source of characters.
* @param offset first character in the array to inspect. * @param offset first character in the array to inspect.
@ -401,14 +402,14 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* constructor, while allowing a sub-array to be specified and * constructor, while allowing a sub-array to be specified and
* with rounding according to the context settings. * with rounding according to the context settings.
* *
* <p>Note that if the sequence of characters is already available * @implNote If the sequence of characters is already available
* within a character array, using this constructor is faster than * within a character array, using this constructor is faster than
* converting the {@code char} array to string and using the * converting the {@code char} array to string and using the
* {@code BigDecimal(String)} constructor. * {@code BigDecimal(String)} constructor.
* *
* @param in {@code char} array that is the source of characters. * @param in {@code char} array that is the source of characters.
* @param offset first character in the array to inspect. * @param offset first character in the array to inspect.
* @param len number of characters to consider.. * @param len number of characters to consider.
* @param mc the context to use. * @param mc the context to use.
* @throws ArithmeticException if the result is inexact but the * @throws ArithmeticException if the result is inexact but the
* rounding mode is {@code UNNECESSARY}. * rounding mode is {@code UNNECESSARY}.
@ -679,10 +680,10 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* same sequence of characters as the {@link #BigDecimal(String)} * same sequence of characters as the {@link #BigDecimal(String)}
* constructor. * constructor.
* *
* <p>Note that if the sequence of characters is already available * @implNote If the sequence of characters is already available
* as a character array, using this constructor is faster than * as a character array, using this constructor is faster than
* converting the {@code char} array to string and using the * converting the {@code char} array to string and using the
* {@code BigDecimal(String)} constructor . * {@code BigDecimal(String)} constructor.
* *
* @param in {@code char} array that is the source of characters. * @param in {@code char} array that is the source of characters.
* @throws NumberFormatException if {@code in} is not a valid * @throws NumberFormatException if {@code in} is not a valid
@ -700,10 +701,10 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* constructor and with rounding according to the context * constructor and with rounding according to the context
* settings. * settings.
* *
* <p>Note that if the sequence of characters is already available * @implNote If the sequence of characters is already available
* as a character array, using this constructor is faster than * as a character array, using this constructor is faster than
* converting the {@code char} array to string and using the * converting the {@code char} array to string and using the
* {@code BigDecimal(String)} constructor . * {@code BigDecimal(String)} constructor.
* *
* @param in {@code char} array that is the source of characters. * @param in {@code char} array that is the source of characters.
* @param mc the context to use. * @param mc the context to use.
@ -805,7 +806,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* "-0" [0,0] * "-0" [0,0]
* </pre> * </pre>
* *
* <p>Note: For values other than {@code float} and * @apiNote For values other than {@code float} and
* {@code double} NaN and &plusmn;Infinity, this constructor is * {@code double} NaN and &plusmn;Infinity, this constructor is
* compatible with the values returned by {@link Float#toString} * compatible with the values returned by {@link Float#toString}
* and {@link Double#toString}. This is generally the preferred * and {@link Double#toString}. This is generally the preferred
@ -859,13 +860,13 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* This is because 0.1 cannot be represented exactly as a * This is because 0.1 cannot be represented exactly as a
* {@code double} (or, for that matter, as a binary fraction of * {@code double} (or, for that matter, as a binary fraction of
* any finite length). Thus, the value that is being passed * any finite length). Thus, the value that is being passed
* <i>in</i> to the constructor is not exactly equal to 0.1, * <em>in</em> to the constructor is not exactly equal to 0.1,
* appearances notwithstanding. * appearances notwithstanding.
* *
* <li> * <li>
* The {@code String} constructor, on the other hand, is * The {@code String} constructor, on the other hand, is
* perfectly predictable: writing {@code new BigDecimal("0.1")} * perfectly predictable: writing {@code new BigDecimal("0.1")}
* creates a {@code BigDecimal} which is <i>exactly</i> equal to * creates a {@code BigDecimal} which is <em>exactly</em> equal to
* 0.1, as one would expect. Therefore, it is generally * 0.1, as one would expect. Therefore, it is generally
* recommended that the {@linkplain #BigDecimal(String) * recommended that the {@linkplain #BigDecimal(String)
* String constructor} be used in preference to this one. * String constructor} be used in preference to this one.
@ -1199,10 +1200,11 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
/** /**
* Translates a {@code long} unscaled value and an * Translates a {@code long} unscaled value and an
* {@code int} scale into a {@code BigDecimal}. This * {@code int} scale into a {@code BigDecimal}.
* {@literal "static factory method"} is provided in preference to *
* a ({@code long}, {@code int}) constructor because it * @apiNote This static factory method is provided in preference
* allows for reuse of frequently used {@code BigDecimal} values.. * to a ({@code long}, {@code int}) constructor because it allows
* for reuse of frequently used {@code BigDecimal} values.
* *
* @param unscaledVal unscaled value of the {@code BigDecimal}. * @param unscaledVal unscaled value of the {@code BigDecimal}.
* @param scale scale of the {@code BigDecimal}. * @param scale scale of the {@code BigDecimal}.
@ -1222,10 +1224,11 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
/** /**
* Translates a {@code long} value into a {@code BigDecimal} * Translates a {@code long} value into a {@code BigDecimal}
* with a scale of zero. This {@literal "static factory method"} * with a scale of zero.
* is provided in preference to a ({@code long}) constructor *
* because it allows for reuse of frequently used * @apiNote This static factory method is provided in preference
* {@code BigDecimal} values. * to a ({@code long}) constructor because it allows for reuse of
* frequently used {@code BigDecimal} values.
* *
* @param val value of the {@code BigDecimal}. * @param val value of the {@code BigDecimal}.
* @return a {@code BigDecimal} whose value is {@code val}. * @return a {@code BigDecimal} whose value is {@code val}.
@ -1270,11 +1273,11 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* the {@code double}'s canonical string representation provided * the {@code double}'s canonical string representation provided
* by the {@link Double#toString(double)} method. * by the {@link Double#toString(double)} method.
* *
* <p><b>Note:</b> This is generally the preferred way to convert * @apiNote This is generally the preferred way to convert a
* a {@code double} (or {@code float}) into a * {@code double} (or {@code float}) into a {@code BigDecimal}, as
* {@code BigDecimal}, as the value returned is equal to that * the value returned is equal to that resulting from constructing
* resulting from constructing a {@code BigDecimal} from the * a {@code BigDecimal} from the result of using {@link
* result of using {@link Double#toString(double)}. * Double#toString(double)}.
* *
* @param val {@code double} to convert to a {@code BigDecimal}. * @param val {@code double} to convert to a {@code BigDecimal}.
* @return a {@code BigDecimal} whose value is equal to or approximately * @return a {@code BigDecimal} whose value is equal to or approximately
@ -1896,7 +1899,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* *
* <p>The remainder is given by * <p>The remainder is given by
* {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}. * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
* Note that this is not the modulo operation (the result can be * Note that this is <em>not</em> the modulo operation (the result can be
* negative). * negative).
* *
* @param divisor value by which this {@code BigDecimal} is to be divided. * @param divisor value by which this {@code BigDecimal} is to be divided.
@ -2037,6 +2040,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* {@code (mc.getRoundingMode()==RoundingMode.UNNECESSARY}) and * {@code (mc.getRoundingMode()==RoundingMode.UNNECESSARY}) and
* the exact result cannot fit in {@code mc.getPrecision()} * the exact result cannot fit in {@code mc.getPrecision()}
* digits. * digits.
* @see BigInteger#sqrt()
* @since 9 * @since 9
*/ */
public BigDecimal sqrt(MathContext mc) { public BigDecimal sqrt(MathContext mc) {
@ -2694,8 +2698,8 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* in this case, the specified rounding mode is applied to the * in this case, the specified rounding mode is applied to the
* division. * division.
* *
* <p>Note that since BigDecimal objects are immutable, calls of * @apiNote Since BigDecimal objects are immutable, calls of
* this method do <i>not</i> result in the original object being * this method do <em>not</em> result in the original object being
* modified, contrary to the usual convention of having methods * modified, contrary to the usual convention of having methods
* named <code>set<i>X</i></code> mutate field <i>{@code X}</i>. * named <code>set<i>X</i></code> mutate field <i>{@code X}</i>.
* Instead, {@code setScale} returns an object with the proper * Instead, {@code setScale} returns an object with the proper
@ -2727,8 +2731,8 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* in this case, the specified rounding mode is applied to the * in this case, the specified rounding mode is applied to the
* division. * division.
* *
* <p>Note that since BigDecimal objects are immutable, calls of * @apiNote Since BigDecimal objects are immutable, calls of
* this method do <i>not</i> result in the original object being * this method do <em>not</em> result in the original object being
* modified, contrary to the usual convention of having methods * modified, contrary to the usual convention of having methods
* named <code>set<i>X</i></code> mutate field <i>{@code X}</i>. * named <code>set<i>X</i></code> mutate field <i>{@code X}</i>.
* Instead, {@code setScale} returns an object with the proper * Instead, {@code setScale} returns an object with the proper
@ -2822,8 +2826,8 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* versions of {@code setScale}, but saves the caller the trouble * versions of {@code setScale}, but saves the caller the trouble
* of specifying a rounding mode in cases where it is irrelevant. * of specifying a rounding mode in cases where it is irrelevant.
* *
* <p>Note that since {@code BigDecimal} objects are immutable, * @apiNote Since {@code BigDecimal} objects are immutable,
* calls of this method do <i>not</i> result in the original * calls of this method do <em>not</em> result in the original
* object being modified, contrary to the usual convention of * object being modified, contrary to the usual convention of
* having methods named <code>set<i>X</i></code> mutate field * having methods named <code>set<i>X</i></code> mutate field
* <i>{@code X}</i>. Instead, {@code setScale} returns an * <i>{@code X}</i>. Instead, {@code setScale} returns an
@ -3091,7 +3095,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
/** /**
* Returns the hash code for this {@code BigDecimal}. Note that * Returns the hash code for this {@code BigDecimal}. Note that
* two {@code BigDecimal} objects that are numerically equal but * two {@code BigDecimal} objects that are numerically equal but
* differ in scale (like 2.0 and 2.00) will generally <i>not</i> * differ in scale (like 2.0 and 2.00) will generally <em>not</em>
* have the same hash code. * have the same hash code.
* *
* @return hash code for this {@code BigDecimal}. * @return hash code for this {@code BigDecimal}.
@ -3342,7 +3346,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* Converts this {@code BigDecimal} to a {@code BigInteger}. * Converts this {@code BigDecimal} to a {@code BigInteger}.
* This conversion is analogous to the * This conversion is analogous to the
* <i>narrowing primitive conversion</i> from {@code double} to * <i>narrowing primitive conversion</i> from {@code double} to
* {@code long} as defined in section 5.1.3 of * {@code long} as defined in
* <cite>The Java&trade; Language Specification</cite>: * <cite>The Java&trade; Language Specification</cite>:
* any fractional part of this * any fractional part of this
* {@code BigDecimal} will be discarded. Note that this * {@code BigDecimal} will be discarded. Note that this
@ -3354,6 +3358,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* {@link #toBigIntegerExact()} method. * {@link #toBigIntegerExact()} method.
* *
* @return this {@code BigDecimal} converted to a {@code BigInteger}. * @return this {@code BigDecimal} converted to a {@code BigInteger}.
* @jls 5.1.3 Narrowing Primitive Conversion
*/ */
public BigInteger toBigInteger() { public BigInteger toBigInteger() {
// force to an integer, quietly // force to an integer, quietly
@ -3379,7 +3384,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* Converts this {@code BigDecimal} to a {@code long}. * Converts this {@code BigDecimal} to a {@code long}.
* This conversion is analogous to the * This conversion is analogous to the
* <i>narrowing primitive conversion</i> from {@code double} to * <i>narrowing primitive conversion</i> from {@code double} to
* {@code short} as defined in section 5.1.3 of * {@code short} as defined in
* <cite>The Java&trade; Language Specification</cite>: * <cite>The Java&trade; Language Specification</cite>:
* any fractional part of this * any fractional part of this
* {@code BigDecimal} will be discarded, and if the resulting * {@code BigDecimal} will be discarded, and if the resulting
@ -3390,6 +3395,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* as return a result with the opposite sign. * as return a result with the opposite sign.
* *
* @return this {@code BigDecimal} converted to a {@code long}. * @return this {@code BigDecimal} converted to a {@code long}.
* @jls 5.1.3 Narrowing Primitive Conversion
*/ */
@Override @Override
public long longValue(){ public long longValue(){
@ -3448,7 +3454,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* Converts this {@code BigDecimal} to an {@code int}. * Converts this {@code BigDecimal} to an {@code int}.
* This conversion is analogous to the * This conversion is analogous to the
* <i>narrowing primitive conversion</i> from {@code double} to * <i>narrowing primitive conversion</i> from {@code double} to
* {@code short} as defined in section 5.1.3 of * {@code short} as defined in
* <cite>The Java&trade; Language Specification</cite>: * <cite>The Java&trade; Language Specification</cite>:
* any fractional part of this * any fractional part of this
* {@code BigDecimal} will be discarded, and if the resulting * {@code BigDecimal} will be discarded, and if the resulting
@ -3459,6 +3465,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* value as well as return a result with the opposite sign. * value as well as return a result with the opposite sign.
* *
* @return this {@code BigDecimal} converted to an {@code int}. * @return this {@code BigDecimal} converted to an {@code int}.
* @jls 5.1.3 Narrowing Primitive Conversion
*/ */
@Override @Override
public int intValue() { public int intValue() {
@ -3531,7 +3538,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* Converts this {@code BigDecimal} to a {@code float}. * Converts this {@code BigDecimal} to a {@code float}.
* This conversion is similar to the * This conversion is similar to the
* <i>narrowing primitive conversion</i> from {@code double} to * <i>narrowing primitive conversion</i> from {@code double} to
* {@code float} as defined in section 5.1.3 of * {@code float} as defined in
* <cite>The Java&trade; Language Specification</cite>: * <cite>The Java&trade; Language Specification</cite>:
* if this {@code BigDecimal} has too great a * if this {@code BigDecimal} has too great a
* magnitude to represent as a {@code float}, it will be * magnitude to represent as a {@code float}, it will be
@ -3542,6 +3549,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* value. * value.
* *
* @return this {@code BigDecimal} converted to a {@code float}. * @return this {@code BigDecimal} converted to a {@code float}.
* @jls 5.1.3 Narrowing Primitive Conversion
*/ */
@Override @Override
public float floatValue(){ public float floatValue(){
@ -3575,7 +3583,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* Converts this {@code BigDecimal} to a {@code double}. * Converts this {@code BigDecimal} to a {@code double}.
* This conversion is similar to the * This conversion is similar to the
* <i>narrowing primitive conversion</i> from {@code double} to * <i>narrowing primitive conversion</i> from {@code double} to
* {@code float} as defined in section 5.1.3 of * {@code float} as defined in
* <cite>The Java&trade; Language Specification</cite>: * <cite>The Java&trade; Language Specification</cite>:
* if this {@code BigDecimal} has too great a * if this {@code BigDecimal} has too great a
* magnitude represent as a {@code double}, it will be * magnitude represent as a {@code double}, it will be
@ -3586,6 +3594,7 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* value. * value.
* *
* @return this {@code BigDecimal} converted to a {@code double}. * @return this {@code BigDecimal} converted to a {@code double}.
* @jls 5.1.3 Narrowing Primitive Conversion
*/ */
@Override @Override
public double doubleValue(){ public double doubleValue(){

View File

@ -116,6 +116,7 @@ import jdk.internal.HotSpotIntrinsicCandidate;
* +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive). * +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive).
* *
* @see BigDecimal * @see BigDecimal
* @jls 4.2.2 Integer Operations
* @author Josh Bloch * @author Josh Bloch
* @author Michael McCloskey * @author Michael McCloskey
* @author Alan Eliasen * @author Alan Eliasen
@ -126,7 +127,7 @@ import jdk.internal.HotSpotIntrinsicCandidate;
public class BigInteger extends Number implements Comparable<BigInteger> { public class BigInteger extends Number implements Comparable<BigInteger> {
/** /**
* The signum of this BigInteger: -1 for negative, 0 for zero, or * The signum of this BigInteger: -1 for negative, 0 for zero, or
* 1 for positive. Note that the BigInteger zero <i>must</i> have * 1 for positive. Note that the BigInteger zero <em>must</em> have
* a signum of 0. This is necessary to ensures that there is exactly one * a signum of 0. This is necessary to ensures that there is exactly one
* representation for each BigInteger value. * representation for each BigInteger value.
*/ */
@ -710,7 +711,7 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
* Constructs a randomly generated positive BigInteger that is probably * Constructs a randomly generated positive BigInteger that is probably
* prime, with the specified bitLength. * prime, with the specified bitLength.
* *
* <p>It is recommended that the {@link #probablePrime probablePrime} * @apiNote It is recommended that the {@link #probablePrime probablePrime}
* method be used in preference to this constructor unless there * method be used in preference to this constructor unless there
* is a compelling need to specify a certainty. * is a compelling need to specify a certainty.
* *
@ -1157,9 +1158,11 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
/** /**
* Returns a BigInteger whose value is equal to that of the * Returns a BigInteger whose value is equal to that of the
* specified {@code long}. This "static factory method" is * specified {@code long}.
* provided in preference to a ({@code long}) constructor *
* because it allows for reuse of frequently used BigIntegers. * @apiNote This static factory method is provided in preference
* to a ({@code long}) constructor because it allows for reuse of
* frequently used BigIntegers.
* *
* @param val value of the BigInteger to return. * @param val value of the BigInteger to return.
* @return a BigInteger with the specified value. * @return a BigInteger with the specified value.
@ -3551,13 +3554,13 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
/** /**
* Returns the number of bits in the minimal two's-complement * Returns the number of bits in the minimal two's-complement
* representation of this BigInteger, <i>excluding</i> a sign bit. * representation of this BigInteger, <em>excluding</em> a sign bit.
* For positive BigIntegers, this is equivalent to the number of bits in * For positive BigIntegers, this is equivalent to the number of bits in
* the ordinary binary representation. (Computes * the ordinary binary representation. (Computes
* {@code (ceil(log2(this < 0 ? -this : this+1)))}.) * {@code (ceil(log2(this < 0 ? -this : this+1)))}.)
* *
* @return number of bits in the minimal two's-complement * @return number of bits in the minimal two's-complement
* representation of this BigInteger, <i>excluding</i> a sign bit. * representation of this BigInteger, <em>excluding</em> a sign bit.
*/ */
public int bitLength() { public int bitLength() {
int n = bitLengthPlusOne - 1; int n = bitLengthPlusOne - 1;
@ -4034,7 +4037,7 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
* Converts this BigInteger to an {@code int}. This * Converts this BigInteger to an {@code int}. This
* conversion is analogous to a * conversion is analogous to a
* <i>narrowing primitive conversion</i> from {@code long} to * <i>narrowing primitive conversion</i> from {@code long} to
* {@code int} as defined in section 5.1.3 of * {@code int} as defined in
* <cite>The Java&trade; Language Specification</cite>: * <cite>The Java&trade; Language Specification</cite>:
* if this BigInteger is too big to fit in an * if this BigInteger is too big to fit in an
* {@code int}, only the low-order 32 bits are returned. * {@code int}, only the low-order 32 bits are returned.
@ -4044,6 +4047,7 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
* *
* @return this BigInteger converted to an {@code int}. * @return this BigInteger converted to an {@code int}.
* @see #intValueExact() * @see #intValueExact()
* @jls 5.1.3 Narrowing Primitive Conversion
*/ */
public int intValue() { public int intValue() {
int result = 0; int result = 0;
@ -4055,7 +4059,7 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
* Converts this BigInteger to a {@code long}. This * Converts this BigInteger to a {@code long}. This
* conversion is analogous to a * conversion is analogous to a
* <i>narrowing primitive conversion</i> from {@code long} to * <i>narrowing primitive conversion</i> from {@code long} to
* {@code int} as defined in section 5.1.3 of * {@code int} as defined in
* <cite>The Java&trade; Language Specification</cite>: * <cite>The Java&trade; Language Specification</cite>:
* if this BigInteger is too big to fit in a * if this BigInteger is too big to fit in a
* {@code long}, only the low-order 64 bits are returned. * {@code long}, only the low-order 64 bits are returned.
@ -4065,6 +4069,7 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
* *
* @return this BigInteger converted to a {@code long}. * @return this BigInteger converted to a {@code long}.
* @see #longValueExact() * @see #longValueExact()
* @jls 5.1.3 Narrowing Primitive Conversion
*/ */
public long longValue() { public long longValue() {
long result = 0; long result = 0;
@ -4078,7 +4083,7 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
* Converts this BigInteger to a {@code float}. This * Converts this BigInteger to a {@code float}. This
* conversion is similar to the * conversion is similar to the
* <i>narrowing primitive conversion</i> from {@code double} to * <i>narrowing primitive conversion</i> from {@code double} to
* {@code float} as defined in section 5.1.3 of * {@code float} as defined in
* <cite>The Java&trade; Language Specification</cite>: * <cite>The Java&trade; Language Specification</cite>:
* if this BigInteger has too great a magnitude * if this BigInteger has too great a magnitude
* to represent as a {@code float}, it will be converted to * to represent as a {@code float}, it will be converted to
@ -4088,6 +4093,7 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
* information about the precision of the BigInteger value. * information about the precision of the BigInteger value.
* *
* @return this BigInteger converted to a {@code float}. * @return this BigInteger converted to a {@code float}.
* @jls 5.1.3 Narrowing Primitive Conversion
*/ */
public float floatValue() { public float floatValue() {
if (signum == 0) { if (signum == 0) {
@ -4162,7 +4168,7 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
* Converts this BigInteger to a {@code double}. This * Converts this BigInteger to a {@code double}. This
* conversion is similar to the * conversion is similar to the
* <i>narrowing primitive conversion</i> from {@code double} to * <i>narrowing primitive conversion</i> from {@code double} to
* {@code float} as defined in section 5.1.3 of * {@code float} as defined in
* <cite>The Java&trade; Language Specification</cite>: * <cite>The Java&trade; Language Specification</cite>:
* if this BigInteger has too great a magnitude * if this BigInteger has too great a magnitude
* to represent as a {@code double}, it will be converted to * to represent as a {@code double}, it will be converted to
@ -4172,6 +4178,7 @@ public class BigInteger extends Number implements Comparable<BigInteger> {
* information about the precision of the BigInteger value. * information about the precision of the BigInteger value.
* *
* @return this BigInteger converted to a {@code double}. * @return this BigInteger converted to a {@code double}.
* @jls 5.1.3 Narrowing Primitive Conversion
*/ */
public double doubleValue() { public double doubleValue() {
if (signum == 0) { if (signum == 0) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -23,7 +23,10 @@
* questions. * questions.
*/ */
package java.net; package java.net;
import java.io.IOException; import java.io.IOException;
import static java.net.InetAddress.PREFER_IPV6_VALUE;
import static java.net.InetAddress.PREFER_SYSTEM_VALUE;
/* /*
* Package private implementation of InetAddressImpl for dual * Package private implementation of InetAddressImpl for dual
@ -35,15 +38,23 @@ import java.io.IOException;
* *
* @since 1.4 * @since 1.4
*/ */
class Inet6AddressImpl implements InetAddressImpl { class Inet6AddressImpl implements InetAddressImpl {
public native String getLocalHostName() throws UnknownHostException;
public native InetAddress[]
lookupAllHostAddr(String hostname) throws UnknownHostException;
public native String getHostByAddr(byte[] addr) throws UnknownHostException;
private native boolean isReachable0(byte[] addr, int scope, int timeout, byte[] inf, int ttl, int if_scope) throws IOException;
public boolean isReachable(InetAddress addr, int timeout, NetworkInterface netif, int ttl) throws IOException { public native String getLocalHostName() throws UnknownHostException;
public native InetAddress[] lookupAllHostAddr(String hostname)
throws UnknownHostException;
public native String getHostByAddr(byte[] addr) throws UnknownHostException;
private native boolean isReachable0(byte[] addr, int scope, int timeout,
byte[] inf, int ttl, int if_scope)
throws IOException;
public boolean isReachable(InetAddress addr, int timeout,
NetworkInterface netif, int ttl)
throws IOException
{
byte[] ifaddr = null; byte[] ifaddr = null;
int scope = -1; int scope = -1;
int netif_scope = -1; int netif_scope = -1;
@ -79,7 +90,8 @@ class Inet6AddressImpl implements InetAddressImpl {
public synchronized InetAddress anyLocalAddress() { public synchronized InetAddress anyLocalAddress() {
if (anyLocalAddress == null) { if (anyLocalAddress == null) {
if (InetAddress.preferIPv6Address) { if (InetAddress.preferIPv6Address == PREFER_IPV6_VALUE ||
InetAddress.preferIPv6Address == PREFER_SYSTEM_VALUE) {
anyLocalAddress = new Inet6Address(); anyLocalAddress = new Inet6Address();
anyLocalAddress.holder().hostName = "::"; anyLocalAddress.holder().hostName = "::";
} else { } else {
@ -91,7 +103,8 @@ class Inet6AddressImpl implements InetAddressImpl {
public synchronized InetAddress loopbackAddress() { public synchronized InetAddress loopbackAddress() {
if (loopbackAddress == null) { if (loopbackAddress == null) {
if (InetAddress.preferIPv6Address) { if (InetAddress.preferIPv6Address == PREFER_IPV6_VALUE ||
InetAddress.preferIPv6Address == PREFER_SYSTEM_VALUE) {
byte[] loopback = byte[] loopback =
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
@ -103,6 +116,6 @@ class Inet6AddressImpl implements InetAddressImpl {
return loopbackAddress; return loopbackAddress;
} }
private InetAddress anyLocalAddress; private InetAddress anyLocalAddress;
private InetAddress loopbackAddress; private InetAddress loopbackAddress;
} }

View File

@ -26,8 +26,6 @@
package java.net; package java.net;
import java.util.NavigableSet; import java.util.NavigableSet;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Objects; import java.util.Objects;
import java.util.Scanner; import java.util.Scanner;
@ -41,6 +39,7 @@ import java.io.ObjectInputStream;
import java.io.ObjectInputStream.GetField; import java.io.ObjectInputStream.GetField;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.io.ObjectOutputStream.PutField; import java.io.ObjectOutputStream.PutField;
import java.lang.annotation.Native;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.ConcurrentSkipListSet;
@ -193,6 +192,11 @@ import sun.net.util.IPAddressUtil;
*/ */
public public
class InetAddress implements java.io.Serializable { class InetAddress implements java.io.Serializable {
@Native static final int PREFER_IPV4_VALUE = 0;
@Native static final int PREFER_IPV6_VALUE = 1;
@Native static final int PREFER_SYSTEM_VALUE = 2;
/** /**
* Specify the address family: Internet Protocol, Version 4 * Specify the address family: Internet Protocol, Version 4
* @since 1.4 * @since 1.4
@ -206,8 +210,7 @@ class InetAddress implements java.io.Serializable {
static final int IPv6 = 2; static final int IPv6 = 2;
/* Specify address family preference */ /* Specify address family preference */
static transient boolean preferIPv6Address = false; static transient final int preferIPv6Address;
static class InetAddressHolder { static class InetAddressHolder {
/** /**
@ -293,8 +296,19 @@ class InetAddress implements java.io.Serializable {
* Load net library into runtime, and perform initializations. * Load net library into runtime, and perform initializations.
*/ */
static { static {
preferIPv6Address = java.security.AccessController.doPrivileged( String str = java.security.AccessController.doPrivileged(
new GetBooleanAction("java.net.preferIPv6Addresses")).booleanValue(); new GetPropertyAction("java.net.preferIPv6Addresses"));
if (str == null) {
preferIPv6Address = PREFER_IPV4_VALUE;
} else if (str.equalsIgnoreCase("true")) {
preferIPv6Address = PREFER_IPV6_VALUE;
} else if (str.equalsIgnoreCase("false")) {
preferIPv6Address = PREFER_IPV4_VALUE;
} else if (str.equalsIgnoreCase("system")) {
preferIPv6Address = PREFER_SYSTEM_VALUE;
} else {
preferIPv6Address = PREFER_IPV4_VALUE;
}
AccessController.doPrivileged( AccessController.doPrivileged(
new java.security.PrivilegedAction<>() { new java.security.PrivilegedAction<>() {
public Void run() { public Void run() {

View File

@ -1,5 +1,5 @@
<!-- <!--
Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it This code is free software; you can redistribute it and/or modify it
@ -35,7 +35,7 @@ alter the mechanisms and behavior of the various classes of the
java.net package. Some are checked only once at startup of the VM, java.net package. Some are checked only once at startup of the VM,
and therefore are best set using the -D option of the java command, and therefore are best set using the -D option of the java command,
while others have a more dynamic nature and can also be changed using while others have a more dynamic nature and can also be changed using
the <a href="../../lang/System.html#setProperty(java.lang.String,%20java.lang.String)">System.setProperty()</a> API. the <a href="../../lang/System.html#setProperty(java.lang.String,%20java.lang.String)">System.setProperty()</a> API.
The purpose of this document is to list The purpose of this document is to list
and detail all of these properties.</P> and detail all of these properties.</P>
<P>If there is no special note, a property value is checked every time it is used.</P> <P>If there is no special note, a property value is checked every time it is used.</P>
@ -58,7 +58,8 @@ and detail all of these properties.</P>
applications that depend on the representation of an IPv4 address applications that depend on the representation of an IPv4 address
(e.g. 192.168.1.1). This property can be set to <B>true</B> to (e.g. 192.168.1.1). This property can be set to <B>true</B> to
change that preference and use IPv6 addresses over IPv4 ones where change that preference and use IPv6 addresses over IPv4 ones where
possible.</P> possible, or <B>system</B> to preserve the order of the addresses as
returned by the operating system.</P>
</UL> </UL>
<P>Both of these properties are checked only once, at startup.</P> <P>Both of these properties are checked only once, at startup.</P>
<a name="Proxies"></a> <a name="Proxies"></a>
@ -73,7 +74,7 @@ of proxies.</P>
<P>The following proxy settings are used by the HTTP protocol handler.</P> <P>The following proxy settings are used by the HTTP protocol handler.</P>
<UL> <UL>
<LI><P><B>http.proxyHost</B> (default: &lt;none&gt;)<BR> <LI><P><B>http.proxyHost</B> (default: &lt;none&gt;)<BR>
The hostname, or address, of the proxy server The hostname, or address, of the proxy server
</P> </P>
<LI><P><B>http.proxyPort</B> (default: 80)<BR> <LI><P><B>http.proxyPort</B> (default: 80)<BR>
The port number of the proxy server.</P> The port number of the proxy server.</P>
@ -94,7 +95,7 @@ of proxies.</P>
<P>The following proxy settings are used by the HTTPS protocol handler.</P> <P>The following proxy settings are used by the HTTPS protocol handler.</P>
<UL> <UL>
<LI><P><B>https.proxyHost</B>(default: &lt;none&gt;)<BR> <LI><P><B>https.proxyHost</B>(default: &lt;none&gt;)<BR>
The hostname, or address, of the proxy server The hostname, or address, of the proxy server
</P> </P>
<LI><P><B>https.proxyPort</B> (default: 443)<BR> <LI><P><B>https.proxyPort</B> (default: 443)<BR>
The port number of the proxy server.</P> The port number of the proxy server.</P>
@ -105,7 +106,7 @@ of proxies.</P>
<P>The following proxy settings are used by the FTP protocol handler.</P> <P>The following proxy settings are used by the FTP protocol handler.</P>
<UL> <UL>
<LI><P><B>ftp.proxyHost</B>(default: &lt;none&gt;)<BR> <LI><P><B>ftp.proxyHost</B>(default: &lt;none&gt;)<BR>
The hostname, or address, of the proxy server The hostname, or address, of the proxy server
</P> </P>
<LI><P><B>ftp.proxyPort</B> (default: 80)<BR> <LI><P><B>ftp.proxyPort</B> (default: 80)<BR>
The port number of the proxy server.</P> The port number of the proxy server.</P>
@ -160,7 +161,7 @@ of proxies.</P>
<LI><P><B>http.agent</B> (default: &ldquo;Java/&lt;version&gt;&rdquo;)<BR> <LI><P><B>http.agent</B> (default: &ldquo;Java/&lt;version&gt;&rdquo;)<BR>
Defines the string sent in the User-Agent request header in http Defines the string sent in the User-Agent request header in http
requests. Note that the string &ldquo;Java/&lt;version&gt;&rdquo; will requests. Note that the string &ldquo;Java/&lt;version&gt;&rdquo; will
be appended to the one provided in the property (e.g. if be appended to the one provided in the property (e.g. if
-Dhttp.agent=&rdquo;foobar&rdquo; is used, the User-Agent header will -Dhttp.agent=&rdquo;foobar&rdquo; is used, the User-Agent header will
contain &ldquo;foobar Java/1.5.0&rdquo; if the version of the VM is contain &ldquo;foobar Java/1.5.0&rdquo; if the version of the VM is
1.5.0). This property is checked only once at startup.</P> 1.5.0). This property is checked only once at startup.</P>

View File

@ -28,6 +28,7 @@ package java.util;
import java.io.IOException; import java.io.IOException;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException; import java.io.ObjectStreamException;
import java.io.Serializable; import java.io.Serializable;
@ -607,7 +608,10 @@ class ImmutableCollections {
// ---------- Serialization Proxy ---------- // ---------- Serialization Proxy ----------
/** /**
* Serialization proxy class for immutable collections. * A unified serialization proxy class for the immutable collections.
*
* @serial
* @since 9
*/ */
final class CollSer implements Serializable { final class CollSer implements Serializable {
private static final long serialVersionUID = 6309168927139932177L; private static final long serialVersionUID = 6309168927139932177L;
@ -616,14 +620,114 @@ final class CollSer implements Serializable {
static final int IMM_SET = 2; static final int IMM_SET = 2;
static final int IMM_MAP = 3; static final int IMM_MAP = 3;
private final int flags; /**
private final Object[] array; * Indicates the type of collection that is serialized.
* The low order 8 bits have the value 1 for an immutable
* {@code List}, 2 for an immutable {@code Set}, and 3 for
* an immutable {@code Map}. Any other value causes an
* {@link InvalidObjectException} to be thrown. The high
* order 24 bits are zero when an instance is serialized,
* and they are ignored when an instance is deserialized.
* They can thus be used by future implementations without
* causing compatibility issues.
*
* <p>The tag value also determines the interpretation of the
* transient {@code Object[] array} field.
* For {@code List} and {@code Set}, the array's length is the size
* of the collection, and the array contains the elements of the collection.
* Null elements are not allowed. For {@code Set}, duplicate elements
* are not allowed.
*
* <p>For {@code Map}, the array's length is twice the number of mappings
* present in the map. The array length is necessarily even.
* The array contains a succession of key and value pairs:
* {@code k1, v1, k2, v2, ..., kN, vN.} Nulls are not allowed,
* and duplicate keys are not allowed.
*
* @serial
* @since 9
*/
private final int tag;
CollSer(int f, Object... a) { /**
flags = f; * @serial
* @since 9
*/
private transient Object[] array;
CollSer(int t, Object... a) {
tag = t;
array = a; array = a;
} }
/**
* Reads objects from the stream and stores them
* in the transient {@code Object[] array} field.
*
* @serialData
* A nonnegative int, indicating the count of objects,
* followed by that many objects.
*
* @param ois the ObjectInputStream from which data is read
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if a serialized class cannot be loaded
* @throws InvalidObjectException if the count is negative
* @since 9
*/
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
int len = ois.readInt();
if (len < 0) {
throw new InvalidObjectException("negative length " + len);
}
Object[] a = new Object[len];
for (int i = 0; i < len; i++) {
a[i] = ois.readObject();
}
array = a;
}
/**
* Writes objects to the stream from
* the transient {@code Object[] array} field.
*
* @serialData
* A nonnegative int, indicating the count of objects,
* followed by that many objects.
*
* @param oos the ObjectOutputStream to which data is written
* @throws IOException if an I/O error occurs
* @since 9
*/
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
oos.writeInt(array.length);
for (int i = 0; i < array.length; i++) {
oos.writeObject(array[i]);
}
}
/**
* Creates and returns an immutable collection from this proxy class.
* The instance returned is created as if by calling one of the
* static factory methods for
* <a href="List.html#immutable">List</a>,
* <a href="Map.html#immutable">Map</a>, or
* <a href="Set.html#immutable">Set</a>.
* This proxy class is the serial form for all immutable collection instances,
* regardless of implementation type. This is necessary to ensure that the
* existence of any particular implementation type is kept out of the
* serialized form.
*
* @return a collection created from this proxy object
* @throws InvalidObjectException if the tag value is illegal or if an exception
* is thrown during creation of the collection
* @throws ObjectStreamException if another serialization error has occurred
* @since 9
*/
private Object readResolve() throws ObjectStreamException { private Object readResolve() throws ObjectStreamException {
try { try {
if (array == null) { if (array == null) {
@ -631,8 +735,8 @@ final class CollSer implements Serializable {
} }
// use low order 8 bits to indicate "kind" // use low order 8 bits to indicate "kind"
// ignore high order bits // ignore high order 24 bits
switch (flags & 0xff) { switch (tag & 0xff) {
case IMM_LIST: case IMM_LIST:
return List.of(array); return List.of(array);
case IMM_SET: case IMM_SET:
@ -646,7 +750,7 @@ final class CollSer implements Serializable {
return new ImmutableCollections.MapN<>(array); return new ImmutableCollections.MapN<>(array);
} }
default: default:
throw new InvalidObjectException(String.format("invalid flags 0x%x", flags)); throw new InvalidObjectException(String.format("invalid flags 0x%x", tag));
} }
} catch (NullPointerException|IllegalArgumentException ex) { } catch (NullPointerException|IllegalArgumentException ex) {
InvalidObjectException ioe = new InvalidObjectException("invalid object"); InvalidObjectException ioe = new InvalidObjectException("invalid object");

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -107,6 +107,9 @@ import java.util.function.UnaryOperator;
* Factories are free to create new instances or reuse existing ones. Therefore, * Factories are free to create new instances or reuse existing ones. Therefore,
* identity-sensitive operations on these instances (reference equality ({@code ==}), * identity-sensitive operations on these instances (reference equality ({@code ==}),
* identity hash code, and synchronization) are unreliable and should be avoided. * identity hash code, and synchronization) are unreliable and should be avoided.
* <li>They are serialized as specified on the
* <a href="{@docRoot}/serialized-form.html#java.util.CollSer">Serialized Form</a>
* page.
* </ul> * </ul>
* *
* <p>This interface is a member of the * <p>This interface is a member of the

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -133,6 +133,9 @@ import java.io.Serializable;
* Factories are free to create new instances or reuse existing ones. Therefore, * Factories are free to create new instances or reuse existing ones. Therefore,
* identity-sensitive operations on these instances (reference equality ({@code ==}), * identity-sensitive operations on these instances (reference equality ({@code ==}),
* identity hash code, and synchronization) are unreliable and should be avoided. * identity hash code, and synchronization) are unreliable and should be avoided.
* <li>They are serialized as specified on the
* <a href="{@docRoot}/serialized-form.html#java.util.CollSer">Serialized Form</a>
* page.
* </ul> * </ul>
* *
* <p>This interface is a member of the * <p>This interface is a member of the

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -84,6 +84,9 @@ package java.util;
* Factories are free to create new instances or reuse existing ones. Therefore, * Factories are free to create new instances or reuse existing ones. Therefore,
* identity-sensitive operations on these instances (reference equality ({@code ==}), * identity-sensitive operations on these instances (reference equality ({@code ==}),
* identity hash code, and synchronization) are unreliable and should be avoided. * identity hash code, and synchronization) are unreliable and should be avoided.
* <li>They are serialized as specified on the
* <a href="{@docRoot}/serialized-form.html#java.util.CollSer">Serialized Form</a>
* page.
* </ul> * </ul>
* *
* <p>This interface is a member of the * <p>This interface is a member of the

View File

@ -1242,7 +1242,8 @@ public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
*/ */
public KeySetView<K,V> keySet() { public KeySetView<K,V> keySet() {
KeySetView<K,V> ks; KeySetView<K,V> ks;
return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null)); if ((ks = keySet) != null) return ks;
return keySet = new KeySetView<K,V>(this, null);
} }
/** /**
@ -1265,7 +1266,8 @@ public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
*/ */
public Collection<V> values() { public Collection<V> values() {
ValuesView<K,V> vs; ValuesView<K,V> vs;
return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this)); if ((vs = values) != null) return vs;
return values = new ValuesView<K,V>(this);
} }
/** /**
@ -1287,7 +1289,8 @@ public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
*/ */
public Set<Map.Entry<K,V>> entrySet() { public Set<Map.Entry<K,V>> entrySet() {
EntrySetView<K,V> es; EntrySetView<K,V> es;
return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this)); if ((es = entrySet) != null) return es;
return entrySet = new EntrySetView<K,V>(this);
} }
/** /**

View File

@ -376,12 +376,12 @@ public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
/** Lazily initialized key set */ /** Lazily initialized key set */
private transient KeySet<K,V> keySet; private transient KeySet<K,V> keySet;
/** Lazily initialized entry set */
private transient EntrySet<K,V> entrySet;
/** Lazily initialized values collection */ /** Lazily initialized values collection */
private transient Values<K,V> values; private transient Values<K,V> values;
/** Lazily initialized entry set */
private transient EntrySet<K,V> entrySet;
/** Lazily initialized descending key set */ /** Lazily initialized descending key set */
private transient ConcurrentNavigableMap<K,V> descendingMap; private transient SubMap<K,V> descendingMap;
/** /**
* Initializes or resets state. Needed by constructors, clone, * Initializes or resets state. Needed by constructors, clone,
@ -1827,13 +1827,15 @@ public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
* @return a navigable set view of the keys in this map * @return a navigable set view of the keys in this map
*/ */
public NavigableSet<K> keySet() { public NavigableSet<K> keySet() {
KeySet<K,V> ks = keySet; KeySet<K,V> ks;
return (ks != null) ? ks : (keySet = new KeySet<>(this)); if ((ks = keySet) != null) return ks;
return keySet = new KeySet<>(this);
} }
public NavigableSet<K> navigableKeySet() { public NavigableSet<K> navigableKeySet() {
KeySet<K,V> ks = keySet; KeySet<K,V> ks;
return (ks != null) ? ks : (keySet = new KeySet<>(this)); if ((ks = keySet) != null) return ks;
return keySet = new KeySet<>(this);
} }
/** /**
@ -1856,8 +1858,9 @@ public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*/ */
public Collection<V> values() { public Collection<V> values() {
Values<K,V> vs = values; Values<K,V> vs;
return (vs != null) ? vs : (values = new Values<>(this)); if ((vs = values) != null) return vs;
return values = new Values<>(this);
} }
/** /**
@ -1888,14 +1891,16 @@ public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
* sorted in ascending key order * sorted in ascending key order
*/ */
public Set<Map.Entry<K,V>> entrySet() { public Set<Map.Entry<K,V>> entrySet() {
EntrySet<K,V> es = entrySet; EntrySet<K,V> es;
return (es != null) ? es : (entrySet = new EntrySet<K,V>(this)); if ((es = entrySet) != null) return es;
return entrySet = new EntrySet<K,V>(this);
} }
public ConcurrentNavigableMap<K,V> descendingMap() { public ConcurrentNavigableMap<K,V> descendingMap() {
ConcurrentNavigableMap<K,V> dm = descendingMap; ConcurrentNavigableMap<K,V> dm;
return (dm != null) ? dm : (descendingMap = new SubMap<K,V> if ((dm = descendingMap) != null) return dm;
(this, null, false, null, false, true)); return descendingMap =
new SubMap<K,V>(this, null, false, null, false, true);
} }
public NavigableSet<K> descendingKeySet() { public NavigableSet<K> descendingKeySet() {
@ -2564,7 +2569,7 @@ public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
* @serial include * @serial include
*/ */
static final class SubMap<K,V> extends AbstractMap<K,V> static final class SubMap<K,V> extends AbstractMap<K,V>
implements ConcurrentNavigableMap<K,V>, Cloneable, Serializable { implements ConcurrentNavigableMap<K,V>, Serializable {
private static final long serialVersionUID = -7647078645895051609L; private static final long serialVersionUID = -7647078645895051609L;
/** Underlying map */ /** Underlying map */
@ -2582,8 +2587,8 @@ public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
// Lazily initialized view holders // Lazily initialized view holders
private transient KeySet<K,V> keySetView; private transient KeySet<K,V> keySetView;
private transient Set<Map.Entry<K,V>> entrySetView; private transient Values<K,V> valuesView;
private transient Collection<V> valuesView; private transient EntrySet<K,V> entrySetView;
/** /**
* Creates a new submap, initializing all fields. * Creates a new submap, initializing all fields.
@ -3049,23 +3054,27 @@ public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
/* ---------------- Submap Views -------------- */ /* ---------------- Submap Views -------------- */
public NavigableSet<K> keySet() { public NavigableSet<K> keySet() {
KeySet<K,V> ks = keySetView; KeySet<K,V> ks;
return (ks != null) ? ks : (keySetView = new KeySet<>(this)); if ((ks = keySetView) != null) return ks;
return keySetView = new KeySet<>(this);
} }
public NavigableSet<K> navigableKeySet() { public NavigableSet<K> navigableKeySet() {
KeySet<K,V> ks = keySetView; KeySet<K,V> ks;
return (ks != null) ? ks : (keySetView = new KeySet<>(this)); if ((ks = keySetView) != null) return ks;
return keySetView = new KeySet<>(this);
} }
public Collection<V> values() { public Collection<V> values() {
Collection<V> vs = valuesView; Values<K,V> vs;
return (vs != null) ? vs : (valuesView = new Values<>(this)); if ((vs = valuesView) != null) return vs;
return valuesView = new Values<>(this);
} }
public Set<Map.Entry<K,V>> entrySet() { public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es = entrySetView; EntrySet<K,V> es;
return (es != null) ? es : (entrySetView = new EntrySet<K,V>(this)); if ((es = entrySetView) != null) return es;
return entrySetView = new EntrySet<K,V>(this);
} }
public NavigableSet<K> descendingKeySet() { public NavigableSet<K> descendingKeySet() {

View File

@ -596,7 +596,7 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
* not, be invoked for each completer in a computation. * not, be invoked for each completer in a computation.
*/ */
public final void propagateCompletion() { public final void propagateCompletion() {
CountedCompleter<?> a = this, s = a; CountedCompleter<?> a = this, s;
for (int c;;) { for (int c;;) {
if ((c = a.pending) == 0) { if ((c = a.pending) == 0) {
if ((a = (s = a).completer) == null) { if ((a = (s = a).completer) == null) {

View File

@ -56,13 +56,11 @@ package java.util.concurrent;
* void solve(Executor e, * void solve(Executor e,
* Collection<Callable<Result>> solvers) * Collection<Callable<Result>> solvers)
* throws InterruptedException, ExecutionException { * throws InterruptedException, ExecutionException {
* CompletionService<Result> ecs * CompletionService<Result> cs
* = new ExecutorCompletionService<Result>(e); * = new ExecutorCompletionService<>(e);
* for (Callable<Result> s : solvers) * solvers.forEach(cs::submit);
* ecs.submit(s); * for (int i = solvers.size(); i > 0; i--) {
* int n = solvers.size(); * Result r = cs.take().get();
* for (int i = 0; i < n; ++i) {
* Result r = ecs.take().get();
* if (r != null) * if (r != null)
* use(r); * use(r);
* } * }
@ -76,27 +74,24 @@ package java.util.concurrent;
* void solve(Executor e, * void solve(Executor e,
* Collection<Callable<Result>> solvers) * Collection<Callable<Result>> solvers)
* throws InterruptedException { * throws InterruptedException {
* CompletionService<Result> ecs * CompletionService<Result> cs
* = new ExecutorCompletionService<Result>(e); * = new ExecutorCompletionService<>(e);
* int n = solvers.size(); * int n = solvers.size();
* List<Future<Result>> futures = new ArrayList<>(n); * List<Future<Result>> futures = new ArrayList<>(n);
* Result result = null; * Result result = null;
* try { * try {
* for (Callable<Result> s : solvers) * solvers.forEach((solver) -> futures.add(cs.submit(solver)));
* futures.add(ecs.submit(s)); * for (int i = n; i > 0; i--) {
* for (int i = 0; i < n; ++i) {
* try { * try {
* Result r = ecs.take().get(); * Result r = cs.take().get();
* if (r != null) { * if (r != null) {
* result = r; * result = r;
* break; * break;
* } * }
* } catch (ExecutionException ignore) {} * } catch (ExecutionException ignore) {}
* } * }
* } * } finally {
* finally { * futures.forEach((future) -> future.cancel(true));
* for (Future<Result> f : futures)
* f.cancel(true);
* } * }
* *
* if (result != null) * if (result != null)

View File

@ -348,10 +348,6 @@ public class Phaser {
private final AtomicReference<QNode> evenQ; private final AtomicReference<QNode> evenQ;
private final AtomicReference<QNode> oddQ; private final AtomicReference<QNode> oddQ;
private AtomicReference<QNode> queueFor(int phase) {
return ((phase & 1) == 0) ? evenQ : oddQ;
}
/** /**
* Returns message string for bounds exceptions on arrival. * Returns message string for bounds exceptions on arrival.
*/ */

View File

@ -67,9 +67,9 @@ public class BasicImageReader implements AutoCloseable {
static private final boolean MAP_ALL = static private final boolean MAP_ALL =
isSystemProperty("jdk.image.map.all", "true", IS_64_BIT ? "true" : "false"); isSystemProperty("jdk.image.map.all", "true", IS_64_BIT ? "true" : "false");
private final String name;
private final ByteOrder byteOrder;
private final Path imagePath; private final Path imagePath;
private final ByteOrder byteOrder;
private final String name;
private final ByteBuffer memoryMap; private final ByteBuffer memoryMap;
private final FileChannel channel; private final FileChannel channel;
private final ImageHeader header; private final ImageHeader header;
@ -83,11 +83,9 @@ public class BasicImageReader implements AutoCloseable {
protected BasicImageReader(Path path, ByteOrder byteOrder) protected BasicImageReader(Path path, ByteOrder byteOrder)
throws IOException { throws IOException {
Objects.requireNonNull(path); this.imagePath = Objects.requireNonNull(path);
Objects.requireNonNull(byteOrder); this.byteOrder = Objects.requireNonNull(byteOrder);
this.name = path.toString(); this.name = this.imagePath.toString();
this.byteOrder = byteOrder;
imagePath = path;
ByteBuffer map; ByteBuffer map;
@ -211,6 +209,8 @@ public class BasicImageReader implements AutoCloseable {
} }
public static void releaseByteBuffer(ByteBuffer buffer) { public static void releaseByteBuffer(ByteBuffer buffer) {
Objects.requireNonNull(buffer);
if (!MAP_ALL) { if (!MAP_ALL) {
ImageBufferCache.releaseBuffer(buffer); ImageBufferCache.releaseBuffer(buffer);
} }
@ -240,10 +240,14 @@ public class BasicImageReader implements AutoCloseable {
} }
public ImageLocation findLocation(String mn, String rn) { public ImageLocation findLocation(String mn, String rn) {
Objects.requireNonNull(mn);
Objects.requireNonNull(rn);
return findLocation("/" + mn + "/" + rn); return findLocation("/" + mn + "/" + rn);
} }
public synchronized ImageLocation findLocation(String name) { public synchronized ImageLocation findLocation(String name) {
Objects.requireNonNull(name);
// Details of the algorithm used here can be found in // Details of the algorithm used here can be found in
// jdk.tools.jlink.internal.PerfectHashBuilder. // jdk.tools.jlink.internal.PerfectHashBuilder.
byte[] bytes = ImageStringsReader.mutf8FromString(name); byte[] bytes = ImageStringsReader.mutf8FromString(name);
@ -287,16 +291,25 @@ public class BasicImageReader implements AutoCloseable {
} }
public long[] getAttributes(int offset) { public long[] getAttributes(int offset) {
if (offset < 0 || offset >= locations.limit()) {
throw new IndexOutOfBoundsException("offset");
}
ByteBuffer buffer = slice(locations, offset, locations.limit() - offset); ByteBuffer buffer = slice(locations, offset, locations.limit() - offset);
return ImageLocation.decompress(buffer); return ImageLocation.decompress(buffer);
} }
public String getString(int offset) { public String getString(int offset) {
if (offset < 0 || offset >= strings.limit()) {
throw new IndexOutOfBoundsException("offset");
}
ByteBuffer buffer = slice(strings, offset, strings.limit() - offset); ByteBuffer buffer = slice(strings, offset, strings.limit() - offset);
return ImageStringsReader.stringFromByteBuffer(buffer); return ImageStringsReader.stringFromByteBuffer(buffer);
} }
private byte[] getBufferBytes(ByteBuffer buffer) { private byte[] getBufferBytes(ByteBuffer buffer) {
Objects.requireNonNull(buffer);
byte[] bytes = new byte[buffer.limit()]; byte[] bytes = new byte[buffer.limit()];
buffer.get(bytes); buffer.get(bytes);
@ -343,6 +356,7 @@ public class BasicImageReader implements AutoCloseable {
} }
public byte[] getResource(String name) { public byte[] getResource(String name) {
Objects.requireNonNull(name);
ImageLocation location = findLocation(name); ImageLocation location = findLocation(name);
return location != null ? getResource(location) : null; return location != null ? getResource(location) : null;
@ -362,6 +376,7 @@ public class BasicImageReader implements AutoCloseable {
} }
public ByteBuffer getResourceBuffer(ImageLocation loc) { public ByteBuffer getResourceBuffer(ImageLocation loc) {
Objects.requireNonNull(loc);
long offset = loc.getContentOffset() + indexSize; long offset = loc.getContentOffset() + indexSize;
long compressedSize = loc.getCompressedSize(); long compressedSize = loc.getCompressedSize();
long uncompressedSize = loc.getUncompressedSize(); long uncompressedSize = loc.getUncompressedSize();
@ -399,6 +414,7 @@ public class BasicImageReader implements AutoCloseable {
} }
public InputStream getResourceStream(ImageLocation loc) { public InputStream getResourceStream(ImageLocation loc) {
Objects.requireNonNull(loc);
byte[] bytes = getResource(loc); byte[] bytes = getResource(loc);
return new ByteArrayInputStream(bytes); return new ByteArrayInputStream(bytes);

View File

@ -27,6 +27,7 @@ package jdk.internal.jimage;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.IntBuffer; import java.nio.IntBuffer;
import java.util.Objects;
/** /**
* @implNote This class needs to maintain JDK 8 source compatibility. * @implNote This class needs to maintain JDK 8 source compatibility.
@ -75,6 +76,8 @@ public final class ImageHeader {
} }
static ImageHeader readFrom(IntBuffer buffer) { static ImageHeader readFrom(IntBuffer buffer) {
Objects.requireNonNull(buffer);
if (buffer.capacity() != HEADER_SLOTS) { if (buffer.capacity() != HEADER_SLOTS) {
throw new InternalError("jimage header not the correct size"); throw new InternalError("jimage header not the correct size");
} }
@ -94,11 +97,13 @@ public final class ImageHeader {
} }
public void writeTo(ImageStream stream) { public void writeTo(ImageStream stream) {
Objects.requireNonNull(stream);
stream.ensure(getHeaderSize()); stream.ensure(getHeaderSize());
writeTo(stream.getBuffer()); writeTo(stream.getBuffer());
} }
public void writeTo(ByteBuffer buffer) { public void writeTo(ByteBuffer buffer) {
Objects.requireNonNull(buffer);
buffer.putInt(magic); buffer.putInt(magic);
buffer.putInt(majorVersion << 16 | minorVersion); buffer.putInt(majorVersion << 16 | minorVersion);
buffer.putInt(flags); buffer.putInt(flags);

View File

@ -26,6 +26,7 @@
package jdk.internal.jimage; package jdk.internal.jimage;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.Objects;
/** /**
* @implNote This class needs to maintain JDK 8 source compatibility. * @implNote This class needs to maintain JDK 8 source compatibility.
@ -50,8 +51,8 @@ public class ImageLocation {
protected final ImageStrings strings; protected final ImageStrings strings;
public ImageLocation(long[] attributes, ImageStrings strings) { public ImageLocation(long[] attributes, ImageStrings strings) {
this.attributes = attributes; this.attributes = Objects.requireNonNull(attributes);
this.strings = strings; this.strings = Objects.requireNonNull(strings);
} }
ImageStrings getStrings() { ImageStrings getStrings() {
@ -67,6 +68,7 @@ public class ImageLocation {
} }
static long[] decompress(ByteBuffer bytes) { static long[] decompress(ByteBuffer bytes) {
Objects.requireNonNull(bytes);
long[] attributes = new long[ATTRIBUTE_COUNT]; long[] attributes = new long[ATTRIBUTE_COUNT];
if (bytes != null) { if (bytes != null) {
@ -103,6 +105,7 @@ public class ImageLocation {
} }
public static byte[] compress(long[] attributes) { public static byte[] compress(long[] attributes) {
Objects.requireNonNull(attributes);
ImageStream stream = new ImageStream(16); ImageStream stream = new ImageStream(16);
for (int kind = ATTRIBUTE_END + 1; kind < ATTRIBUTE_COUNT; kind++) { for (int kind = ATTRIBUTE_END + 1; kind < ATTRIBUTE_COUNT; kind++) {
@ -124,6 +127,8 @@ public class ImageLocation {
} }
public boolean verify(String name) { public boolean verify(String name) {
Objects.requireNonNull(name);
return name.equals(getFullName()); return name.equals(getFullName());
} }
@ -250,6 +255,7 @@ public class ImageLocation {
} }
static ImageLocation readFrom(BasicImageReader reader, int offset) { static ImageLocation readFrom(BasicImageReader reader, int offset) {
Objects.requireNonNull(reader);
long[] attributes = reader.getAttributes(offset); long[] attributes = reader.getAttributes(offset);
ImageStringsReader strings = reader.getStrings(); ImageStringsReader strings = reader.getStrings();

View File

@ -59,6 +59,9 @@ public final class ImageReader implements AutoCloseable {
} }
public static ImageReader open(Path imagePath, ByteOrder byteOrder) throws IOException { public static ImageReader open(Path imagePath, ByteOrder byteOrder) throws IOException {
Objects.requireNonNull(imagePath);
Objects.requireNonNull(byteOrder);
return SharedImageReader.open(imagePath, byteOrder); return SharedImageReader.open(imagePath, byteOrder);
} }
@ -218,6 +221,9 @@ public final class ImageReader implements AutoCloseable {
} }
public static ImageReader open(Path imagePath, ByteOrder byteOrder) throws IOException { public static ImageReader open(Path imagePath, ByteOrder byteOrder) throws IOException {
Objects.requireNonNull(imagePath);
Objects.requireNonNull(byteOrder);
synchronized (OPEN_FILES) { synchronized (OPEN_FILES) {
SharedImageReader reader = OPEN_FILES.get(imagePath); SharedImageReader reader = OPEN_FILES.get(imagePath);
@ -237,6 +243,8 @@ public final class ImageReader implements AutoCloseable {
} }
public void close(ImageReader image) throws IOException { public void close(ImageReader image) throws IOException {
Objects.requireNonNull(image);
synchronized (OPEN_FILES) { synchronized (OPEN_FILES) {
if (!openers.remove(image)) { if (!openers.remove(image)) {
throw new IOException("image file already closed"); throw new IOException("image file already closed");

View File

@ -31,6 +31,7 @@ import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
/** /**
* Factory to get ImageReader * Factory to get ImageReader
@ -54,6 +55,7 @@ public class ImageReaderFactory {
* Returns an {@code ImageReader} to read from the given image file * Returns an {@code ImageReader} to read from the given image file
*/ */
public static ImageReader get(Path jimage) throws IOException { public static ImageReader get(Path jimage) throws IOException {
Objects.requireNonNull(jimage);
ImageReader reader = readers.get(jimage); ImageReader reader = readers.get(jimage);
if (reader != null) { if (reader != null) {
return reader; return reader;

View File

@ -28,6 +28,7 @@ package jdk.internal.jimage;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import java.util.Arrays; import java.util.Arrays;
import java.util.Objects;
/** /**
* @implNote This class needs to maintain JDK 8 source compatibility. * @implNote This class needs to maintain JDK 8 source compatibility.
@ -57,16 +58,16 @@ public class ImageStream {
public ImageStream(int size, ByteOrder byteOrder) { public ImageStream(int size, ByteOrder byteOrder) {
buffer = ByteBuffer.allocate(size); buffer = ByteBuffer.allocate(size);
buffer.order(byteOrder); buffer.order(Objects.requireNonNull(byteOrder));
} }
public ImageStream(byte[] bytes, ByteOrder byteOrder) { public ImageStream(byte[] bytes, ByteOrder byteOrder) {
buffer = ByteBuffer.wrap(bytes); buffer = ByteBuffer.wrap(Objects.requireNonNull(bytes));
buffer.order(byteOrder); buffer.order(Objects.requireNonNull(byteOrder));
} }
public ImageStream(ByteBuffer buffer) { public ImageStream(ByteBuffer buffer) {
this.buffer = buffer; this.buffer = Objects.requireNonNull(buffer);
} }
public ImageStream align(int alignment) { public ImageStream align(int alignment) {

View File

@ -27,6 +27,7 @@ package jdk.internal.jimage;
import java.io.UTFDataFormatException; import java.io.UTFDataFormatException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.Objects;
/** /**
* @implNote This class needs to maintain JDK 8 source compatibility. * @implNote This class needs to maintain JDK 8 source compatibility.
@ -40,7 +41,7 @@ public class ImageStringsReader implements ImageStrings {
private final BasicImageReader reader; private final BasicImageReader reader;
ImageStringsReader(BasicImageReader reader) { ImageStringsReader(BasicImageReader reader) {
this.reader = reader; this.reader = Objects.requireNonNull(reader);
} }
@Override @Override
@ -54,7 +55,19 @@ public class ImageStringsReader implements ImageStrings {
} }
private static int hashCode(byte[] bytes, int offset, int count, int seed) { private static int hashCode(byte[] bytes, int offset, int count, int seed) {
for (int i = offset, limit = offset + count; i < limit; i++) { Objects.requireNonNull(bytes);
if (offset < 0 || count < 0 || offset > bytes.length - count) {
throw new IndexOutOfBoundsException("offset=" + offset + ", count=" + count);
}
int limit = offset + count;
if (limit < 0 || limit > bytes.length) {
throw new IndexOutOfBoundsException("limit=" + limit);
}
for (int i = offset; i < limit; i++) {
seed = (seed * HASH_MULTIPLIER) ^ (bytes[i] & 0xFF); seed = (seed * HASH_MULTIPLIER) ^ (bytes[i] & 0xFF);
} }

View File

@ -72,8 +72,8 @@ import java.util.concurrent.ConcurrentHashMap;
* loader. This allows automatic modules (for example) to link to types in the * loader. This allows automatic modules (for example) to link to types in the
* unnamed module of the parent class loader. * unnamed module of the parent class loader.
* *
* @see Layer#createWithOneLoader * @see Layer#defineModulesWithOneLoader
* @see Layer#createWithManyLoaders * @see Layer#defineModulesWithManyLoaders
*/ */
public final class Loader extends SecureClassLoader { public final class Loader extends SecureClassLoader {
@ -315,6 +315,8 @@ public final class Loader extends SecureClassLoader {
}, acc); }, acc);
} catch (PrivilegedActionException pae) { } catch (PrivilegedActionException pae) {
throw (IOException) pae.getCause(); throw (IOException) pae.getCause();
} catch (SecurityException se) {
return null;
} }
} }

View File

@ -475,6 +475,23 @@ public class VM {
*/ */
public static native long getNanoTimeAdjustment(long offsetInSeconds); public static native long getNanoTimeAdjustment(long offsetInSeconds);
/**
* Returns the VM arguments for this runtime environment.
*
* @implNote
* The HotSpot JVM processes the input arguments from multiple sources
* in the following order:
* 1. JAVA_TOOL_OPTIONS environment variable
* 2. Options from JNI Invocation API
* 3. _JAVA_OPTIONS environment variable
*
* If VM options file is specified via -XX:VMOptionsFile, the vm options
* file is read and expanded in place of -XX:VMOptionFile option.
*
* Open issue with -XX:Flags (see JDK-8157979)
*/
public static native String[] getRuntimeArguments();
static { static {
initialize(); initialize();
} }

View File

@ -165,6 +165,7 @@ module java.base {
java.sql, java.sql,
java.xml, java.xml,
jdk.charsets, jdk.charsets,
jdk.compiler,
jdk.jartool, jdk.jartool,
jdk.jlink, jdk.jlink,
jdk.net, jdk.net,

View File

@ -29,6 +29,7 @@ import java.security.AlgorithmConstraints;
import java.security.CryptoPrimitive; import java.security.CryptoPrimitive;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Date;
import java.util.Set; import java.util.Set;
import java.util.EnumSet; import java.util.EnumSet;
import java.math.BigInteger; import java.math.BigInteger;
@ -59,7 +60,7 @@ import sun.security.x509.X509CRLImpl;
import sun.security.x509.AlgorithmId; import sun.security.x509.AlgorithmId;
/** /**
* A <code>PKIXCertPathChecker</code> implementation to check whether a * A {@code PKIXCertPathChecker} implementation to check whether a
* specified certificate contains the required algorithm constraints. * specified certificate contains the required algorithm constraints.
* <p> * <p>
* Certificate fields such as the subject public key, the signature * Certificate fields such as the subject public key, the signature
@ -74,6 +75,7 @@ public final class AlgorithmChecker extends PKIXCertPathChecker {
private final AlgorithmConstraints constraints; private final AlgorithmConstraints constraints;
private final PublicKey trustedPubKey; private final PublicKey trustedPubKey;
private final Date pkixdate;
private PublicKey prevPubKey; private PublicKey prevPubKey;
private static final Set<CryptoPrimitive> SIGNATURE_PRIMITIVE_SET = private static final Set<CryptoPrimitive> SIGNATURE_PRIMITIVE_SET =
@ -99,7 +101,7 @@ public final class AlgorithmChecker extends PKIXCertPathChecker {
private boolean trustedMatch = false; private boolean trustedMatch = false;
/** /**
* Create a new <code>AlgorithmChecker</code> with the algorithm * Create a new {@code AlgorithmChecker} with the algorithm
* constraints specified in security property * constraints specified in security property
* "jdk.certpath.disabledAlgorithms". * "jdk.certpath.disabledAlgorithms".
* *
@ -107,11 +109,26 @@ public final class AlgorithmChecker extends PKIXCertPathChecker {
* certificate * certificate
*/ */
public AlgorithmChecker(TrustAnchor anchor) { public AlgorithmChecker(TrustAnchor anchor) {
this(anchor, certPathDefaultConstraints); this(anchor, certPathDefaultConstraints, null);
} }
/** /**
* Create a new <code>AlgorithmChecker</code> with the * Create a new {@code AlgorithmChecker} with the
* given {@code TrustAnchor} and {@code AlgorithmConstraints}.
*
* @param anchor the trust anchor selected to validate the target
* certificate
* @param constraints the algorithm constraints (or null)
*
* @throws IllegalArgumentException if the {@code anchor} is null
*/
public AlgorithmChecker(TrustAnchor anchor,
AlgorithmConstraints constraints) {
this(anchor, constraints, null);
}
/**
* Create a new {@code AlgorithmChecker} with the
* given {@code AlgorithmConstraints}. * given {@code AlgorithmConstraints}.
* <p> * <p>
* Note that this constructor will be used to check a certification * Note that this constructor will be used to check a certification
@ -124,20 +141,24 @@ public final class AlgorithmChecker extends PKIXCertPathChecker {
this.prevPubKey = null; this.prevPubKey = null;
this.trustedPubKey = null; this.trustedPubKey = null;
this.constraints = constraints; this.constraints = constraints;
this.pkixdate = null;
} }
/** /**
* Create a new <code>AlgorithmChecker</code> with the * Create a new {@code AlgorithmChecker} with the
* given <code>TrustAnchor</code> and <code>AlgorithmConstraints</code>. * given {@code TrustAnchor} and {@code AlgorithmConstraints}.
* *
* @param anchor the trust anchor selected to validate the target * @param anchor the trust anchor selected to validate the target
* certificate * certificate
* @param constraints the algorithm constraints (or null) * @param constraints the algorithm constraints (or null)
* @param pkixdate Date the constraints are checked against. The value is
* either the PKIXParameter date or null for the current date.
* *
* @throws IllegalArgumentException if the <code>anchor</code> is null * @throws IllegalArgumentException if the {@code anchor} is null
*/ */
public AlgorithmChecker(TrustAnchor anchor, public AlgorithmChecker(TrustAnchor anchor,
AlgorithmConstraints constraints) { AlgorithmConstraints constraints,
Date pkixdate) {
if (anchor == null) { if (anchor == null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
@ -157,6 +178,22 @@ public final class AlgorithmChecker extends PKIXCertPathChecker {
this.prevPubKey = trustedPubKey; this.prevPubKey = trustedPubKey;
this.constraints = constraints; this.constraints = constraints;
this.pkixdate = pkixdate;
}
/**
* Create a new {@code AlgorithmChecker} with the
* given {@code TrustAnchor} and {@code PKIXParameter} date.
*
* @param anchor the trust anchor selected to validate the target
* certificate
* @param pkixdate Date the constraints are checked against. The value is
* either the PKIXParameter date or null for the current date.
*
* @throws IllegalArgumentException if the {@code anchor} is null
*/
public AlgorithmChecker(TrustAnchor anchor, Date pkixdate) {
this(anchor, certPathDefaultConstraints, pkixdate);
} }
// Check this 'cert' for restrictions in the AnchorCertificates // Check this 'cert' for restrictions in the AnchorCertificates
@ -259,7 +296,7 @@ public final class AlgorithmChecker extends PKIXCertPathChecker {
// permits() will throw exception on failure. // permits() will throw exception on failure.
certPathDefaultConstraints.permits(primitives, certPathDefaultConstraints.permits(primitives,
new CertConstraintParameters((X509Certificate)cert, new CertConstraintParameters((X509Certificate)cert,
trustedMatch)); trustedMatch, pkixdate));
// new CertConstraintParameters(x509Cert, trustedMatch)); // new CertConstraintParameters(x509Cert, trustedMatch));
// If there is no previous key, set one and exit // If there is no previous key, set one and exit
if (prevPubKey == null) { if (prevPubKey == null) {

View File

@ -172,7 +172,7 @@ public final class PKIXCertPathValidator extends CertPathValidatorSpi {
List<PKIXCertPathChecker> certPathCheckers = new ArrayList<>(); List<PKIXCertPathChecker> certPathCheckers = new ArrayList<>();
// add standard checkers that we will be using // add standard checkers that we will be using
certPathCheckers.add(untrustedChecker); certPathCheckers.add(untrustedChecker);
certPathCheckers.add(new AlgorithmChecker(anchor)); certPathCheckers.add(new AlgorithmChecker(anchor, params.date()));
certPathCheckers.add(new KeyChecker(certPathLen, certPathCheckers.add(new KeyChecker(certPathLen,
params.targetCertConstraints())); params.targetCertConstraints()));
certPathCheckers.add(new ConstraintsChecker(certPathLen)); certPathCheckers.add(new ConstraintsChecker(certPathLen));

View File

@ -343,7 +343,8 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi {
checkers.add(policyChecker); checkers.add(policyChecker);
// add the algorithm checker // add the algorithm checker
checkers.add(new AlgorithmChecker(builder.trustAnchor)); checkers.add(new AlgorithmChecker(builder.trustAnchor,
buildParams.date()));
BasicChecker basicChecker = null; BasicChecker basicChecker = null;
if (nextState.keyParamsNeeded()) { if (nextState.keyParamsNeeded()) {

View File

@ -26,6 +26,7 @@
package sun.security.util; package sun.security.util;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.Date;
/** /**
* This class is a wrapper for keeping state and passing objects between PKIX, * This class is a wrapper for keeping state and passing objects between PKIX,
@ -34,18 +35,21 @@ import java.security.cert.X509Certificate;
public class CertConstraintParameters { public class CertConstraintParameters {
// A certificate being passed to check against constraints. // A certificate being passed to check against constraints.
private final X509Certificate cert; private final X509Certificate cert;
// This is true if the trust anchor in the certificate chain matches a cert // This is true if the trust anchor in the certificate chain matches a cert
// in AnchorCertificates // in AnchorCertificates
private final boolean trustedMatch; private final boolean trustedMatch;
// PKIXParameter date
private final Date pkixDate;
public CertConstraintParameters(X509Certificate c, boolean match) { public CertConstraintParameters(X509Certificate c, boolean match,
Date pkixdate) {
cert = c; cert = c;
trustedMatch = match; trustedMatch = match;
pkixDate = pkixdate;
} }
public CertConstraintParameters(X509Certificate c) { public CertConstraintParameters(X509Certificate c) {
this(c, false); this(c, false, null);
} }
// Returns if the trust anchor has a match if anchor checking is enabled. // Returns if the trust anchor has a match if anchor checking is enabled.
@ -56,4 +60,9 @@ public class CertConstraintParameters {
public X509Certificate getCertificate() { public X509Certificate getCertificate() {
return cert; return cert;
} }
public Date getPKIXParamDate() {
return pkixDate;
}
} }

View File

@ -31,11 +31,15 @@ import java.security.Key;
import java.security.cert.CertPathValidatorException; import java.security.cert.CertPathValidatorException;
import java.security.cert.CertPathValidatorException.BasicReason; import java.security.cert.CertPathValidatorException.BasicReason;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@ -226,6 +230,8 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints {
private Map<String, Set<Constraint>> constraintsMap = new HashMap<>(); private Map<String, Set<Constraint>> constraintsMap = new HashMap<>();
private static final Pattern keySizePattern = Pattern.compile( private static final Pattern keySizePattern = Pattern.compile(
"keySize\\s*(<=|<|==|!=|>|>=)\\s*(\\d+)"); "keySize\\s*(<=|<|==|!=|>|>=)\\s*(\\d+)");
private static final Pattern denyAfterPattern = Pattern.compile(
"denyAfter\\s+(\\d{4})-(\\d{2})-(\\d{2})");
public Constraints(String[] constraintArray) { public Constraints(String[] constraintArray) {
for (String constraintEntry : constraintArray) { for (String constraintEntry : constraintArray) {
@ -259,6 +265,8 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints {
Constraint c, lastConstraint = null; Constraint c, lastConstraint = null;
// Allow only one jdkCA entry per constraint entry // Allow only one jdkCA entry per constraint entry
boolean jdkCALimit = false; boolean jdkCALimit = false;
// Allow only one denyAfter entry per constraint entry
boolean denyAfterLimit = false;
for (String entry : policy.split("&")) { for (String entry : policy.split("&")) {
entry = entry.trim(); entry = entry.trim();
@ -284,6 +292,22 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints {
} }
c = new jdkCAConstraint(algorithm); c = new jdkCAConstraint(algorithm);
jdkCALimit = true; jdkCALimit = true;
} else if(matcher.usePattern(denyAfterPattern).matches()) {
if (debug != null) {
debug.println("Constraints set to denyAfter");
}
if (denyAfterLimit) {
throw new IllegalArgumentException("Only one " +
"denyAfter entry allowed in property. " +
"Constraint: " + constraintEntry);
}
int year = Integer.parseInt(matcher.group(1));
int month = Integer.parseInt(matcher.group(2));
int day = Integer.parseInt(matcher.group(3));
c = new DenyAfterConstraint(algorithm, year, month,
day);
denyAfterLimit = true;
} else { } else {
throw new IllegalArgumentException("Error in security" + throw new IllegalArgumentException("Error in security" +
" property. Constraint unknown: " + entry); " property. Constraint unknown: " + entry);
@ -360,7 +384,15 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints {
} }
} }
// Abstract class for algorithm constraint checking /**
* This abstract Constraint class for algorithm-based checking
* may contain one or more constraints. If the '&' on the {@Security}
* property is used, multiple constraints have been grouped together
* requiring all the constraints to fail for the check to be disallowed.
*
* If the class contains multiple constraints, the next constraint
* is stored in {@code nextConstraint} in linked-list fashion.
*/
private abstract static class Constraint { private abstract static class Constraint {
String algorithm; String algorithm;
Constraint nextConstraint = null; Constraint nextConstraint = null;
@ -396,22 +428,79 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints {
} }
/** /**
* Check if an algorithm constraint permit this key to be used. * Check if an algorithm constraint is permitted with a given key.
*
* If the check inside of {@code permit()} fails, it must call
* {@code next()} with the same {@code Key} parameter passed if
* multiple constraints need to be checked.
*
* @param key Public key * @param key Public key
* @return true if constraints do not match * @return 'true' if constraint is allowed, 'false' if disallowed.
*/ */
public boolean permits(Key key) { public boolean permits(Key key) {
return true; return true;
} }
/** /**
* Check if an algorithm constraint is permit this certificate to * Check if an algorithm constraint is permitted with a given
* be used. * CertConstraintParameters.
* @param cp CertificateParameter containing certificate and state info *
* @return true if constraints do not match * If the check inside of {@code permits()} fails, it must call
* {@code next()} with the same {@code CertConstraintParameters}
* parameter passed if multiple constraints need to be checked.
*
* @param cp CertConstraintParameter containing certificate info
* @throws CertPathValidatorException if constraint disallows.
*
*/ */
public abstract void permits(CertConstraintParameters cp) public abstract void permits(CertConstraintParameters cp)
throws CertPathValidatorException; throws CertPathValidatorException;
/**
* Recursively check if the constraints are allowed.
*
* If {@code nextConstraint} is non-null, this method will
* call {@code nextConstraint}'s {@code permits()} to check if the
* constraint is allowed or denied. If the constraint's
* {@code permits()} is allowed, this method will exit this and any
* recursive next() calls, returning 'true'. If the constraints called
* were disallowed, the last constraint will throw
* {@code CertPathValidatorException}.
*
* @param cp CertConstraintParameters
* @return 'true' if constraint allows the operation, 'false' if
* we are at the end of the constraint list or,
* {@code nextConstraint} is null.
*/
boolean next(CertConstraintParameters cp)
throws CertPathValidatorException {
if (nextConstraint != null) {
nextConstraint.permits(cp);
return true;
}
return false;
}
/**
* Recursively check if this constraint is allowed,
*
* If {@code nextConstraint} is non-null, this method will
* call {@code nextConstraint}'s {@code permit()} to check if the
* constraint is allowed or denied. If the constraint's
* {@code permit()} is allowed, this method will exit this and any
* recursive next() calls, returning 'true'. If the constraints
* called were disallowed the check will exit with 'false'.
*
* @param key Public key
* @return 'true' if constraint allows the operation, 'false' if
* the constraint denies the operation.
*/
boolean next(Key key) {
if (nextConstraint != null && nextConstraint.permits(key)) {
return true;
}
return false;
}
} }
/* /*
@ -424,9 +513,9 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints {
} }
/* /*
* Check if each constraint fails and check if there is a linked * Check if CertConstraintParameters has a trusted match, if it does
* constraint Any permitted constraint will exit the linked list * call next() for any following constraints. If it does not, exit
* to allow the operation. * as this constraint(s) does not restrict the operation.
*/ */
public void permits(CertConstraintParameters cp) public void permits(CertConstraintParameters cp)
throws CertPathValidatorException { throws CertPathValidatorException {
@ -434,10 +523,9 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints {
debug.println("jdkCAConstraints.permits(): " + algorithm); debug.println("jdkCAConstraints.permits(): " + algorithm);
} }
// Return false if the chain has a trust anchor in cacerts // Check chain has a trust anchor in cacerts
if (cp.isTrustedMatch()) { if (cp.isTrustedMatch()) {
if (nextConstraint != null) { if (next(cp)) {
nextConstraint.permits(cp);
return; return;
} }
throw new CertPathValidatorException( throw new CertPathValidatorException(
@ -448,6 +536,99 @@ public class DisabledAlgorithmConstraints extends AbstractAlgorithmConstraints {
} }
} }
/*
* This class handles the denyAfter constraint. The date is in the UTC/GMT
* timezone.
*/
private static class DenyAfterConstraint extends Constraint {
private Date denyAfterDate;
private static final SimpleDateFormat dateFormat =
new SimpleDateFormat("EEE, MMM d HH:mm:ss z YYYY");
DenyAfterConstraint(String algo, int year, int month, int day) {
Calendar c;
algorithm = algo;
if (debug != null) {
debug.println("DenyAfterConstraint read in as: year " +
year + ", month = " + month + ", day = " + day);
}
c = new Calendar.Builder().setTimeZone(TimeZone.getTimeZone("GMT"))
.setDate(year, month - 1, day).build();
if (year > c.getActualMaximum(Calendar.YEAR) ||
year < c.getActualMinimum(Calendar.YEAR)) {
throw new IllegalArgumentException(
"Invalid year given in constraint: " + year);
}
if ((month - 1) > c.getActualMaximum(Calendar.MONTH) ||
(month - 1) < c.getActualMinimum(Calendar.MONTH)) {
throw new IllegalArgumentException(
"Invalid month given in constraint: " + month);
}
if (day > c.getActualMaximum(Calendar.DAY_OF_MONTH) ||
day < c.getActualMinimum(Calendar.DAY_OF_MONTH)) {
throw new IllegalArgumentException(
"Invalid Day of Month given in constraint: " + day);
}
denyAfterDate = c.getTime();
if (debug != null) {
debug.println("DenyAfterConstraint date set to: " +
dateFormat.format(denyAfterDate));
}
}
/*
* Checking that the provided date is not beyond the constraint date.
* The provided date can be the PKIXParameter date if given,
* otherwise it is the current date.
*
* If the constraint disallows, call next() for any following
* constraints. Throw an exception if this is the last constraint.
*/
@Override
public void permits(CertConstraintParameters cp)
throws CertPathValidatorException {
Date currentDate;
if (cp.getPKIXParamDate() != null) {
currentDate = cp.getPKIXParamDate();
} else {
currentDate = new Date();
}
if (!denyAfterDate.after(currentDate)) {
if (next(cp)) {
return;
}
throw new CertPathValidatorException(
"denyAfter constraint check failed. " +
"Constraint date: " +
dateFormat.format(denyAfterDate) +
"; Cert date: " +
dateFormat.format(currentDate),
null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
}
}
/*
* Return result if the constraint's date is beyond the current date
* in UTC timezone.
*/
public boolean permits(Key key) {
if (next(key)) {
return true;
}
if (debug != null) {
debug.println("DenyAfterConstraints.permits(): " + algorithm);
}
return denyAfterDate.after(new Date());
}
}
/* /*
* This class contains constraints dealing with the key size * This class contains constraints dealing with the key size

View File

@ -570,9 +570,7 @@ krb5.kdc.bad.policy = tryLast
# describes the mechanism for disabling algorithms based on algorithm name # describes the mechanism for disabling algorithms based on algorithm name
# and/or key length. This includes algorithms used in certificates, as well # and/or key length. This includes algorithms used in certificates, as well
# as revocation information such as CRLs and signed OCSP Responses. # as revocation information such as CRLs and signed OCSP Responses.
# # The syntax of the disabled algorithm string is described as follows:
# The syntax of the disabled algorithm string is described as this Java
# BNF-style:
# DisabledAlgorithms: # DisabledAlgorithms:
# " DisabledAlgorithm { , DisabledAlgorithm } " # " DisabledAlgorithm { , DisabledAlgorithm } "
# #
@ -583,26 +581,23 @@ krb5.kdc.bad.policy = tryLast
# (see below) # (see below)
# #
# Constraint: # Constraint:
# KeySizeConstraint, CertConstraint # KeySizeConstraint | CAConstraint | DenyAfterConstraint
# #
# KeySizeConstraint: # KeySizeConstraint:
# keySize Operator DecimalInteger # keySize Operator KeyLength
# #
# Operator: # Operator:
# <= | < | == | != | >= | > # <= | < | == | != | >= | >
# #
# DecimalInteger: # KeyLength:
# DecimalDigits # Integer value of the algorithm's key length in bits
# #
# DecimalDigits: # CAConstraint:
# DecimalDigit {DecimalDigit}
#
# DecimalDigit: one of
# 1 2 3 4 5 6 7 8 9 0
#
# CertConstraint
# jdkCA # jdkCA
# #
# DenyAfterConstraint:
# denyAfter YYYY-MM-DD
#
# The "AlgorithmName" is the standard algorithm name of the disabled # The "AlgorithmName" is the standard algorithm name of the disabled
# algorithm. See "Java Cryptography Architecture Standard Algorithm Name # algorithm. See "Java Cryptography Architecture Standard Algorithm Name
# Documentation" for information about Standard Algorithm Names. Matching # Documentation" for information about Standard Algorithm Names. Matching
@ -615,27 +610,42 @@ krb5.kdc.bad.policy = tryLast
# that rely on DSA, such as NONEwithDSA, SHA1withDSA. However, the assertion # that rely on DSA, such as NONEwithDSA, SHA1withDSA. However, the assertion
# will not disable algorithms related to "ECDSA". # will not disable algorithms related to "ECDSA".
# #
# A "Constraint" provides further guidance for the algorithm being specified. # A "Constraint" defines restrictions on the keys and/or certificates for
# The "KeySizeConstraint" requires a key of a valid size range if the # a specified AlgorithmName:
# "AlgorithmName" is of a key algorithm. The "DecimalInteger" indicates the
# key size specified in number of bits. For example, "RSA keySize <= 1024"
# indicates that any RSA key with key size less than or equal to 1024 bits
# should be disabled, and "RSA keySize < 1024, RSA keySize > 2048" indicates
# that any RSA key with key size less than 1024 or greater than 2048 should
# be disabled. Note that the "KeySizeConstraint" only makes sense to key
# algorithms.
# #
# "CertConstraint" specifies additional constraints for # KeySizeConstraint:
# certificates that contain algorithms that are restricted: # keySize Operator KeyLength
# The constraint requires a key of a valid size range if the
# "AlgorithmName" is of a key algorithm. The "KeyLength" indicates
# the key size specified in number of bits. For example,
# "RSA keySize <= 1024" indicates that any RSA key with key size less
# than or equal to 1024 bits should be disabled, and
# "RSA keySize < 1024, RSA keySize > 2048" indicates that any RSA key
# with key size less than 1024 or greater than 2048 should be disabled.
# This constraint is only used on algorithms that have a key size.
# #
# "jdkCA" prohibits the specified algorithm only if the algorithm is used # CAConstraint:
# in a certificate chain that terminates at a marked trust anchor in the # jdkCA
# lib/security/cacerts keystore.  All other chains are not affected. # This constraint prohibits the specified algorithm only if the
# If the jdkCA constraint is not set, then all chains using the # algorithm is used in a certificate chain that terminates at a marked
# specified algorithm are restricted. jdkCA may only be used once in # trust anchor in the lib/security/cacerts keystore. If the jdkCA
# a DisabledAlgorithm expression. # constraint is not set, then all chains using the specified algorithm
# Example:  To apply this constraint to SHA-1 certificates, include # are restricted. jdkCA may only be used once in a DisabledAlgorithm
# the following:  "SHA1 jdkCA" # expression.
# Example:  To apply this constraint to SHA-1 certificates, include
# the following:  "SHA1 jdkCA"
#
# DenyAfterConstraint:
# denyAfter YYYY-MM-DD
# This constraint prohibits a certificate with the specified algorithm
# from being used after the date regardless of the certificate's
# validity.  JAR files that are signed and timestamped before the
# constraint date with certificates containing the disabled algorithm
# will not be restricted.  The date is processed in the UTC timezone.
# This constraint can only be used once in a DisabledAlgorithm
# expression.
# Example: To deny usage of RSA 2048 bit certificates after Feb 3 2020,
# use the following: "RSA keySize == 2048 & denyAfter 2020-02-03"
# #
# When an algorithm must satisfy more than one constraint, it must be # When an algorithm must satisfy more than one constraint, it must be
# delimited by an ampersand '&'. For example, to restrict certificates in a # delimited by an ampersand '&'. For example, to restrict certificates in a

View File

@ -55,3 +55,8 @@ Java_jdk_internal_misc_VM_initialize(JNIEnv *env, jclass cls) {
(*env)->RegisterNatives(env, cls, (*env)->RegisterNatives(env, cls,
methods, sizeof(methods)/sizeof(methods[0])); methods, sizeof(methods)/sizeof(methods[0]));
} }
JNIEXPORT jobjectArray JNICALL
Java_jdk_internal_misc_VM_getRuntimeArguments(JNIEnv *env, jclass cls) {
return JVM_GetVmArguments(env);
}

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -61,7 +61,7 @@ Java_java_net_InetAddress_init(JNIEnv *env, jclass cls) {
CHECK_NULL(iac_class); CHECK_NULL(iac_class);
ia_holderID = (*env)->GetFieldID(env, ia_class, "holder", "Ljava/net/InetAddress$InetAddressHolder;"); ia_holderID = (*env)->GetFieldID(env, ia_class, "holder", "Ljava/net/InetAddress$InetAddressHolder;");
CHECK_NULL(ia_holderID); CHECK_NULL(ia_holderID);
ia_preferIPv6AddressID = (*env)->GetStaticFieldID(env, ia_class, "preferIPv6Address", "Z"); ia_preferIPv6AddressID = (*env)->GetStaticFieldID(env, ia_class, "preferIPv6Address", "I");
CHECK_NULL(ia_preferIPv6AddressID); CHECK_NULL(ia_preferIPv6AddressID);
iac_addressID = (*env)->GetFieldID(env, iac_class, "address", "I"); iac_addressID = (*env)->GetFieldID(env, iac_class, "address", "I");

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1994, 2015, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1994, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -1744,9 +1744,14 @@ static int instruction_length(unsigned char *iptr, unsigned char *end)
} }
default: { default: {
if (instruction < 0 || instruction > JVM_OPC_MAX)
return -1;
/* A length of 0 indicates an error. */ /* A length of 0 indicates an error. */
int length = opcode_length[instruction]; if (opcode_length[instruction] <= 0)
return (length <= 0) ? -1 : length; return -1;
return opcode_length[instruction];
} }
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -76,6 +76,13 @@ static void freeCEN(jzfile *);
static jint INITIAL_META_COUNT = 2; /* initial number of entries in meta name array */ static jint INITIAL_META_COUNT = 2; /* initial number of entries in meta name array */
/*
* Declare library specific JNI_Onload entry if static build
*/
#ifdef STATIC_BUILD
DEF_STATIC_JNI_OnLoad
#endif
/* /*
* The ZFILE_* functions exist to provide some platform-independence with * The ZFILE_* functions exist to provide some platform-independence with
* respect to file access needs. * respect to file access needs.

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -48,6 +48,7 @@
#include "java_net_Inet4AddressImpl.h" #include "java_net_Inet4AddressImpl.h"
#include "java_net_Inet6AddressImpl.h" #include "java_net_Inet6AddressImpl.h"
#include "java_net_InetAddress.h"
/* the initial size of our hostent buffers */ /* the initial size of our hostent buffers */
#ifndef NI_MAXHOST #ifndef NI_MAXHOST
@ -157,7 +158,10 @@ lookupIfLocalhost(JNIEnv *env, const char *hostname, jboolean includeV6)
} }
name = (*env)->NewStringUTF(env, hostname); name = (*env)->NewStringUTF(env, hostname);
CHECK_NULL_RETURN(name, NULL); if (name == NULL) {
freeifaddrs(ifa);
return NULL;
}
/* Iterate over the interfaces, and total up the number of IPv4 and IPv6 /* Iterate over the interfaces, and total up the number of IPv4 and IPv6
* addresses we have. Also keep a count of loopback addresses. We need to * addresses we have. Also keep a count of loopback addresses. We need to
@ -312,8 +316,8 @@ Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
JNU_ReleaseStringPlatformChars(env, host, hostname); JNU_ReleaseStringPlatformChars(env, host, hostname);
return NULL; return NULL;
} else { } else {
int i = 0; int i = 0, addressPreference = -1;
int inetCount = 0, inet6Count = 0, inetIndex, inet6Index; int inetCount = 0, inet6Count = 0, inetIndex = 0, inet6Index = 0, originalIndex = 0;
struct addrinfo *itr, *last = NULL, *iterator = res; struct addrinfo *itr, *last = NULL, *iterator = res;
while (iterator != NULL) { while (iterator != NULL) {
int skip = 0; int skip = 0;
@ -394,14 +398,18 @@ Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
goto cleanupAndReturn; goto cleanupAndReturn;
} }
if ((*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID)) { addressPreference = (*env)->GetStaticIntField(env, ia_class, ia_preferIPv6AddressID);
if (addressPreference == java_net_InetAddress_PREFER_IPV6_VALUE) {
/* AF_INET addresses will be offset by inet6Count */ /* AF_INET addresses will be offset by inet6Count */
inetIndex = inet6Count; inetIndex = inet6Count;
inet6Index = 0; inet6Index = 0;
} else { } else if (addressPreference == java_net_InetAddress_PREFER_IPV4_VALUE) {
/* AF_INET6 addresses will be offset by inetCount */ /* AF_INET6 addresses will be offset by inetCount */
inetIndex = 0; inetIndex = 0;
inet6Index = inetCount; inet6Index = inetCount;
} else if (addressPreference == java_net_InetAddress_PREFER_SYSTEM_VALUE) {
inetIndex = inet6Index = originalIndex = 0;
} }
while (iterator != NULL) { while (iterator != NULL) {
@ -414,7 +422,7 @@ Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
} }
setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in*)iterator->ai_addr)->sin_addr.s_addr)); setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in*)iterator->ai_addr)->sin_addr.s_addr));
setInetAddress_hostName(env, iaObj, host); setInetAddress_hostName(env, iaObj, host);
(*env)->SetObjectArrayElement(env, ret, inetIndex, iaObj); (*env)->SetObjectArrayElement(env, ret, (inetIndex | originalIndex), iaObj);
inetIndex++; inetIndex++;
} else if (iterator->ai_family == AF_INET6) { } else if (iterator->ai_family == AF_INET6) {
jint scope = 0; jint scope = 0;
@ -435,9 +443,13 @@ Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
setInet6Address_scopeid(env, iaObj, scope); setInet6Address_scopeid(env, iaObj, scope);
} }
setInetAddress_hostName(env, iaObj, host); setInetAddress_hostName(env, iaObj, host);
(*env)->SetObjectArrayElement(env, ret, inet6Index, iaObj); (*env)->SetObjectArrayElement(env, ret, (inet6Index | originalIndex), iaObj);
inet6Index++; inet6Index++;
} }
if (addressPreference == java_net_InetAddress_PREFER_SYSTEM_VALUE) {
originalIndex++;
inetIndex = inet6Index = 0;
}
iterator = iterator->ai_next; iterator = iterator->ai_next;
} }
} }

View File

@ -243,6 +243,7 @@ JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByName0
if (name_utf == NULL) { if (name_utf == NULL) {
if (!(*env)->ExceptionCheck(env)) if (!(*env)->ExceptionCheck(env))
JNU_ThrowOutOfMemoryError(env, NULL); JNU_ThrowOutOfMemoryError(env, NULL);
freeif(ifs);
return NULL; return NULL;
} }
@ -519,7 +520,7 @@ JNIEXPORT jbyteArray JNICALL Java_java_net_NetworkInterface_getMacAddr0
} }
if ((sock = openSocketWithFallback(env, name_utf)) < 0) { if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
(*env)->ReleaseStringUTFChars(env, name, name_utf); (*env)->ReleaseStringUTFChars(env, name, name_utf);
return JNI_FALSE; return NULL;
} }
if (!IS_NULL(addrArray)) { if (!IS_NULL(addrArray)) {
@ -664,7 +665,7 @@ jobject createNetworkInterface(JNIEnv *env, netif *ifs) {
} }
// Create the array of InetAddresses // Create the array of InetAddresses
addrArr = (*env)->NewObjectArray(env, addr_count, ia_class, NULL); addrArr = (*env)->NewObjectArray(env, addr_count, ia_class, NULL);
if (addrArr == NULL) { if (addrArr == NULL) {
return NULL; return NULL;
} }
@ -1829,7 +1830,7 @@ static int getFlags(int sock, const char *ifname, int *flags) {
strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1); strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
if (ioctl(sock, SIOCGLIFFLAGS, (char *)&if2) < 0) { if (ioctl(sock, SIOCGLIFFLAGS, (char *)&if2) < 0) {
return -1; return -1;
} }
*flags = if2.lifr_flags; *flags = if2.lifr_flags;
@ -1859,8 +1860,7 @@ static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
"IPV6 Socket creation failed"); "IPV6 Socket creation failed");
return -1; return -1;
} }
} } else { // errno is not NOSUPPORT
else{ // errno is not NOSUPPORT
NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
"IPV4 Socket creation failed"); "IPV4 Socket creation failed");
return -1; return -1;

View File

@ -95,8 +95,8 @@ void setDefaultScopeID(JNIEnv *env, struct sockaddr *him)
CHECK_NULL(c); CHECK_NULL(c);
c = (*env)->NewGlobalRef(env, c); c = (*env)->NewGlobalRef(env, c);
CHECK_NULL(c); CHECK_NULL(c);
ni_defaultIndexID = (*env)->GetStaticFieldID( ni_defaultIndexID = (*env)->GetStaticFieldID(env, c, "defaultIndex", "I");
env, c, "defaultIndex", "I"); CHECK_NULL(ni_defaultIndexID);
ni_class = c; ni_class = c;
} }
int defaultIndex; int defaultIndex;
@ -118,8 +118,8 @@ int getDefaultScopeID(JNIEnv *env) {
CHECK_NULL_RETURN(c, 0); CHECK_NULL_RETURN(c, 0);
c = (*env)->NewGlobalRef(env, c); c = (*env)->NewGlobalRef(env, c);
CHECK_NULL_RETURN(c, 0); CHECK_NULL_RETURN(c, 0);
ni_defaultIndexID = (*env)->GetStaticFieldID(env, c, ni_defaultIndexID = (*env)->GetStaticFieldID(env, c, "defaultIndex", "I");
"defaultIndex", "I"); CHECK_NULL_RETURN(ni_defaultIndexID, 0);
ni_class = c; ni_class = c;
} }
defaultIndex = (*env)->GetStaticIntField(env, ni_class, defaultIndex = (*env)->GetStaticIntField(env, ni_class,

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -97,7 +97,7 @@ Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
/* get the address preference */ /* get the address preference */
preferIPv6Address preferIPv6Address
= (*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID); = (*env)->GetStaticIntField(env, ia_class, ia_preferIPv6AddressID);
/* Try once, with our static buffer. */ /* Try once, with our static buffer. */
memset(&hints, 0, sizeof(hints)); memset(&hints, 0, sizeof(hints));
@ -122,7 +122,7 @@ Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
} }
} else { } else {
int i = 0; int i = 0;
int inetCount = 0, inet6Count = 0, inetIndex, inet6Index; int inetCount = 0, inet6Count = 0, inetIndex = 0, inet6Index = 0, originalIndex = 0;
struct addrinfo *itr, *last, *iterator = res; struct addrinfo *itr, *last, *iterator = res;
while (iterator != NULL) { while (iterator != NULL) {
int skip = 0; int skip = 0;
@ -203,12 +203,14 @@ Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
goto cleanupAndReturn; goto cleanupAndReturn;
} }
if (preferIPv6Address) { if (preferIPv6Address == java_net_InetAddress_PREFER_IPV6_VALUE) {
inetIndex = inet6Count; inetIndex = inet6Count;
inet6Index = 0; inet6Index = 0;
} else { } else if (preferIPv6Address == java_net_InetAddress_PREFER_IPV4_VALUE) {
inetIndex = 0; inetIndex = 0;
inet6Index = inetCount; inet6Index = inetCount;
} else if (preferIPv6Address == java_net_InetAddress_PREFER_SYSTEM_VALUE) {
inetIndex = inet6Index = originalIndex = 0;
} }
while (iterator != NULL) { while (iterator != NULL) {
@ -220,7 +222,7 @@ Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
} }
setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in*)iterator->ai_addr)->sin_addr.s_addr)); setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in*)iterator->ai_addr)->sin_addr.s_addr));
setInetAddress_hostName(env, iaObj, host); setInetAddress_hostName(env, iaObj, host);
(*env)->SetObjectArrayElement(env, ret, inetIndex, iaObj); (*env)->SetObjectArrayElement(env, ret, (inetIndex | originalIndex), iaObj);
inetIndex ++; inetIndex ++;
} else if (iterator->ai_family == AF_INET6) { } else if (iterator->ai_family == AF_INET6) {
jint scope = 0; jint scope = 0;
@ -240,9 +242,13 @@ Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
setInet6Address_scopeid(env, iaObj, scope); setInet6Address_scopeid(env, iaObj, scope);
} }
setInetAddress_hostName(env, iaObj, host); setInetAddress_hostName(env, iaObj, host);
(*env)->SetObjectArrayElement(env, ret, inet6Index, iaObj); (*env)->SetObjectArrayElement(env, ret, (inet6Index | originalIndex), iaObj);
inet6Index ++; inet6Index ++;
} }
if (preferIPv6Address == java_net_InetAddress_PREFER_SYSTEM_VALUE) {
originalIndex++;
inetIndex = inet6Index = 0;
}
iterator = iterator->ai_next; iterator = iterator->ai_next;
} }
} }

View File

@ -40,7 +40,7 @@ import jdk.tools.jlink.internal.ModuleEntryImpl;
* <li>For jimage content: /{module name}/{package1}/.../{packageN}/{file * <li>For jimage content: /{module name}/{package1}/.../{packageN}/{file
* name}</li> * name}</li>
* <li>For other files (shared lib, launchers, config, ...):/{module name}/ * <li>For other files (shared lib, launchers, config, ...):/{module name}/
* {@literal bin|conf|native}/{dir1}>/.../{dirN}/{file name}</li> * {@literal bin|conf|native}/{dir1}/.../{dirN}/{file name}</li>
* </ul> * </ul>
*/ */
public interface ModuleEntry { public interface ModuleEntry {

View File

@ -296,45 +296,6 @@ public final class Unsafe {
theInternalUnsafe.putDouble(o, offset, x); theInternalUnsafe.putDouble(o, offset, x);
} }
// These read VM internal data.
/**
* Fetches an uncompressed reference value from a given native variable
* ignoring the VM's compressed references mode.
*
* @param address a memory address locating the variable
* @return the value fetched from the indicated native variable
*/
@ForceInline
public Object getUncompressedObject(long address) {
return theInternalUnsafe.getUncompressedObject(address);
}
/**
* Fetches the {@link java.lang.Class} Java mirror for the given native
* metaspace {@code Klass} pointer.
*
* @param metaspaceKlass a native metaspace {@code Klass} pointer
* @return the {@link java.lang.Class} Java mirror
*/
@ForceInline
public Class<?> getJavaMirror(long metaspaceKlass) {
return theInternalUnsafe.getJavaMirror(metaspaceKlass);
}
/**
* Fetches a native metaspace {@code Klass} pointer for the given Java
* object.
*
* @param o Java heap object for which to fetch the class pointer
* @return a native metaspace {@code Klass} pointer
*/
@ForceInline
public long getKlassPointer(Object o) {
return theInternalUnsafe.getKlassPointer(o);
}
// These work on values in the C heap. // These work on values in the C heap.
/** /**

View File

@ -376,12 +376,17 @@ final class ZipPath implements Path {
// count names // count names
count = 0; count = 0;
index = 0; index = 0;
while (index < path.length) { if (path.length == 0) {
byte c = path[index++]; // empty path has one name
if (c != '/') { count = 1;
count++; } else {
while (index < path.length && path[index] != '/') while (index < path.length) {
index++; byte c = path[index++];
if (c != '/') {
count++;
while (index < path.length && path[index] != '/')
index++;
}
} }
} }
// populate offsets // populate offsets
@ -423,10 +428,11 @@ final class ZipPath implements Path {
// removes redundant slashs, replace "\" to zip separator "/" // removes redundant slashs, replace "\" to zip separator "/"
// and check for invalid characters // and check for invalid characters
private byte[] normalize(byte[] path) { private byte[] normalize(byte[] path) {
if (path.length == 0) int len = path.length;
if (len == 0)
return path; return path;
byte prevC = 0; byte prevC = 0;
for (int i = 0; i < path.length; i++) { for (int i = 0; i < len; i++) {
byte c = path[i]; byte c = path[i];
if (c == '\\' || c == '\u0000') if (c == '\\' || c == '\u0000')
return normalize(path, i); return normalize(path, i);
@ -434,6 +440,8 @@ final class ZipPath implements Path {
return normalize(path, i - 1); return normalize(path, i - 1);
prevC = c; prevC = c;
} }
if (len > 1 && prevC == '/')
return Arrays.copyOf(path, len - 1);
return path; return path;
} }
@ -567,7 +575,8 @@ final class ZipPath implements Path {
if (watcher == null || events == null || modifiers == null) { if (watcher == null || events == null || modifiers == null) {
throw new NullPointerException(); throw new NullPointerException();
} }
throw new UnsupportedOperationException(); // watcher must be associated with a different provider
throw new ProviderMismatchException();
} }
@Override @Override

View File

@ -195,8 +195,6 @@ java/rmi/transport/rapidExportUnexport/RapidExportUnexport.java 7146541 linux-al
java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java 7191877 generic-all java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java 7191877 generic-all
sun/rmi/transport/proxy/EagerHttpFallback.java 7195095 generic-all
java/rmi/activation/Activatable/extLoadedImpl/ext.sh 8062724 generic-all java/rmi/activation/Activatable/extLoadedImpl/ext.sh 8062724 generic-all
sun/rmi/rmic/newrmic/equivalence/run.sh 8145980 generic-all sun/rmi/rmic/newrmic/equivalence/run.sh 8145980 generic-all
@ -288,8 +286,6 @@ sun/security/krb5/auto/HttpNegotiateServer.java 8038079 generic-
sun/security/tools/keytool/autotest.sh 8130302 generic-all sun/security/tools/keytool/autotest.sh 8130302 generic-all
sun/security/provider/NSASuiteB/TestDSAGenParameterSpec.java 8137255 generic-all
sun/security/x509/URICertStore/ExtensionsWithLDAP.java 8134577 generic-all sun/security/x509/URICertStore/ExtensionsWithLDAP.java 8134577 generic-all
sun/security/provider/SecureRandom/StrongSecureRandom.java 8157387 linux-all sun/security/provider/SecureRandom/StrongSecureRandom.java 8157387 linux-all
@ -394,7 +390,5 @@ com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java 8141370 linux-i5
# core_tools # core_tools
tools/jimage/JImageTest.java 8150975 linux-i586,windows-i586
############################################################################ ############################################################################

View File

@ -527,9 +527,13 @@ needs_jre = \
java/net/URLConnection/HandleContentTypeWithAttrs.java \ java/net/URLConnection/HandleContentTypeWithAttrs.java \
java/security/Security/ClassLoaderDeadlock/ClassLoaderDeadlock.sh \ java/security/Security/ClassLoaderDeadlock/ClassLoaderDeadlock.sh \
java/security/Security/ClassLoaderDeadlock/Deadlock.sh \ java/security/Security/ClassLoaderDeadlock/Deadlock.sh \
java/text/AttributedCharacterIterator/Attribute/ReadResolve.java \
java/text/AttributedString/TestAttributedStringCtor.java \
java/text/AttributedString/getRunStartLimitTest.java \
java/util/jar/Manifest/CreateManifest.java \ java/util/jar/Manifest/CreateManifest.java \
java/util/logging/TestMainAppContext.java \ java/util/logging/TestMainAppContext.java \
java/util/logging/TestLoggingWithMainAppContext.java \ java/util/logging/TestLoggingWithMainAppContext.java \
java/util/TimeZone/DefaultTimeZoneTest.java \
java/text/Bidi/BidiConformance.java \ java/text/Bidi/BidiConformance.java \
java/text/Bidi/BidiEmbeddingTest.java \ java/text/Bidi/BidiEmbeddingTest.java \
java/text/Bidi/Bug7042148.java \ java/text/Bidi/Bug7042148.java \
@ -724,6 +728,7 @@ needs_compact2 = \
java/util/Collections/UnmodifiableMapEntrySet.java \ java/util/Collections/UnmodifiableMapEntrySet.java \
java/util/Comparator/BasicTest.java \ java/util/Comparator/BasicTest.java \
java/util/Comparator/TypeTest.java \ java/util/Comparator/TypeTest.java \
java/util/Date/TimestampTest.java \
java/util/Iterator/IteratorDefaults.java \ java/util/Iterator/IteratorDefaults.java \
java/util/Iterator/PrimitiveIteratorDefaults.java \ java/util/Iterator/PrimitiveIteratorDefaults.java \
java/util/List/ListDefaults.java \ java/util/List/ListDefaults.java \

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -25,6 +25,7 @@
* @test * @test
* @bug 8039358 * @bug 8039358
* @summary com.sun.jarsigner.ContentSignerParameters.getTSAPolicyID() should be default * @summary com.sun.jarsigner.ContentSignerParameters.getTSAPolicyID() should be default
* @modules jdk.jartool
* @compile DefaultMethod.java * @compile DefaultMethod.java
*/ */

View File

@ -0,0 +1 @@
modules = jdk.httpserver

View File

@ -0,0 +1,151 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4108453 4778440 6304780 6396378
* @summary Basic tests for java.awt.ComponentOrientation
* @build TestBundle TestBundle_es TestBundle_iw
* @build TestBundle1 TestBundle1_ar
*
* @run main BasicTest
*/
/*
* (C) Copyright IBM Corp. 1998 - All Rights Reserved
*
* The original version of this source code and documentation is copyrighted
* and owned by IBM, Inc. These materials are provided under terms of a
* License Agreement between IBM and Sun. This technology is protected by
* multiple US and International patents. This notice and attribution to IBM
* may not be removed.
*/
import java.awt.ComponentOrientation;
import java.util.Locale;
import java.util.ResourceBundle;
public class BasicTest {
public static void main(String args[]) {
System.out.println("BasicTest {");
TestInvariants();
TestLocale();
TestBundle();
System.out.println("} Pass");
}
// TestInvariants
//
// Various no-brainer tests to make sure the constants behave properly
// and so on.
//
static void TestInvariants() {
System.out.println(" TestInvariants {");
Assert(ComponentOrientation.LEFT_TO_RIGHT.isLeftToRight(),
"LEFT_TO_RIGHT.isLeftToRight()");
Assert(ComponentOrientation.UNKNOWN.isLeftToRight(),
"UNKNOWN.isLeftToRight()");
Assert(!ComponentOrientation.RIGHT_TO_LEFT.isLeftToRight(),
"!RIGHT_TO_LEFT.isLeftToRight()");
Assert(ComponentOrientation.LEFT_TO_RIGHT.isHorizontal(),
"LEFT_TO_RIGHT.isHorizontal()");
Assert(ComponentOrientation.UNKNOWN.isHorizontal(),
"UNKNOWN.isHorizontal()");
Assert(ComponentOrientation.RIGHT_TO_LEFT.isHorizontal(),
"RIGHT_TO_LEFT.isHorizontal()");
System.out.println(" } Pass");
}
// TestLocale
//
// Make sure that getOrientation(Locale) works, and that the appropriate
// system locales are RIGHT_TO_LEFT
//
static void TestLocale() {
System.out.println(" TestLocale {");
ComponentOrientation orient = ComponentOrientation.getOrientation(Locale.US);
Assert(orient == ComponentOrientation.LEFT_TO_RIGHT, "US == LEFT_TO_RIGHT");
orient = ComponentOrientation.getOrientation(new Locale("iw", ""));
Assert(orient == ComponentOrientation.RIGHT_TO_LEFT, "iw == RIGHT_TO_LEFT");
orient = ComponentOrientation.getOrientation(new Locale("ar", ""));
Assert(orient == ComponentOrientation.RIGHT_TO_LEFT, "ar == RIGHT_TO_LEFT");
System.out.println(" } Pass");
}
// TestBundle
//
// Make sure that getOrientation(ResourceBundle) works right, especially
// the fallback mechasm
//
static void TestBundle() {
System.out.println(" TestBundle {");
// This will fall back to the default locale's bundle or root bundle
ResourceBundle rb = ResourceBundle.getBundle("TestBundle",
new Locale("et", ""));
if (rb.getLocale().getLanguage().equals(new Locale("iw").getLanguage())) {
assertEquals(rb, ComponentOrientation.RIGHT_TO_LEFT, "et == RIGHT_TO_LEFT" );
} else if (rb.getLocale().getLanguage() == "es") {
assertEquals(rb, ComponentOrientation.LEFT_TO_RIGHT, "et == LEFT_TO_RIGHT" );
} else {
assertEquals(rb, ComponentOrientation.UNKNOWN, "et == UNKNOWN" );
}
// We have actual bundles for "es" and "iw", so it should just fetch
// the orientation object out of them
rb = ResourceBundle.getBundle("TestBundle",new Locale("es", ""));
assertEquals(rb, ComponentOrientation.LEFT_TO_RIGHT, "es == LEFT_TO_RIGHT" );
rb = ResourceBundle.getBundle("TestBundle", new Locale("iw", "IL"));
assertEquals(rb, ComponentOrientation.RIGHT_TO_LEFT, "iw == RIGHT_TO_LEFT" );
// This bundle has no orientation setting at all, so we should get
// the system's default orientation for Arabic
rb = ResourceBundle.getBundle("TestBundle1", new Locale("ar", ""));
assertEquals(rb, ComponentOrientation.RIGHT_TO_LEFT, "ar == RIGHT_TO_LEFT" );
System.out.println(" } Pass");
}
static void assertEquals(ResourceBundle rb, ComponentOrientation o, String str) {
Assert(ComponentOrientation.getOrientation(rb) == o, str);
}
static void Assert(boolean condition, String str) {
if (!condition) {
System.err.println(" ASSERT FAILED: " + str);
throw new RuntimeException("Assert Failed: " + str);
}
}
}

View File

@ -0,0 +1,117 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4108453
* @summary Test ComponentOrientation (Bidi) support in BorderLayout
*/
/*
* (C) Copyright IBM Corp. 1998 - All Rights Reserved
*
* The original version of this source code and documentation is copyrighted
* and owned by IBM, Inc. These materials are provided under terms of a
* License Agreement between IBM and Sun. This technology is protected by
* multiple US and International patents. This notice and attribution to IBM
* may not be removed.
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class BorderTest extends Applet {
Panel panel1;
Panel panel2;
public BorderTest() {
setLayout(new GridLayout(0,2));
// Create a panel with a BorderLayout and a bunch of buttons in it
panel1 = new Panel();
panel1.setLayout(new BorderLayout());
panel1.add("North", new Button("North"));
panel1.add("South", new Button("South"));
panel1.add("East", new Button("East"));
panel1.add("West", new Button("West"));
panel1.add("Center", new Button("Center"));
add(panel1);
// Create a panel with a BorderLayout and a bunch of buttons in it
panel2 = new Panel();
panel2.setLayout(new BorderLayout());
panel2.add(BorderLayout.BEFORE_FIRST_LINE, new Button("FirstLine"));
panel2.add(BorderLayout.AFTER_LAST_LINE, new Button("LastLine"));
panel2.add(BorderLayout.BEFORE_LINE_BEGINS, new Button("FirstItem"));
panel2.add(BorderLayout.AFTER_LINE_ENDS, new Button("LastItem"));
panel2.add("Center", new Button("Center"));
add(panel2);
// Create a popup menu for switching between orientations
{
Choice c = new Choice();
c.addItem("LEFT_TO_RIGHT");
c.addItem("RIGHT_TO_LEFT");
c.addItem("UNKNOWN");
c.addItemListener( new ItemListener() {
public void itemStateChanged(ItemEvent e) {
String item = (String)(e.getItem());
ComponentOrientation o = ComponentOrientation.UNKNOWN;
if (item.equals("LEFT_TO_RIGHT")) {
o = ComponentOrientation.LEFT_TO_RIGHT;
} else if (item.equals("RIGHT_TO_LEFT")) {
o = ComponentOrientation.RIGHT_TO_LEFT;
}
panel1.setComponentOrientation(o);
panel2.setComponentOrientation(o);
panel1.layout();
panel2.layout();
panel1.repaint();
panel2.repaint();
}
} );
add(c);
}
}
public static void main(String args[]) {
Frame f = new Frame("BorderTest");
f.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
e.getWindow().hide();
e.getWindow().dispose();
System.exit(0);
};
} );
BorderTest BorderTest = new BorderTest();
BorderTest.init();
BorderTest.start();
f.add("Center", BorderTest);
f.setSize(450, 300);
f.show();
}
}

View File

@ -0,0 +1,150 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4108453
* @summary Test ComponentOrientation (Bidi) support in FlowLayout
*/
/*
* (C) Copyright IBM Corp. 1998 - All Rights Reserved
*
* The original version of this source code and documentation is copyrighted
* and owned by IBM, Inc. These materials are provided under terms of a
* License Agreement between IBM and Sun. This technology is protected by
* multiple US and International patents. This notice and attribution to IBM
* may not be removed.
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class FlowTest extends Applet {
Panel panel;
public FlowTest() {
setLayout(new BorderLayout());
// Create a panel with a FlowLayout and a bunch of buttons in it
panel = new Panel();
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
panel.add(new Button("one"));
panel.add(new Button("two"));
panel.add(new Button("three"));
panel.add(new Button("four"));
panel.add(new Button("five"));
panel.add(new Button("six"));
panel.add(new Button("seven"));
panel.add(new Button("eight"));
panel.add(new Button("nine"));
panel.add(new Button("ten"));
panel.add(new Button("eleven"));
add("Center", panel);
Panel controls = new Panel();
controls.setLayout(new GridLayout(0, 2));
// Menu for setting the alignment of the main FlowLayout panel
{
Choice c = new Choice();
c.addItem("LEFT");
c.addItem("CENTER");
c.addItem("RIGHT");
c.addItem("LEADING");
c.addItem("TRAILING");
c.addItemListener( new ItemListener() {
public void itemStateChanged(ItemEvent e) {
String item = (String)(e.getItem());
FlowLayout layout = (FlowLayout) panel.getLayout();
if (item.equals("LEFT")) {
layout.setAlignment(FlowLayout.LEFT);
} else if (item.equals("CENTER")) {
layout.setAlignment(FlowLayout.CENTER);
} else if (item.equals("RIGHT")) {
layout.setAlignment(FlowLayout.RIGHT);
} else if (item.equals("LEADING")) {
layout.setAlignment(FlowLayout.LEADING);
} else if (item.equals("TRAILING")) {
layout.setAlignment(FlowLayout.TRAILING);
}
panel.layout();
panel.repaint();
}
} );
controls.add(new Label("FlowLayout Alignment:"));
controls.add(c);
}
// Create a popup menu for switching the Panel between orientations
{
Choice c = new Choice();
c.addItem("LEFT_TO_RIGHT");
c.addItem("RIGHT_TO_LEFT");
c.addItem("UNKNOWN");
c.addItemListener( new ItemListener() {
public void itemStateChanged(ItemEvent e) {
String item = (String)(e.getItem());
if (item.equals("LEFT_TO_RIGHT")) {
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
} else if (item.equals("RIGHT_TO_LEFT")) {
panel.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
} else {
panel.setComponentOrientation(ComponentOrientation.UNKNOWN);
}
panel.layout();
panel.repaint();
}
} );
controls.add(new Label("ComponentOrientation:"));
controls.add(c);
}
add("South", controls);
}
public static void main(String args[]) {
Frame f = new Frame("FlowTest");
f.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
e.getWindow().hide();
e.getWindow().dispose();
System.exit(0);
};
} );
FlowTest flowTest = new FlowTest();
flowTest.init();
flowTest.start();
f.add("Center", flowTest);
f.setSize(300, 300);
f.show();
}
}

View File

@ -0,0 +1,46 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* 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.
*/
/**
* TestBundle.java -- used by BasicTest
*
* (C) Copyright IBM Corp. 1998 - All Rights Reserved
*
* The original version of this source code and documentation is copyrighted
* and owned by IBM, Inc. These materials are provided under terms of a
* License Agreement between IBM and Sun. This technology is protected by
* multiple US and International patents. This notice and attribution to IBM
* may not be removed.
*/
import java.util.ListResourceBundle;
import java.awt.ComponentOrientation;
public class TestBundle extends ListResourceBundle {
protected Object[][] getContents() {
return new Object[][] {
{ "Orientation", ComponentOrientation.UNKNOWN },
};
}
};

View File

@ -0,0 +1,49 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* 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.
*/
/**
* TestBundle1.java -- used by BasicTest
*
* @bug 4108453
* @summary Basic tests for java.awt.ComponentOrientation
*
* (C) Copyright IBM Corp. 1998 - All Rights Reserved
*
* The original version of this source code and documentation is copyrighted
* and owned by IBM, Inc. These materials are provided under terms of a
* License Agreement between IBM and Sun. This technology is protected by
* multiple US and International patents. This notice and attribution to IBM
* may not be removed.
*/
import java.util.ListResourceBundle;
import java.awt.ComponentOrientation;
public class TestBundle1 extends ListResourceBundle {
protected Object[][] getContents() {
return new Object[][] {
{ },
};
}
};

View File

@ -0,0 +1,49 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* 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.
*/
/**
* TestBundle1_ar.java -- used by BasicTest
*
* @bug 4108453
* @summary Basic tests for java.awt.ComponentOrientation
*
* (C) Copyright IBM Corp. 1998 - All Rights Reserved
*
* The original version of this source code and documentation is copyrighted
* and owned by IBM, Inc. These materials are provided under terms of a
* License Agreement between IBM and Sun. This technology is protected by
* multiple US and International patents. This notice and attribution to IBM
* may not be removed.
*/
import java.util.ListResourceBundle;
import java.awt.ComponentOrientation;
public class TestBundle1_ar extends ListResourceBundle {
protected Object[][] getContents() {
return new Object[][] {
{ },
};
}
};

View File

@ -0,0 +1,46 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* 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.
*/
/**
* TestBundle_es.java -- used by BasicTest
*
* (C) Copyright IBM Corp. 1998 - All Rights Reserved
*
* The original version of this source code and documentation is copyrighted
* and owned by IBM, Inc. These materials are provided under terms of a
* License Agreement between IBM and Sun. This technology is protected by
* multiple US and International patents. This notice and attribution to IBM
* may not be removed.
*/
import java.util.ListResourceBundle;
import java.awt.ComponentOrientation;
public class TestBundle_es extends ListResourceBundle {
protected Object[][] getContents() {
return new Object[][] {
{ "Orientation", ComponentOrientation.LEFT_TO_RIGHT },
};
}
};

View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* 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.
*/
/**
*
*
* used by BasicTest
*
* (C) Copyright IBM Corp. 1998 - All Rights Reserved
*
* The original version of this source code and documentation is copyrighted
* and owned by IBM, Inc. These materials are provided under terms of a
* License Agreement between IBM and Sun. This technology is protected by
* multiple US and International patents. This notice and attribution to IBM
* may not be removed.
*/
import java.util.ListResourceBundle;
import java.awt.ComponentOrientation;
public class TestBundle_iw extends ListResourceBundle {
protected Object[][] getContents() {
return new Object[][] {
{ "Orientation", ComponentOrientation.RIGHT_TO_LEFT },
};
}
};

View File

@ -0,0 +1,155 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4108453 4778440 6304785
* @summary Test Window.applyResourceBundle orientation support
*
* @build TestBundle TestBundle_es TestBundle_iw
* @build TestBundle1 TestBundle1_ar
* @run main WindowTest
*/
import java.awt.*;
import java.applet.*;
import java.util.Locale;
import java.util.ResourceBundle;
public class WindowTest extends Applet {
static Exception failure=null;
static Thread mainThread=null;
public static void main(String args[]) throws Exception {
mainThread = Thread.currentThread();
WindowTest app = new WindowTest();
app.start();
try {
Thread.sleep(300000);
} catch (InterruptedException e) {
if (failure != null) {
throw failure;
}
}
}
public void start() {
try {
doTest();
} catch (Exception e) {
failure = e;
}
mainThread.interrupt();
}
public void doTest() {
System.out.println("WindowTest {");
ResourceBundle rb;
Frame myFrame;
// Create a window containing a hierarchy of components.
System.out.println(" Creating component hierarchy...");
myFrame = new Frame();
myFrame.setLayout(new FlowLayout());
Panel panel1 = new Panel();
panel1.setLayout(new BorderLayout());
panel1.add("North", new Button("North"));
panel1.add("South", new Button("South"));
panel1.add("East", new Button("East"));
panel1.add("West", new Button("West"));
panel1.add("Center", new Button("Center"));
myFrame.add(panel1);
Panel panel2 = new Panel();
panel2.setLayout(new BorderLayout());
panel2.add(BorderLayout.BEFORE_FIRST_LINE, new Button("FirstLine"));
panel2.add(BorderLayout.AFTER_LAST_LINE, new Button("LastLine"));
panel2.add(BorderLayout.BEFORE_LINE_BEGINS, new Button("FirstItem"));
panel2.add(BorderLayout.AFTER_LINE_ENDS, new Button("LastItem"));
panel2.add("Center", new Button("Center"));
myFrame.add(panel2);
// After construction, all of the components' orientations should be
// set to ComponentOrientation.UNKNOWN.
System.out.println(" Verifying orientation is UNKNOWN...");
verifyOrientation(myFrame, ComponentOrientation.UNKNOWN);
// This will load TestBundle1 using the default locale and apply
// it to the component hierarchy. Since the bundle has no Orientation
// specified, this should fall back to the bundle-locale's orientation
System.out.println(" Applying TestBundle1 by name and verifying...");
myFrame.applyResourceBundle("TestBundle1");
verifyOrientation(myFrame,
ComponentOrientation.getOrientation(
ResourceBundle.getBundle("TestBundle1", Locale.getDefault())));
System.out.println(" Applying TestBundle_iw and verifying...");
rb = ResourceBundle.getBundle("TestBundle", new Locale("iw", ""));
myFrame.applyResourceBundle(rb);
verifyOrientation(myFrame, ComponentOrientation.RIGHT_TO_LEFT);
System.out.println(" Applying TestBundle_es and verifying...");
rb = ResourceBundle.getBundle("TestBundle", new Locale("es", ""));
myFrame.applyResourceBundle(rb);
verifyOrientation(myFrame, ComponentOrientation.LEFT_TO_RIGHT);
myFrame.setVisible(false);
myFrame.dispose();
System.out.println("}");
}
static void verifyOrientation(Component c, ComponentOrientation orient) {
ComponentOrientation o = c.getComponentOrientation();
if (o != orient) {
throw new RuntimeException("ERROR: expected " + oString(orient) +
", got " + oString(o) +
" on component " + c);
}
if (c instanceof Container) {
Container cont = (Container) c;
int ncomponents = cont.getComponentCount();
for (int i = 0 ; i < ncomponents ; ++i) {
Component comp = cont.getComponent(i);
verifyOrientation(comp, orient);
}
}
}
static String oString(ComponentOrientation o) {
if (o == ComponentOrientation.LEFT_TO_RIGHT) {
return "LEFT_TO_RIGHT";
}
else if (o == ComponentOrientation.RIGHT_TO_LEFT) {
return "RIGHT_TO_LEFT";
}
else {
return "UNKNOWN";
}
}
}

View File

@ -202,7 +202,7 @@ public class VerifyStackTrace {
// synthetic frames introduced by lambdas & method handles // synthetic frames introduced by lambdas & method handles
return produced.replaceAll(":[1-9][0-9]*\\)", ":00)") return produced.replaceAll(":[1-9][0-9]*\\)", ":00)")
.replaceAll("-internal/", "/").replaceAll("-ea/", "/") .replaceAll("-internal/", "/").replaceAll("-ea/", "/")
.replaceAll("java.base@[0-9]+/", "java.base/") .replaceAll("java.base@(\\d+\\.){0,3}(\\d+)/", "java.base/")
.replaceAll("/[0-9]+\\.run", "/xxxxxxxx.run") .replaceAll("/[0-9]+\\.run", "/xxxxxxxx.run")
.replaceAll("/[0-9]+\\.invoke", "/xxxxxxxx.invoke") .replaceAll("/[0-9]+\\.invoke", "/xxxxxxxx.invoke")
.replaceAll("\\$[0-9]+", "\\$??"); .replaceAll("\\$[0-9]+", "\\$??");

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -38,6 +38,7 @@ import java.io.InputStream;
import java.lang.module.ModuleFinder; import java.lang.module.ModuleFinder;
import java.lang.module.ModuleReader; import java.lang.module.ModuleReader;
import java.lang.module.ModuleReference; import java.lang.module.ModuleReference;
import java.lang.reflect.Module;
import java.net.URI; import java.net.URI;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
@ -64,16 +65,24 @@ public class ModuleReaderTest {
private static final Path SRC_DIR = Paths.get(TEST_SRC, "src"); private static final Path SRC_DIR = Paths.get(TEST_SRC, "src");
private static final Path MODS_DIR = Paths.get("mods"); private static final Path MODS_DIR = Paths.get("mods");
// the module name of the base module
private static final String BASE_MODULE = "java.base";
// the module name of the test module // the module name of the test module
private static final String TEST_MODULE = "m"; private static final String TEST_MODULE = "m";
// resources in the base module
private static final String[] BASE_RESOURCES = {
"java/lang/Object.class"
};
// resources in test module (can't use module-info.class as a test // resources in test module (can't use module-info.class as a test
// resource as it will be modified by the jmod tool) // resource as it will be modified by the jmod tool)
private static final String[] RESOURCES = { private static final String[] TEST_RESOURCES = {
"p/Main.class" "p/Main.class"
}; };
// a resource that is not in the test module // a resource that is not in the base or test module
private static final String NOT_A_RESOURCE = "NotAResource"; private static final String NOT_A_RESOURCE = "NotAResource";
@ -89,7 +98,74 @@ public class ModuleReaderTest {
/** /**
* Test exploded module * Test ModuleReader to module in runtime image
*/
public void testImage() throws Exception {
ModuleFinder finder = ModuleFinder.ofSystem();
ModuleReference mref = finder.find(BASE_MODULE).get();
ModuleReader reader = mref.open();
try (reader) {
for (String name : BASE_RESOURCES) {
byte[] expectedBytes;
Module baseModule = Object.class.getModule();
try (InputStream in = baseModule.getResourceAsStream(name)) {
expectedBytes = in.readAllBytes();
}
testFind(reader, name, expectedBytes);
testOpen(reader, name, expectedBytes);
testRead(reader, name, expectedBytes);
}
// test "not found"
assertFalse(reader.find(NOT_A_RESOURCE).isPresent());
assertFalse(reader.open(NOT_A_RESOURCE).isPresent());
assertFalse(reader.read(NOT_A_RESOURCE).isPresent());
// test nulls
try {
reader.find(null);
assertTrue(false);
} catch (NullPointerException expected) { }
try {
reader.open(null);
assertTrue(false);
} catch (NullPointerException expected) { }
try {
reader.read(null);
assertTrue(false);
} catch (NullPointerException expected) { }
try {
reader.release(null);
assertTrue(false);
} catch (NullPointerException expected) { }
}
// test closed ModuleReader
try {
reader.open(BASE_RESOURCES[0]);
assertTrue(false);
} catch (IOException expected) { }
try {
reader.read(BASE_RESOURCES[0]);
assertTrue(false);
} catch (IOException expected) { }
}
/**
* Test ModuleReader to exploded module
*/ */
public void testExplodedModule() throws Exception { public void testExplodedModule() throws Exception {
test(MODS_DIR); test(MODS_DIR);
@ -97,7 +173,7 @@ public class ModuleReaderTest {
/** /**
* Test modular JAR * Test ModuleReader to modular JAR
*/ */
public void testModularJar() throws Exception { public void testModularJar() throws Exception {
Path dir = Files.createTempDirectory(USER_DIR, "mlib"); Path dir = Files.createTempDirectory(USER_DIR, "mlib");
@ -111,7 +187,7 @@ public class ModuleReaderTest {
/** /**
* Test JMOD * Test ModuleReader to JMOD
*/ */
public void testJMod() throws Exception { public void testJMod() throws Exception {
Path dir = Files.createTempDirectory(USER_DIR, "mlib"); Path dir = Files.createTempDirectory(USER_DIR, "mlib");
@ -145,7 +221,7 @@ public class ModuleReaderTest {
try (reader) { try (reader) {
// test each of the known resources in the module // test each of the known resources in the module
for (String name : RESOURCES) { for (String name : TEST_RESOURCES) {
byte[] expectedBytes byte[] expectedBytes
= Files.readAllBytes(MODS_DIR = Files.readAllBytes(MODS_DIR
.resolve(TEST_MODULE) .resolve(TEST_MODULE)
@ -157,6 +233,7 @@ public class ModuleReaderTest {
} }
// test "not found" // test "not found"
assertFalse(reader.find(NOT_A_RESOURCE).isPresent());
assertFalse(reader.open(NOT_A_RESOURCE).isPresent()); assertFalse(reader.open(NOT_A_RESOURCE).isPresent());
assertFalse(reader.read(NOT_A_RESOURCE).isPresent()); assertFalse(reader.read(NOT_A_RESOURCE).isPresent());
@ -176,19 +253,22 @@ public class ModuleReaderTest {
assertTrue(false); assertTrue(false);
} catch (NullPointerException expected) { } } catch (NullPointerException expected) { }
// should release(null) throw NPE? try {
reader.release(null);
throw new RuntimeException();
} catch (NullPointerException expected) { }
} }
// test closed ModuleReader // test closed ModuleReader
try { try {
reader.open(RESOURCES[0]); reader.open(TEST_RESOURCES[0]);
assertTrue(false); assertTrue(false);
} catch (IOException expected) { } } catch (IOException expected) { }
try { try {
reader.read(RESOURCES[0]); reader.read(TEST_RESOURCES[0]);
assertTrue(false); assertTrue(false);
} catch (IOException expected) { } } catch (IOException expected) { }
} }

View File

@ -103,7 +103,7 @@ public class BasicLayerTest {
/** /**
* Exercise Layer.create, created on an empty layer * Exercise Layer defineModules, created with empty layer as parent
*/ */
public void testLayerOnEmpty() { public void testLayerOnEmpty() {
ModuleDescriptor descriptor1 ModuleDescriptor descriptor1
@ -184,7 +184,7 @@ public class BasicLayerTest {
/** /**
* Exercise Layer.create, created over the boot layer * Exercise Layer defineModules, created with boot layer as parent
*/ */
public void testLayerOnBoot() { public void testLayerOnBoot() {
ModuleDescriptor descriptor1 ModuleDescriptor descriptor1
@ -247,8 +247,8 @@ public class BasicLayerTest {
/** /**
* Layer.create with a configuration of two modules that have the same * Exercise Layer defineModules with a configuration of two modules that
* module-private package. * have the same module-private package.
*/ */
public void testSameConcealedPackage() { public void testSameConcealedPackage() {
ModuleDescriptor descriptor1 ModuleDescriptor descriptor1
@ -281,8 +281,8 @@ public class BasicLayerTest {
/** /**
* Layer.create with a configuration with a partitioned graph. The same * Exercise Layer defineModules with a configuration that is a partitioned
* package is exported in both partitions. * graph. The same package is exported in both partitions.
*/ */
public void testSameExportInPartitionedGraph() { public void testSameExportInPartitionedGraph() {
@ -338,9 +338,9 @@ public class BasicLayerTest {
/** /**
* Layer.create with a configuration that contains a module that has a * Exercise Layer defineModules with a configuration that contains a module
* concealed package that is the same name as a non-exported package * that has a concealed package that is the same name as a non-exported
* in a parent layer. * package in a parent layer.
*/ */
public void testConcealSamePackageAsBootLayer() { public void testConcealSamePackageAsBootLayer() {
@ -667,9 +667,9 @@ public class BasicLayerTest {
/** /**
* Attempt to use Layer.create to create a layer with a module defined to a * Attempt to use Layer defineModules to create a layer with a module
* class loader that already has a module of the same name defined to the * defined to a class loader that already has a module of the same name
* class loader. * defined to the class loader.
*/ */
@Test(expectedExceptions = { LayerInstantiationException.class }) @Test(expectedExceptions = { LayerInstantiationException.class })
public void testModuleAlreadyDefinedToLoader() { public void testModuleAlreadyDefinedToLoader() {
@ -696,9 +696,9 @@ public class BasicLayerTest {
/** /**
* Attempt to use Layer.create to create a Layer with a module containing * Attempt to use Layer defineModules to create a Layer with a module
* package {@code p} where the class loader already has a module defined * containing package {@code p} where the class loader already has a module
* to it containing package {@code p}. * defined to it containing package {@code p}.
*/ */
@Test(expectedExceptions = { LayerInstantiationException.class }) @Test(expectedExceptions = { LayerInstantiationException.class })
public void testPackageAlreadyInNamedModule() { public void testPackageAlreadyInNamedModule() {
@ -738,8 +738,9 @@ public class BasicLayerTest {
/** /**
* Attempt to use Layer.create to create a Layer with a module containing * Attempt to use Layer defineModules to create a Layer with a module
* a package in which a type is already loaded by the class loader. * containing a package in which a type is already loaded by the class
* loader.
*/ */
@Test(expectedExceptions = { LayerInstantiationException.class }) @Test(expectedExceptions = { LayerInstantiationException.class })
public void testPackageAlreadyInUnnamedModule() throws Exception { public void testPackageAlreadyInUnnamedModule() throws Exception {
@ -762,6 +763,46 @@ public class BasicLayerTest {
} }
/**
* Attempt to create a Layer with a module named "java.base".
*/
public void testLayerWithJavaBase() {
ModuleDescriptor descriptor
= new ModuleDescriptor.Builder("java.base")
.exports("java.lang")
.build();
ModuleFinder finder = ModuleUtils.finderOf(descriptor);
Configuration cf = Layer.boot()
.configuration()
.resolveRequires(finder, ModuleFinder.of(), Set.of("java.base"));
assertTrue(cf.modules().size() == 1);
ClassLoader scl = ClassLoader.getSystemClassLoader();
try {
Layer.boot().defineModules(cf, loader -> null );
assertTrue(false);
} catch (LayerInstantiationException e) { }
try {
Layer.boot().defineModules(cf, loader -> new ClassLoader() { });
assertTrue(false);
} catch (LayerInstantiationException e) { }
try {
Layer.boot().defineModulesWithOneLoader(cf, scl);
assertTrue(false);
} catch (LayerInstantiationException e) { }
try {
Layer.boot().defineModulesWithManyLoaders(cf, scl);
assertTrue(false);
} catch (LayerInstantiationException e) { }
}
/** /**
* Parent of configuration != configuration of parent Layer * Parent of configuration != configuration of parent Layer
*/ */
@ -812,7 +853,6 @@ public class BasicLayerTest {
@Test(expectedExceptions = { NullPointerException.class }) @Test(expectedExceptions = { NullPointerException.class })
public void testCreateWithNull2() { public void testCreateWithNull2() {
ClassLoader loader = new ClassLoader() { };
Configuration cf = resolveRequires(Layer.boot().configuration(), ModuleFinder.of()); Configuration cf = resolveRequires(Layer.boot().configuration(), ModuleFinder.of());
Layer.boot().defineModules(cf, null); Layer.boot().defineModules(cf, null);
} }

View File

@ -70,7 +70,7 @@ public class LayerAndLoadersTest {
/** /**
* Basic test of Layer.defineModulesWithOneLoader * Basic test of Layer defineModulesWithOneLoader
* *
* Test scenario: * Test scenario:
* m1 requires m2 and m3 * m1 requires m2 and m3
@ -99,7 +99,7 @@ public class LayerAndLoadersTest {
/** /**
* Basic test of Layer.defineModulesWithManyLoaders * Basic test of Layer defineModulesWithManyLoaders
* *
* Test scenario: * Test scenario:
* m1 requires m2 and m3 * m1 requires m2 and m3
@ -131,7 +131,7 @@ public class LayerAndLoadersTest {
/** /**
* Basic test of Layer.defineModulesWithOneLoader where one of the modules * Basic test of Layer defineModulesWithOneLoader where one of the modules
* is a service provider module. * is a service provider module.
* *
* Test scenario: * Test scenario:
@ -172,8 +172,8 @@ public class LayerAndLoadersTest {
/** /**
* Basic test of Layer.defineModulesWithManyLoaders where one of the modules * Basic test of Layer defineModulesWithManyLoaders where one of the
* is a service provider module. * modules is a service provider module.
* *
* Test scenario: * Test scenario:
* m1 requires m2 and m3 * m1 requires m2 and m3
@ -224,7 +224,7 @@ public class LayerAndLoadersTest {
/** /**
* Tests that the class loaders created by Layer.createWithXXX delegate * Tests that the class loaders created by defineModulesWithXXX delegate
* to the given parent class loader. * to the given parent class loader.
*/ */
public void testDelegationToParent() throws Exception { public void testDelegationToParent() throws Exception {
@ -254,7 +254,7 @@ public class LayerAndLoadersTest {
/** /**
* Test Layer.createWithXXX when modules that have overlapping packages. * Test defineModulesWithXXX when modules that have overlapping packages.
* *
* Test scenario: * Test scenario:
* m1 exports p * m1 exports p
@ -288,7 +288,7 @@ public class LayerAndLoadersTest {
/** /**
* Test Layer.createWithXXX with split delegation. * Test Layer defineModulesWithXXX with split delegation.
* *
* Test scenario: * Test scenario:
* layer1: m1 exports p, m2 exports p * layer1: m1 exports p, m2 exports p
@ -319,7 +319,8 @@ public class LayerAndLoadersTest {
ModuleFinder finder2 = ModuleUtils.finderOf(descriptor3, descriptor4); ModuleFinder finder2 = ModuleUtils.finderOf(descriptor3, descriptor4);
Configuration cf2 = cf1.resolveRequires(finder2, ModuleFinder.of(), Set.of("m3", "m4")); Configuration cf2 = cf1.resolveRequires(finder2, ModuleFinder.of(),
Set.of("m3", "m4"));
// package p cannot be supplied by two class loaders // package p cannot be supplied by two class loaders
try { try {
@ -335,8 +336,8 @@ public class LayerAndLoadersTest {
/** /**
* Test Layer.createWithXXX when the modules that override same named * Test Layer defineModulesWithXXX when the modules that override same
* modules in the parent layer. * named modules in the parent layer.
* *
* Test scenario: * Test scenario:
* layer1: m1, m2, m3 => same loader * layer1: m1, m2, m3 => same loader
@ -350,7 +351,8 @@ public class LayerAndLoadersTest {
checkLayer(layer1, "m1", "m2", "m3"); checkLayer(layer1, "m1", "m2", "m3");
ModuleFinder finder = ModuleFinder.of(MODS_DIR); ModuleFinder finder = ModuleFinder.of(MODS_DIR);
Configuration cf2 = cf1.resolveRequires(finder, ModuleFinder.of(), Set.of("m1")); Configuration cf2 = cf1.resolveRequires(finder, ModuleFinder.of(),
Set.of("m1"));
Layer layer2 = layer1.defineModulesWithOneLoader(cf2, null); Layer layer2 = layer1.defineModulesWithOneLoader(cf2, null);
checkLayer(layer2, "m1", "m2", "m3"); checkLayer(layer2, "m1", "m2", "m3");
@ -383,8 +385,8 @@ public class LayerAndLoadersTest {
/** /**
* Test Layer.createWithXXX when the modules that override same named * Test Layer defineModulesWithXXX when the modules that override same
* modules in the parent layer. * named modules in the parent layer.
* *
* Test scenario: * Test scenario:
* layer1: m1, m2, m3 => loader pool * layer1: m1, m2, m3 => loader pool
@ -398,7 +400,8 @@ public class LayerAndLoadersTest {
checkLayer(layer1, "m1", "m2", "m3"); checkLayer(layer1, "m1", "m2", "m3");
ModuleFinder finder = ModuleFinder.of(MODS_DIR); ModuleFinder finder = ModuleFinder.of(MODS_DIR);
Configuration cf2 = cf1.resolveRequires(finder, ModuleFinder.of(), Set.of("m1")); Configuration cf2 = cf1.resolveRequires(finder, ModuleFinder.of(),
Set.of("m1"));
Layer layer2 = layer1.defineModulesWithManyLoaders(cf2, null); Layer layer2 = layer1.defineModulesWithManyLoaders(cf2, null);
checkLayer(layer2, "m1", "m2", "m3"); checkLayer(layer2, "m1", "m2", "m3");
@ -477,8 +480,8 @@ public class LayerAndLoadersTest {
/** /**
* Test Layer.createWithXXX when the modules that override same named * Test Layer defineModulesWithXXX when the modules that override same
* modules in the parent layer. * named modules in the parent layer.
* *
* layer1: m1, m2, m3 => same loader * layer1: m1, m2, m3 => same loader
* layer2: m1, m3 => same loader * layer2: m1, m3 => same loader
@ -492,7 +495,8 @@ public class LayerAndLoadersTest {
ModuleFinder finder = finderFor("m1", "m3"); ModuleFinder finder = finderFor("m1", "m3");
Configuration cf2 = cf1.resolveRequires(finder, ModuleFinder.of(), Set.of("m1")); Configuration cf2 = cf1.resolveRequires(finder, ModuleFinder.of(),
Set.of("m1"));
Layer layer2 = layer1.defineModulesWithOneLoader(cf2, null); Layer layer2 = layer1.defineModulesWithOneLoader(cf2, null);
checkLayer(layer2, "m1", "m3"); checkLayer(layer2, "m1", "m3");
@ -513,8 +517,8 @@ public class LayerAndLoadersTest {
/** /**
* Test Layer.createWithXXX when the modules that override same named * Test Layer defineModulesWithXXX when the modules that override same
* modules in the parent layer. * named modules in the parent layer.
* *
* layer1: m1, m2, m3 => loader pool * layer1: m1, m2, m3 => loader pool
* layer2: m1, m3 => loader pool * layer2: m1, m3 => loader pool
@ -528,7 +532,8 @@ public class LayerAndLoadersTest {
ModuleFinder finder = finderFor("m1", "m3"); ModuleFinder finder = finderFor("m1", "m3");
Configuration cf2 = cf1.resolveRequires(finder, ModuleFinder.of(), Set.of("m1")); Configuration cf2 = cf1.resolveRequires(finder, ModuleFinder.of(),
Set.of("m1"));
Layer layer2 = layer1.defineModulesWithManyLoaders(cf2, null); Layer layer2 = layer1.defineModulesWithManyLoaders(cf2, null);
checkLayer(layer2, "m1", "m3"); checkLayer(layer2, "m1", "m3");

View File

@ -0,0 +1,147 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* 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.logging
* @summary Test java.lang.reflect.Module methods that specify permission checks
* @run main/othervm -Djava.security.policy=${test.src}/allow.policy WithSecurityManager allow
* @run main/othervm WithSecurityManager deny
*/
import java.io.IOException;
import java.io.InputStream;
import java.lang.module.Configuration;
import java.lang.module.ModuleFinder;
import java.lang.module.ModuleReference;
import java.lang.reflect.Layer;
import java.lang.reflect.Module;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
/**
* Test java.lang.reflect.Module methods that specify permission checks.
*/
public class WithSecurityManager {
// a module that will be loaded into a child layer
static final String ANOTHER_MODULE = "java.logging";
static final String ANOTHER_MODULE_RESOURCE = "java/util/logging/Logger.class";
public static void main(String[] args) throws IOException {
boolean allow = args[0].equals("allow");
// base module, in the boot layer
Module base = Object.class.getModule();
// another module, in a child layer
Module other = loadModuleInChildLayer(ANOTHER_MODULE);
assertTrue(other.getLayer() != Layer.boot());
System.setSecurityManager(new SecurityManager());
test(base, "java/lang/Object.class", allow);
test(other, ANOTHER_MODULE_RESOURCE, allow);
}
/**
* Test the permission checks by invoking methods on the given module.
*
* If {@code allow} is {@code true} then the permission checks should succeed.
*/
static void test(Module m, String name, boolean allow) throws IOException {
// test Module::getClassLoader
System.out.format("Test getClassLoader on %s ...%n", m);
try {
ClassLoader cl = m.getClassLoader();
System.out.println(cl);
if (!allow)
assertTrue("getClassLoader should have failed", false);
} catch (SecurityException e) {
System.out.println(e + " thrown");
if (allow)
throw e;
}
// test Module::getResourceAsStream
System.out.format("Test getResourceAsStream(\"%s\") on %s ...%n", name, m);
try (InputStream in = m.getResourceAsStream(name)) {
System.out.println(in);
if (allow && (in == null))
assertTrue(name + " not found", false);
if (!allow && (in != null))
assertTrue(name + " should not be found", false);
}
}
/**
* Create a module layer that contains the given system module.
*/
static Module loadModuleInChildLayer(String mn) {
Optional<ModuleReference> omref = ModuleFinder.ofSystem().find(mn);
assertTrue("module " + mn + " not a system module", omref.isPresent());
// create a ModuleFinder that only finds this module
ModuleReference mref = omref.get();
ModuleFinder finder = new ModuleFinder() {
@Override
public Optional<ModuleReference> find(String name) {
if (name.equals(mn))
return Optional.of(mref);
else
return Optional.empty();
}
@Override
public Set<ModuleReference> findAll() {
return Collections.singleton(mref);
}
};
// create a child configuration and layer with this module
Layer bootLayer = Layer.boot();
Configuration cf = bootLayer
.configuration()
.resolveRequires(finder, ModuleFinder.of(), Set.of(ANOTHER_MODULE));
Layer layer = bootLayer.defineModulesWithOneLoader(cf, null);
Optional<Module> om = layer.findModule(mn);
assertTrue("module " + mn + " not in child layer", om.isPresent());
return om.get();
}
static void assertTrue(String msg, boolean e) {
if (!e)
throw new RuntimeException(msg);
}
static void assertTrue(boolean e) {
if (!e)
throw new RuntimeException();
}
}

View File

@ -0,0 +1,27 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* 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.
*/
grant {
permission java.lang.RuntimePermission "getClassLoader";
permission java.io.FilePermission "${java.home}/-", "read";
};

View File

@ -0,0 +1,132 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8016521
* @summary InetAddress should not always re-order addresses returned from name
* service
* @run main/othervm -Djava.net.preferIPv6Addresses=false PreferIPv6AddressesTest
* @run main/othervm -Djava.net.preferIPv6Addresses=true PreferIPv6AddressesTest
* @run main/othervm -Djava.net.preferIPv6Addresses=system PreferIPv6AddressesTest
* @run main/othervm PreferIPv6AddressesTest
*/
import java.io.IOException;
import java.net.*;
import java.nio.channels.DatagramChannel;
import java.util.Arrays;
import java.util.stream.IntStream;
import static java.lang.System.out;
public class PreferIPv6AddressesTest {
// A name, that if resolves, returns both IPv4 and IPv6 addresses.
static final String HOST_NAME = "www.google.com";
static final InetAddress LOOPBACK = InetAddress.getLoopbackAddress();
static final String preferIPV6Address =
System.getProperty("java.net.preferIPv6Addresses", "false");
public static void main(String args[]) throws IOException {
InetAddress addrs[];
try {
addrs = InetAddress.getAllByName(HOST_NAME);
} catch (UnknownHostException e) {
out.println("Unknown host " + HOST_NAME + ", cannot run test.");
return;
}
int firstIPv4Address = IntStream.range(0, addrs.length)
.filter(x -> addrs[x] instanceof Inet4Address)
.findFirst().orElse(-1);
int firstIPv6Address = IntStream.range(0, addrs.length)
.filter(x -> addrs[x] instanceof Inet6Address)
.findFirst().orElse(-1);
out.println("IPv6 supported: " + IPv6Supported());
out.println("Addresses: " + Arrays.asList(addrs));
if (preferIPV6Address.equalsIgnoreCase("true") && firstIPv6Address != -1) {
int off = firstIPv4Address != -1 ? firstIPv4Address : addrs.length;
assertAllv6Addresses(addrs, 0, off);
assertAllv4Addresses(addrs, off, addrs.length);
assertLoopbackAddress(Inet6Address.class);
assertAnyLocalAddress(Inet6Address.class);
} else if (preferIPV6Address.equalsIgnoreCase("false") && firstIPv4Address != -1) {
int off = firstIPv6Address != -1 ? firstIPv6Address : addrs.length;
assertAllv4Addresses(addrs, 0, off);
assertAllv6Addresses(addrs, off, addrs.length);
assertLoopbackAddress(Inet4Address.class);
assertAnyLocalAddress(Inet4Address.class);
} else if (preferIPV6Address.equalsIgnoreCase("system") && IPv6Supported()) {
assertLoopbackAddress(Inet6Address.class);
assertAnyLocalAddress(Inet6Address.class);
} else if (preferIPV6Address.equalsIgnoreCase("system") && !IPv6Supported()) {
assertLoopbackAddress(Inet4Address.class);
assertAnyLocalAddress(Inet4Address.class);
}
}
static void assertAllv4Addresses(InetAddress[] addrs, int off, int len) {
IntStream.range(off, len)
.mapToObj(x -> addrs[x])
.forEach(x -> {
if (!(x instanceof Inet4Address))
throw new RuntimeException("Expected IPv4, got " + x);
});
}
static void assertAllv6Addresses(InetAddress[] addrs, int off, int len) {
IntStream.range(off, len)
.mapToObj(x -> addrs[x])
.forEach(x -> {
if (!(x instanceof Inet6Address))
throw new RuntimeException("Expected IPv6, got " + x);
});
}
static void assertLoopbackAddress(Class<?> expectedType) {
if (!LOOPBACK.getClass().isAssignableFrom(expectedType))
throw new RuntimeException("Expected " + expectedType
+ ", got " + LOOPBACK.getClass());
}
static void assertAnyLocalAddress(Class<?> expectedType) {
InetAddress anyAddr = (new InetSocketAddress(0)).getAddress();
if (!anyAddr.getClass().isAssignableFrom(expectedType))
throw new RuntimeException("Expected " + expectedType
+ ", got " + anyAddr.getClass());
}
static boolean IPv6Supported() throws IOException {
try {
DatagramChannel.open(StandardProtocolFamily.INET6);
return true;
} catch (UnsupportedOperationException x) {
return false;
}
}
}

View File

@ -0,0 +1,159 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @library /lib/testlibrary
* @build jdk.testlibrary.ProcessTools
* ModuleTest CompilerUtils JarUtils
* @run testng ModuleTest
* @summary Basic tests for using rmi in module world
*/
import static jdk.testlibrary.ProcessTools.executeTestJava;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.io.File;
import java.nio.file.Paths;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class ModuleTest {
static String fileJoin(String... names) {
return String.join(File.separator, names);
}
static String pathJoin(String... paths) {
return String.join(File.pathSeparator, paths);
}
private static final String TEST_SRC = System.getProperty("test.src");
private static final String CLIENT_EXP = fileJoin("exploded", "mclient");
private static final String SERVER_EXP = fileJoin("exploded", "mserver");
private static final String MTEST_EXP = fileJoin("exploded", "mtest");
private static final String CLIENT_JAR = fileJoin("mods", "mclient.jar");
private static final String SERVER_JAR = fileJoin("mods", "mserver.jar");
private static final String MTEST_JAR = fileJoin("mods", "mtest.jar");
private static final String DUMMY_MAIN = "testpkg.DummyApp";
/**
* Compiles all sample classes
*/
@BeforeTest
public void compileAll() throws Exception {
assertTrue(CompilerUtils.compile(
Paths.get(TEST_SRC, "src", "mserver"),
Paths.get(SERVER_EXP)));
JarUtils.createJarFile(
Paths.get(SERVER_JAR),
Paths.get(SERVER_EXP));
assertTrue(CompilerUtils.compile(
Paths.get(TEST_SRC, "src", "mclient"),
Paths.get(CLIENT_EXP),
"-cp", SERVER_JAR));
JarUtils.createJarFile(
Paths.get(CLIENT_JAR),
Paths.get(CLIENT_EXP));
assertTrue(CompilerUtils.compile(Paths.get(TEST_SRC, "src", "mtest"),
Paths.get(MTEST_EXP),
"-cp", pathJoin(CLIENT_JAR, SERVER_JAR)));
JarUtils.createJarFile(
Paths.get(MTEST_JAR),
Paths.get(MTEST_EXP));
}
/**
* Test the client, server and dummy application in different modules
* @throws Exception
*/
@Test
public void testAllInModule() throws Exception {
assertEquals(executeTestJava("-mp", pathJoin(MTEST_JAR, CLIENT_JAR, SERVER_JAR),
"-addmods", "mclient,mserver",
"-m", "mtest/" + DUMMY_MAIN)
.outputTo(System.out)
.errorTo(System.out)
.getExitValue(),
0);
}
/**
* Test the client and server in unnamed modules,
* while the dummy application is in automatic module
* @throws Exception
*/
@Test
public void testAppInModule() throws Exception {
assertEquals(executeTestJava("-mp", MTEST_JAR,
"-cp", pathJoin(CLIENT_JAR, SERVER_JAR),
"-m", "mtest/" + DUMMY_MAIN)
.outputTo(System.out)
.errorTo(System.out)
.getExitValue(),
0);
}
/**
* Test the client and server in automatic modules,
* while the dummy application is in unnamed module
* @throws Exception
*/
@Test
public void testAppInUnnamedModule() throws Exception {
assertEquals(executeTestJava("-mp", pathJoin(CLIENT_JAR, SERVER_JAR),
"-addmods", "mclient,mserver",
"-cp", MTEST_JAR,
DUMMY_MAIN)
.outputTo(System.out)
.errorTo(System.out)
.getExitValue(),
0);
}
/**
* Test the server and test application in automatic modules,
* with client in unnamed module
* @throws Exception
*/
@Test
public void testClientInUnamedModule() throws Exception {
assertEquals(executeTestJava("-mp", pathJoin(MTEST_JAR, SERVER_JAR),
"-addmods", "mserver",
"-cp", CLIENT_JAR,
"-m", "mtest/" + DUMMY_MAIN)
.outputTo(System.out)
.errorTo(System.out)
.getExitValue(),
0);
}
}

View File

@ -0,0 +1,47 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package clientpkg;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import serverpkg.Hello;
public class Client {
int port;
Hello stub;
public Client(Hello stub) {
this.stub = stub;
}
public String testStub() throws Exception {
try {
return stub.sayHello();
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
throw e;
}
}
}

View File

@ -0,0 +1,32 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package serverpkg;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Hello extends Remote {
String sayHello() throws RemoteException;
}

View File

@ -0,0 +1,37 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package serverpkg;
public class Server implements Hello {
private final String hello = "Hello world!";
public Server() {
}
@Override
public String sayHello() {
return hello;
}
}

View File

@ -0,0 +1,55 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package testpkg;
import java.rmi.server.UnicastRemoteObject;
import clientpkg.Client;
import serverpkg.Hello;
import serverpkg.Server;
public class DummyApp {
public static void main(String args[]) {
try {
Hello obj = new Server();
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
Client client = new Client(stub);
String testStubReturn = client.testStub();
System.out.println("Stub is: " + testStubReturn);
if (!testStubReturn.equals(obj.sayHello())) {
throw new RuntimeException("Unexpected string from stub call, expected \""
+ testStubReturn + "\", actual \"" + obj.sayHello() + "\"");
} else {
System.out.println("Test passed");
}
System.exit(0);
} catch (Throwable e) {
e.printStackTrace();
System.exit(-1);
}
}
}

View File

@ -0,0 +1,88 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4136620 4144590
@summary Make sure that Attribute & subclasses are serialized and deserialized correctly
@modules java.desktop
*/
import java.text.AttributedCharacterIterator.Attribute;
import java.awt.font.TextAttribute;
import java.io.*;
public class ReadResolve {
public static void main(String[] args) throws Exception {
testSerializationCycle(Attribute.LANGUAGE);
testSerializationCycle(TextAttribute.INPUT_METHOD_HIGHLIGHT);
boolean gotException = false;
Attribute result = null;
try {
result = doSerializationCycle(FakeAttribute.LANGUAGE);
} catch (Throwable e) {
gotException = true;
}
if (!gotException) {
throw new RuntimeException("Attribute should throw an exception when given a fake \"language\" attribute. Deserialized object: " + result);
}
}
static Attribute doSerializationCycle(Attribute attribute) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(attribute);
oos.flush();
byte[] data = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ObjectInputStream ois = new ObjectInputStream(bais);
Attribute result = (Attribute) ois.readObject();
return result;
}
static void testSerializationCycle(Attribute attribute) throws Exception {
Attribute result = doSerializationCycle(attribute);
if (result != attribute) {
throw new RuntimeException("attribute changed identity during serialization/deserialization");
}
}
private static class FakeAttribute extends Attribute {
// This LANGUAGE attribute should never be confused with the
// Attribute.LANGUAGE attribute. However, we don't override
// readResolve here, so that deserialization goes
// to Attribute. Attribute has to catch this problem and reject
// the fake attribute.
static final FakeAttribute LANGUAGE = new FakeAttribute("language");
FakeAttribute(String name) {
super(name);
}
}
}

View File

@ -0,0 +1,258 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4139771
* @summary test all aspects of AttributedString class
*/
import java.text.Annotation;
import java.text.AttributedCharacterIterator;
import java.text.AttributedCharacterIterator.Attribute;
import java.text.AttributedString;
import java.text.CharacterIterator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class AttributedStringTest {
private static final String text = "Hello, world!";
private static final Annotation hi = new Annotation("hi");
private static final int[] array5_13 = {5, 13};
private static final int[] array3_9_13 = {3, 9, 13};
private static final int[] array5_9_13 = {5, 9, 13};
private static final int[] array3_5_9_13 = {3, 5, 9, 13};
private static final Attribute[] arrayLanguage = {Attribute.LANGUAGE};
private static final Attribute[] arrayLanguageReading = {Attribute.LANGUAGE, Attribute.READING};
private static final Set setLanguageReading = new HashSet();
static {
setLanguageReading.add(Attribute.LANGUAGE);
setLanguageReading.add(Attribute.READING);
}
public static final void main(String argv[]) throws Exception {
AttributedString string;
AttributedCharacterIterator iterator;
// create a string with text, but no attributes
string = new AttributedString(text);
iterator = string.getIterator();
// make sure the text is there and attributes aren't
checkIteratorText(iterator, text);
if (!iterator.getAllAttributeKeys().isEmpty()) {
throwException(iterator, "iterator provides attributes where none are defined");
}
// add an attribute to a subrange
string.addAttribute(Attribute.LANGUAGE, Locale.ENGLISH, 3, 9);
iterator = string.getIterator();
// make sure the attribute is defined, and it's on the correct subrange
checkIteratorAttributeKeys(iterator, arrayLanguage);
checkIteratorSubranges(iterator, array3_9_13);
checkIteratorAttribute(iterator, 0, Attribute.LANGUAGE, null);
checkIteratorAttribute(iterator, 3, Attribute.LANGUAGE, Locale.ENGLISH);
checkIteratorAttribute(iterator, 9, Attribute.LANGUAGE, null);
// add an attribute to a subrange
string.addAttribute(Attribute.READING, hi, 0, 5);
iterator = string.getIterator();
// make sure the attribute is defined, and it's on the correct subrange
checkIteratorAttributeKeys(iterator, arrayLanguageReading);
checkIteratorSubranges(iterator, array3_5_9_13);
checkIteratorAttribute(iterator, 0, Attribute.READING, hi);
checkIteratorAttribute(iterator, 3, Attribute.READING, hi);
checkIteratorAttribute(iterator, 5, Attribute.READING, null);
checkIteratorAttribute(iterator, 9, Attribute.READING, null);
// make sure the first attribute wasn't adversely affected
// in particular, we shouldn't see separate subranges (3,5) and (5,9).
checkIteratorSubranges(iterator, Attribute.LANGUAGE, array3_9_13);
checkIteratorAttribute(iterator, 0, Attribute.LANGUAGE, null);
checkIteratorAttribute(iterator, 3, Attribute.LANGUAGE, Locale.ENGLISH);
checkIteratorAttribute(iterator, 5, Attribute.LANGUAGE, Locale.ENGLISH);
checkIteratorAttribute(iterator, 9, Attribute.LANGUAGE, null);
// for the entire set of attributes, we expect four subranges
checkIteratorSubranges(iterator, setLanguageReading, array3_5_9_13);
// redefine the language attribute so that both language and reading are continuous from 0 to 5
string.addAttribute(Attribute.LANGUAGE, Locale.US, 0, 5);
iterator = string.getIterator();
// make sure attributes got changed and merged correctly
checkIteratorAttributeKeys(iterator, arrayLanguageReading);
checkIteratorSubranges(iterator, array3_5_9_13);
checkIteratorSubranges(iterator, Attribute.LANGUAGE, array5_9_13);
checkIteratorSubranges(iterator, Attribute.READING, array5_13);
checkIteratorSubranges(iterator, setLanguageReading, array5_9_13);
checkIteratorAttribute(iterator, 0, Attribute.LANGUAGE, Locale.US);
checkIteratorAttribute(iterator, 3, Attribute.LANGUAGE, Locale.US);
checkIteratorAttribute(iterator, 5, Attribute.LANGUAGE, Locale.ENGLISH);
checkIteratorAttribute(iterator, 9, Attribute.LANGUAGE, null);
// make sure an annotation is only returned if its range is contained in the iterator's range
iterator = string.getIterator(null, 3, 5);
checkIteratorAttribute(iterator, 3, Attribute.READING, null);
checkIteratorAttribute(iterator, 5, Attribute.READING, null);
iterator = string.getIterator(null, 0, 4);
checkIteratorAttribute(iterator, 0, Attribute.READING, null);
checkIteratorAttribute(iterator, 3, Attribute.READING, null);
iterator = string.getIterator(null, 0, 5);
checkIteratorAttribute(iterator, 0, Attribute.READING, hi);
checkIteratorAttribute(iterator, 4, Attribute.READING, hi);
checkIteratorAttribute(iterator, 5, Attribute.READING, null);
}
private static final void checkIteratorText(AttributedCharacterIterator iterator, String expectedText) throws Exception {
if (iterator.getEndIndex() - iterator.getBeginIndex() != expectedText.length()) {
throwException(iterator, "text length doesn't match between original text and iterator");
}
char c = iterator.first();
for (int i = 0; i < expectedText.length(); i++) {
if (c != expectedText.charAt(i)) {
throwException(iterator, "text content doesn't match between original text and iterator");
}
c = iterator.next();
}
if (c != CharacterIterator.DONE) {
throwException(iterator, "iterator text doesn't end with DONE");
}
}
private static final void checkIteratorAttributeKeys(AttributedCharacterIterator iterator, Attribute[] expectedKeys) throws Exception {
Set iteratorKeys = iterator.getAllAttributeKeys();
if (iteratorKeys.size() != expectedKeys.length) {
throwException(iterator, "number of keys returned by iterator doesn't match expectation");
}
for (int i = 0; i < expectedKeys.length; i++) {
if (!iteratorKeys.contains(expectedKeys[i])) {
throwException(iterator, "expected key wasn't found in iterator's key set");
}
}
}
private static final void checkIteratorSubranges(AttributedCharacterIterator iterator, int[] expectedLimits) throws Exception {
int previous = 0;
char c = iterator.first();
for (int i = 0; i < expectedLimits.length; i++) {
if (iterator.getRunStart() != previous || iterator.getRunLimit() != expectedLimits[i]) {
throwException(iterator, "run boundaries are not as expected: " + iterator.getRunStart() + ", " + iterator.getRunLimit());
}
previous = expectedLimits[i];
c = iterator.setIndex(previous);
}
if (c != CharacterIterator.DONE) {
throwException(iterator, "iterator's run sequence doesn't end with DONE");
}
}
private static final void checkIteratorSubranges(AttributedCharacterIterator iterator, Attribute key, int[] expectedLimits) throws Exception {
int previous = 0;
char c = iterator.first();
for (int i = 0; i < expectedLimits.length; i++) {
if (iterator.getRunStart(key) != previous || iterator.getRunLimit(key) != expectedLimits[i]) {
throwException(iterator, "run boundaries are not as expected: " + iterator.getRunStart(key) + ", " + iterator.getRunLimit(key) + " for key " + key);
}
previous = expectedLimits[i];
c = iterator.setIndex(previous);
}
if (c != CharacterIterator.DONE) {
throwException(iterator, "iterator's run sequence doesn't end with DONE");
}
}
private static final void checkIteratorSubranges(AttributedCharacterIterator iterator, Set keys, int[] expectedLimits) throws Exception {
int previous = 0;
char c = iterator.first();
for (int i = 0; i < expectedLimits.length; i++) {
if (iterator.getRunStart(keys) != previous || iterator.getRunLimit(keys) != expectedLimits[i]) {
throwException(iterator, "run boundaries are not as expected: " + iterator.getRunStart(keys) + ", " + iterator.getRunLimit(keys) + " for keys " + keys);
}
previous = expectedLimits[i];
c = iterator.setIndex(previous);
}
if (c != CharacterIterator.DONE) {
throwException(iterator, "iterator's run sequence doesn't end with DONE");
}
}
private static final void checkIteratorAttribute(AttributedCharacterIterator iterator, int index, Attribute key, Object expectedValue) throws Exception {
iterator.setIndex(index);
Object value = iterator.getAttribute(key);
if (!((expectedValue == null && value == null) || (expectedValue != null && expectedValue.equals(value)))) {
throwException(iterator, "iterator returns wrong attribute value - " + value + " instead of " + expectedValue);
}
value = iterator.getAttributes().get(key);
if (!((expectedValue == null && value == null) || (expectedValue != null && expectedValue.equals(value)))) {
throwException(iterator, "iterator's map returns wrong attribute value - " + value + " instead of " + expectedValue);
}
}
private static final void throwException(AttributedCharacterIterator iterator, String details) throws Exception {
dumpIterator(iterator);
throw new Exception(details);
}
private static final void dumpIterator(AttributedCharacterIterator iterator) {
Set attributeKeys = iterator.getAllAttributeKeys();
System.out.print("All attributes: ");
Iterator keyIterator = attributeKeys.iterator();
while (keyIterator.hasNext()) {
Attribute key = (Attribute) keyIterator.next();
System.out.print(key);
}
for(char c = iterator.first(); c != CharacterIterator.DONE; c = iterator.next()) {
if (iterator.getIndex() == iterator.getBeginIndex() ||
iterator.getIndex() == iterator.getRunStart()) {
System.out.println();
Map attributes = iterator.getAttributes();
Set entries = attributes.entrySet();
Iterator attributeIterator = entries.iterator();
while (attributeIterator.hasNext()) {
Map.Entry entry = (Map.Entry) attributeIterator.next();
System.out.print("<" + entry.getKey() + ": "
+ entry.getValue() + ">");
}
}
System.out.print(" ");
System.out.print(c);
}
System.out.println();
System.out.println("done");
System.out.println();
}
}

View File

@ -0,0 +1,55 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4146853
* @summary Make sure we can construct an AttributedString from
* an AttributedCharacterIterator covering only a subrange
* @modules java.desktop
*/
import java.awt.font.TextAttribute;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.Hashtable;
public class TestAttributedStringCtor {
public static void main(String[] args) {
// Create a new AttributedString with one attribute.
Hashtable attributes = new Hashtable();
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
AttributedString origString = new AttributedString("Hello world.", attributes);
// Create an iterator over part of the AttributedString.
AttributedCharacterIterator iter = origString.getIterator(null, 4, 6);
// Attempt to create a new AttributedString from the iterator.
// This will throw IllegalArgumentException.
AttributedString newString = new AttributedString(iter);
// Without the exception this would get executed.
System.out.println("DONE");
}
}

View File

@ -0,0 +1,116 @@
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4151160
* @summary Make sure to return correct run start and limit values
* when the iterator has been created with begin and end index values.
* @modules java.desktop
*/
import java.awt.font.TextAttribute;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.text.Annotation;
public class getRunStartLimitTest {
public static void main(String[] args) throws Exception {
String text = "Hello world";
AttributedString as = new AttributedString(text);
// add non-Annotation attributes
as.addAttribute(TextAttribute.WEIGHT,
TextAttribute.WEIGHT_LIGHT,
0,
3);
as.addAttribute(TextAttribute.WEIGHT,
TextAttribute.WEIGHT_BOLD,
3,
5);
as.addAttribute(TextAttribute.WEIGHT,
TextAttribute.WEIGHT_EXTRABOLD,
5,
text.length());
// add Annotation attributes
as.addAttribute(TextAttribute.WIDTH,
new Annotation(TextAttribute.WIDTH_EXTENDED),
0,
3);
as.addAttribute(TextAttribute.WIDTH,
new Annotation(TextAttribute.WIDTH_CONDENSED),
3,
4);
AttributedCharacterIterator aci = as.getIterator(null, 2, 4);
aci.first();
int runStart = aci.getRunStart();
if (runStart != 2) {
throw new Exception("1st run start is wrong. ("+runStart+" should be 2.)");
}
int runLimit = aci.getRunLimit();
if (runLimit != 3) {
throw new Exception("1st run limit is wrong. ("+runLimit+" should be 3.)");
}
Object value = aci.getAttribute(TextAttribute.WEIGHT);
if (value != TextAttribute.WEIGHT_LIGHT) {
throw new Exception("1st run attribute is wrong. ("
+value+" should be "+TextAttribute.WEIGHT_LIGHT+".)");
}
value = aci.getAttribute(TextAttribute.WIDTH);
if (value != null) {
throw new Exception("1st run annotation is wrong. ("
+value+" should be null.)");
}
aci.setIndex(runLimit);
runStart = aci.getRunStart();
if (runStart != 3) {
throw new Exception("2nd run start is wrong. ("+runStart+" should be 3.)");
}
runLimit = aci.getRunLimit();
if (runLimit != 4) {
throw new Exception("2nd run limit is wrong. ("+runLimit+" should be 4.)");
}
value = aci.getAttribute(TextAttribute.WEIGHT);
if (value != TextAttribute.WEIGHT_BOLD) {
throw new Exception("2nd run attribute is wrong. ("
+value+" should be "+TextAttribute.WEIGHT_BOLD+".)");
}
value = aci.getAttribute(TextAttribute.WIDTH);
if (!(value instanceof Annotation)
|| (((Annotation)value).getValue() != TextAttribute.WIDTH_CONDENSED)) {
throw new Exception("2nd run annotation is wrong. (" + value + " should be "
+ new Annotation(TextAttribute.WIDTH_CONDENSED)+".)");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,261 @@
/*
* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4533872 4640853
* @library /java/text/testlib
* @summary Unit tests for supplementary character support (JSR-204) and Unicode 4.0 support
*/
import java.text.BreakIterator;
import java.util.Locale;
public class Bug4533872 extends IntlTest {
public static void main(String[] args) throws Exception {
new Bug4533872().run(args);
}
static final String[] given = {
/* Lu Nd Lu Ll */
"XYZ12345 ABCDE abcde",
/* Nd Lo Nd Lu Po Lu Ll */
"123\uD800\uDC00345 ABC\uFF61XYZ abc",
/* Nd Lo Nd Lu Po Lu Ll */
"123\uD800\uDC00345 ABC\uD800\uDD00XYZ abc",
/* Lu Ll Cs Ll Cs Lu Lo Lu */
"ABCabc\uDC00xyz\uD800ABC\uD800\uDC00XYZ",
};
// Golden data for TestNext(), TestBoundar() and TestPrintEach*ward()
static final String[][] expected = {
{"XYZ12345", " ", "ABCDE", " ", "abcde"},
{"123\uD800\uDC00345", " ", "ABC", "\uFF61", "XYZ", " ", "abc"},
{"123\uD800\uDC00345", " ", "ABC", "\uD800\uDD00", "XYZ", " ", "abc"},
{"ABCabc", "\uDC00", "xyz", "\uD800", "ABC\uD800\uDC00XYZ"},
};
BreakIterator iter;
int start, end, current;
/*
* Test for next(int n)
*/
void TestNext() {
iter = BreakIterator.getWordInstance(Locale.US);
for (int i = 0; i < given.length; i++) {
iter.setText(given[i]);
start = iter.first();
int j = expected[i].length - 1;
start = iter.next(j);
end = iter.next();
if (!expected[i][j].equals(given[i].substring(start, end))) {
errln("Word break failure: printEachForward() expected:<" +
expected[i][j] + ">, got:<" +
given[i].substring(start, end) +
"> start=" + start + " end=" + end);
}
}
}
/*
* Test for isBoundary(int n)
*/
void TestIsBoundary() {
iter = BreakIterator.getWordInstance(Locale.US);
for (int i = 0; i < given.length; i++) {
iter.setText(given[i]);
start = iter.first();
end = iter.next();
while (end < given[i].length()) {
if (!iter.isBoundary(end)) {
errln("Word break failure: isBoundary() This should be a boundary. Index=" +
end + " for " + given[i]);
}
end = iter.next();
}
}
}
/*
* The followig test cases were made based on examples in BreakIterator's
* API Doc.
*/
/*
* Test mainly for next() and current()
*/
void TestPrintEachForward() {
iter = BreakIterator.getWordInstance(Locale.US);
for (int i = 0; i < given.length; i++) {
iter.setText(given[i]);
start = iter.first();
// Check current()'s return value - should be same as first()'s.
current = iter.current();
if (start != current) {
errln("Word break failure: printEachForward() Unexpected current value: current()=" +
current + ", expected(=first())=" + start);
}
int j = 0;
for (end = iter.next();
end != BreakIterator.DONE;
start = end, end = iter.next(), j++) {
// Check current()'s return value - should be same as next()'s.
current = iter.current();
if (end != current) {
errln("Word break failure: printEachForward() Unexpected current value: current()=" +
current + ", expected(=next())=" + end);
}
if (!expected[i][j].equals(given[i].substring(start, end))) {
errln("Word break failure: printEachForward() expected:<" +
expected[i][j] + ">, got:<" +
given[i].substring(start, end) +
"> start=" + start + " end=" + end);
}
}
}
}
/*
* Test mainly for previous() and current()
*/
void TestPrintEachBackward() {
iter = BreakIterator.getWordInstance(Locale.US);
for (int i = 0; i < given.length; i++) {
iter.setText(given[i]);
end = iter.last();
// Check current()'s return value - should be same as last()'s.
current = iter.current();
if (end != current) {
errln("Word break failure: printEachBackward() Unexpected current value: current()=" +
current + ", expected(=last())=" + end);
}
int j;
for (start = iter.previous(), j = expected[i].length-1;
start != BreakIterator.DONE;
end = start, start = iter.previous(), j--) {
// Check current()'s return value - should be same as previous()'s.
current = iter.current();
if (start != current) {
errln("Word break failure: printEachBackward() Unexpected current value: current()=" +
current + ", expected(=previous())=" + start);
}
if (!expected[i][j].equals(given[i].substring(start, end))) {
errln("Word break failure: printEachBackward() expected:<" +
expected[i][j] + ">, got:<" +
given[i].substring(start, end) +
"> start=" + start + " end=" + end);
}
}
}
}
/*
* Test mainly for following() and previous()
*/
void TestPrintAt_1() {
iter = BreakIterator.getWordInstance(Locale.US);
int[][] index = {
{2, 8, 10, 15, 17},
{1, 8, 10, 12, 15, 17, 20},
{3, 8, 10, 13, 16, 18, 20},
{4, 6, 9, 10, 16},
};
for (int i = 0; i < given.length; i++) {
iter.setText(given[i]);
for (int j = index[i].length-1; j >= 0; j--) {
end = iter.following(index[i][j]);
start = iter.previous();
if (!expected[i][j].equals(given[i].substring(start, end))) {
errln("Word break failure: printAt_1() expected:<" +
expected[i][j] + ">, got:<" +
given[i].substring(start, end) +
"> start=" + start + " end=" + end);
}
}
}
}
/*
* Test mainly for preceding() and next()
*/
void TestPrintAt_2() {
iter = BreakIterator.getWordInstance(Locale.US);
int[][] index = {
{2, 9, 10, 15, 17},
{1, 9, 10, 13, 16, 18, 20},
{4, 9, 10, 13, 16, 18, 20},
{6, 7, 10, 11, 15},
};
for (int i = 0; i < given.length; i++) {
iter.setText(given[i]);
// Check preceding(0)'s return value - should equals BreakIterator.DONE.
if (iter.preceding(0) != BreakIterator.DONE) {
errln("Word break failure: printAt_2() expected:-1(BreakIterator.DONE), got:" +
iter.preceding(0));
}
for (int j = 0; j < index[i].length; j++) {
start = iter.preceding(index[i][j]);
end = iter.next();
if (!expected[i][j].equals(given[i].substring(start, end))) {
errln("Word break failure: printAt_2() expected:<" +
expected[i][j] + ">, got:<" +
given[i].substring(start, end) +
"> start=" + start + " end=" + end);
}
}
// Check next()'s return value - should equals BreakIterator.DONE.
end = iter.last();
start = iter.next();
if (start != BreakIterator.DONE) {
errln("Word break failure: printAt_2() expected:-1(BreakIterator.DONE), got:" + start);
}
}
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4740757
* @summary Confirm line-breaking behavior of Hangul
*/
import java.text.*;
import java.util.*;
public class Bug4740757 {
private static boolean err = false;
public static void main(String[] args) {
Locale defaultLocale = Locale.getDefault();
if (defaultLocale.getLanguage().equals("th")) {
Locale.setDefault(Locale.KOREA);
test4740757();
Locale.setDefault(defaultLocale);
} else {
test4740757();
}
if (err) {
throw new RuntimeException("Incorrect Line-breaking");
}
}
private static void test4740757() {
String source = "\uc548\ub155\ud558\uc138\uc694? \uc88b\uc740 \uc544\uce68, \uc5ec\ubcf4\uc138\uc694! \uc548\ub155. End.";
String expected = "\uc548/\ub155/\ud558/\uc138/\uc694? /\uc88b/\uc740 /\uc544/\uce68, /\uc5ec/\ubcf4/\uc138/\uc694! /\uc548/\ub155. /End./";
BreakIterator bi = BreakIterator.getLineInstance(Locale.KOREAN);
bi.setText(source);
int start = bi.first();
int end = bi.next();
StringBuilder sb = new StringBuilder();
for (; end != BreakIterator.DONE; start = end, end = bi.next()) {
sb.append(source.substring(start,end));
sb.append('/');
}
if (!expected.equals(sb.toString())) {
System.err.println("Failed: Hangul line-breaking failed." +
"\n\tExpected: " + expected +
"\n\tGot: " + sb +
"\nin " + Locale.getDefault() + " locale.");
err = true;
}
}
}

View File

@ -0,0 +1,41 @@
/*
* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4912404
* @summary Confirm that BreakIterator.equals(null) return false.
*/
import java.text.BreakIterator;
public class Bug4912404 {
public static void main(String[] args) {
BreakIterator b = BreakIterator.getWordInstance();
b.setText("abc");
if (b.equals(null)) {
throw new RuntimeException("BreakIterator.equals(null) should return false.");
}
}
}

View File

@ -0,0 +1,41 @@
/*
* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
* 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
* @run main/timeout=60 Bug4932583
* @bug 4932583
* @summary Confirm that BreakIterator doesn't get caught in an infinite loop.
*/
import java.text.*;
import java.util.*;
import java.io.*;
public class Bug4932583 {
public static void main(String[] args) {
BreakIterator iterator = BreakIterator.getCharacterInstance();
iterator.setText("\uDB40\uDFFF");
int boundary = iterator.next();
}
}

View File

@ -0,0 +1,122 @@
/*
* Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6513074
* @summary Confirm that JIS X 0213 characters are processed in line-breaking properly.
*/
import java.text.*;
import java.util.*;
public class Bug6513074 {
private static final String[][] source = {
{"\ufa30\ufa31 \ufa69\ufa6a",
"JIS X 0213 compatibility additions (\\uFA30-\\uFA6A)"},
};
private static final String[] expected_line = {
"\ufa30/\ufa31 /\ufa69/\ufa6a/",
};
private static final String[] expected_word = {
"\ufa30\ufa31/ /\ufa69\ufa6a/",
};
private static final String[] expected_char = {
"\ufa30/\ufa31/ /\ufa69/\ufa6a/",
};
private static boolean err = false;
public static void main(String[] args) {
Locale defaultLocale = Locale.getDefault();
if (defaultLocale.getLanguage().equals("th")) {
Locale.setDefault(Locale.JAPAN);
test6513074();
Locale.setDefault(defaultLocale);
} else {
test6513074();
}
if (err) {
throw new RuntimeException("Failed: Incorrect Text-breaking.");
}
}
private static void test6513074() {
BreakIterator bi = BreakIterator.getLineInstance(Locale.JAPAN);
for (int i = 0; i < source.length; i++) {
testBreakIterator(bi, "Line", source[i][0], expected_line[i], source[i][1]);
}
bi = BreakIterator.getWordInstance(Locale.JAPAN);
for (int i = 0; i < source.length; i++) {
testBreakIterator(bi, "Word", source[i][0], expected_word[i], source[i][1]);
}
bi = BreakIterator.getCharacterInstance(Locale.JAPAN);
for (int i = 0; i < source.length; i++) {
testBreakIterator(bi, "Character", source[i][0], expected_char[i], source[i][1]);
}
}
private static void testBreakIterator(BreakIterator bi,
String type,
String source,
String expected,
String description) {
bi.setText(source);
int start = bi.first();
int end = bi.next();
StringBuilder sb = new StringBuilder();
for (; end != BreakIterator.DONE; start = end, end = bi.next()) {
sb.append(source.substring(start,end));
sb.append('/');
}
if (!expected.equals(sb.toString())) {
System.err.println("Failed: Incorrect " + type + "-breaking for " +
description +
"\n\tExpected: " + toString(expected) +
"\n\tGot: " + toString(sb.toString()));
err = true;
}
}
private static String toString(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
sb.append(" 0x" + Integer.toHexString(s.charAt(i)));
}
return sb.toString();
}
}

View File

@ -0,0 +1,86 @@
/*
* Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
* 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
@summary test Comparison of New Collators against Old Collators in the en_US locale
*/
import java.io.*;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Locale;
import java.text.BreakIterator;
import java.lang.Math;
public class NewVSOld_th_TH {
public static void main(String args[]) throws FileNotFoundException,
UnsupportedEncodingException,
IOException {
final String ENCODING = "UTF-8";
final Locale THAI_LOCALE = new Locale("th", "TH");
String rawFileName = "test_th_TH.txt";
String oldFileName = "broken_th_TH.txt";
StringBuilder rawText = new StringBuilder();
StringBuilder oldText = new StringBuilder();
StringBuilder cookedText = new StringBuilder();
File f;
f = new File(System.getProperty("test.src", "."), rawFileName);
try (InputStreamReader rawReader =
new InputStreamReader(new FileInputStream(f), ENCODING)) {
int c;
while ((c = rawReader.read()) != -1) {
rawText.append((char) c);
}
}
f = new File(System.getProperty("test.src", "."), oldFileName);
try (InputStreamReader oldReader =
new InputStreamReader(new FileInputStream(f), ENCODING)) {
int c;
while ((c = oldReader.read()) != -1) {
oldText.append((char) c);
}
}
BreakIterator breakIterator = BreakIterator.getWordInstance(THAI_LOCALE);
breakIterator.setText(rawText.toString());
int start = breakIterator.first();
for (int end = breakIterator.next();
end != BreakIterator.DONE;
start = end, end = breakIterator.next()) {
cookedText.append(rawText.substring(start, end));
cookedText.append("\n");
}
String cooked = cookedText.toString();
String old = oldText.toString();
if (cooked.compareTo(old) != 0) {
throw new RuntimeException("Text not broken the same as with the old BreakIterators");
}
}
}

View File

@ -0,0 +1,13 @@
การ
เก็บ
ภาษีประเทศ
ไทยและ
ประเทศ
เดนมาร์ค
อนุสัญญา
ระหว่าง
รัฐบาล
แห่ง
ประเทศ
ไทย
กับ

View File

@ -0,0 +1 @@
การเก็บภาษีประเทศไทยและประเทศเดนมาร์คอนุสัญญาระหว่างรัฐบาลแห่งประเทศไทยกับ

View File

@ -0,0 +1,286 @@
/*
* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @library /java/text/testlib
* @summary test for Character Iterator
*/
/*
*
*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* Portions copyright (c) 2007 Sun Microsystems, Inc.
* All Rights Reserved.
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for NON-COMMERCIAL purposes and without
* fee is hereby granted provided that this copyright notice
* appears in all copies. Please refer to the file "copyright.html"
* for further important copyright and licensing information.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
* THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*
*/
import java.text.*;
public class CharacterIteratorTest extends IntlTest {
public static void main(String[] args) throws Exception {
new CharacterIteratorTest().run(args);
}
public CharacterIteratorTest() {
}
public void TestConstructionAndEquality() {
String testText = "Now is the time for all good men to come to the aid of their country.";
String testText2 = "Don't bother using this string.";
CharacterIterator test1 = new StringCharacterIterator(testText);
CharacterIterator test2 = new StringCharacterIterator(testText, 5);
CharacterIterator test3 = new StringCharacterIterator(testText, 2, 20, 5);
CharacterIterator test4 = new StringCharacterIterator(testText2);
CharacterIterator test5 = (CharacterIterator)test1.clone();
if (test1.equals(test2) || test1.equals(test3) || test1.equals(test4))
errln("Construation or equals() failed: Two unequal iterators tested equal");
if (!test1.equals(test5))
errln("clone() or equals() failed: Two clones tested unequal");
if (test1.hashCode() == test2.hashCode() || test1.hashCode() == test3.hashCode()
|| test1.hashCode() == test4.hashCode())
errln("hash() failed: different objects have same hash code");
if (test1.hashCode() != test5.hashCode())
errln("hash() failed: identical objects have different hash codes");
test1.setIndex(5);
if (!test1.equals(test2) || test1.equals(test5))
errln("setIndex() failed");
}
public void TestIteration() {
String text = "Now is the time for all good men to come to the aid of their country.";
CharacterIterator iter = new StringCharacterIterator(text, 5);
if (iter.current() != text.charAt(5))
errln("Iterator didn't start out in the right place.");
char c = iter.first();
int i = 0;
if (iter.getBeginIndex() != 0 || iter.getEndIndex() != text.length())
errln("getBeginIndex() or getEndIndex() failed");
logln("Testing forward iteration...");
do {
if (c == CharacterIterator.DONE && i != text.length())
errln("Iterator reached end prematurely");
else if (c != text.charAt(i))
errln("Character mismatch at position " + i + ", iterator has " + c +
", string has " + text.charAt(c));
if (iter.current() != c)
errln("current() isn't working right");
if (iter.getIndex() != i)
errln("getIndex() isn't working right");
if (c != CharacterIterator.DONE) {
c = iter.next();
i++;
}
} while (c != CharacterIterator.DONE);
c = iter.last();
i = text.length() - 1;
logln("Testing backward iteration...");
do {
if (c == CharacterIterator.DONE && i >= 0)
errln("Iterator reached end prematurely");
else if (c != text.charAt(i))
errln("Character mismatch at position " + i + ", iterator has " + c +
", string has " + text.charAt(c));
if (iter.current() != c)
errln("current() isn't working right");
if (iter.getIndex() != i)
errln("getIndex() isn't working right");
if (c != CharacterIterator.DONE) {
c = iter.previous();
i--;
}
} while (c != CharacterIterator.DONE);
iter = new StringCharacterIterator(text, 5, 15, 10);
if (iter.getBeginIndex() != 5 || iter.getEndIndex() != 15)
errln("creation of a restricted-range iterator failed");
if (iter.getIndex() != 10 || iter.current() != text.charAt(10))
errln("starting the iterator in the middle didn't work");
c = iter.first();
i = 5;
logln("Testing forward iteration over a range...");
do {
if (c == CharacterIterator.DONE && i != 15)
errln("Iterator reached end prematurely");
else if (c != text.charAt(i))
errln("Character mismatch at position " + i + ", iterator has " + c +
", string has " + text.charAt(c));
if (iter.current() != c)
errln("current() isn't working right");
if (iter.getIndex() != i)
errln("getIndex() isn't working right");
if (c != CharacterIterator.DONE) {
c = iter.next();
i++;
}
} while (c != CharacterIterator.DONE);
c = iter.last();
i = 14;
logln("Testing backward iteration over a range...");
do {
if (c == CharacterIterator.DONE && i >= 5)
errln("Iterator reached end prematurely");
else if (c != text.charAt(i))
errln("Character mismatch at position " + i + ", iterator has " + c +
", string has " + text.charAt(c));
if (iter.current() != c)
errln("current() isn't working right");
if (iter.getIndex() != i)
errln("getIndex() isn't working right");
if (c != CharacterIterator.DONE) {
c = iter.previous();
i--;
}
} while (c != CharacterIterator.DONE);
}
/**
* @bug 4082050 4078261 4078255
*/
public void TestPathologicalCases() {
String text = "This is only a test.";
/*
This test is commented out until API-change approval for bug #4082050 goes through.
// test for bug #4082050 (don't get an error if begin == end, even though all
// operations on the iterator will cause exceptions)
// [I actually fixed this so that you CAN create an iterator with begin == end,
// but all operations on it return DONE.]
CharacterIterator iter = new StringCharacterIterator(text, 5, 5, 5);
if (iter.first() != CharacterIterator.DONE
|| iter.next() != CharacterIterator.DONE
|| iter.last() != CharacterIterator.DONE
|| iter.previous() != CharacterIterator.DONE
|| iter.current() != CharacterIterator.DONE
|| iter.getIndex() != 5)
errln("Got something other than DONE when performing operations on an empty StringCharacterIterator");
*/
CharacterIterator iter = null;
// if we try to construct a StringCharacterIterator with an endIndex that's off
// the end of the String under iterator, we're supposed to get an
// IllegalArgumentException
boolean gotException = false;
try {
iter = new StringCharacterIterator(text, 5, 100, 5);
}
catch (IllegalArgumentException e) {
gotException = true;
}
if (!gotException)
errln("StringCharacterIterator didn't throw an exception when given an invalid substring range.");
// test for bug #4078255 (getting wrong value from next() when we're at the end
// of the string)
iter = new StringCharacterIterator(text);
int expectedIndex = iter.getEndIndex();
int actualIndex;
iter.last();
actualIndex = iter.getIndex();
if (actualIndex != expectedIndex - 1)
errln("last() failed: expected " + (expectedIndex - 1) + ", got " + actualIndex);
iter.next();
actualIndex = iter.getIndex();
if (actualIndex != expectedIndex)
errln("next() after last() failed: expected " + expectedIndex + ", got " + actualIndex);
iter.next();
actualIndex = iter.getIndex();
if (actualIndex != expectedIndex)
errln("second next() after last() failed: expected " + expectedIndex + ", got " + actualIndex);
}
/*
* @bug 4123771 4051073
* #4123771 is actually a duplicate of bug #4051073, which was fixed some time ago, but
* no one ever added a regression test for it.
*/
public void TestBug4123771() {
String text = "Some string for testing";
StringCharacterIterator iter = new StringCharacterIterator(text);
int index = iter.getEndIndex();
try {
char c = iter.setIndex(index);
}
catch (Exception e) {
System.out.println("method setIndex(int position) throws unexpected exception " + e);
System.out.println(" position: " + index);
System.out.println(" getEndIndex(): " + iter.getEndIndex());
System.out.println(" text.length(): " + text.length());
errln(""); // re-throw the exception through our test framework
}
}
}

View File

@ -0,0 +1,318 @@
/*
* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @library /java/text/testlib
* @summary test Collation API
*/
/*
(C) Copyright Taligent, Inc. 1996 - All Rights Reserved
(C) Copyright IBM Corp. 1996 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
import java.util.Locale;
import java.text.Collator;
import java.text.RuleBasedCollator;
import java.text.CollationKey;
import java.text.CollationElementIterator;
public class APITest extends CollatorTest {
public static void main(String[] args) throws Exception {
new APITest().run(args);
}
final void doAssert(boolean condition, String message)
{
if (!condition) {
err("ERROR: ");
errln(message);
}
}
public final void TestProperty( )
{
Collator col = null;
try {
col = Collator.getInstance(Locale.ROOT);
logln("The property tests begin : ");
logln("Test ctors : ");
doAssert(col.compare("ab", "abc") < 0, "ab < abc comparison failed");
doAssert(col.compare("ab", "AB") < 0, "ab < AB comparison failed");
doAssert(col.compare("black-bird", "blackbird") > 0, "black-bird > blackbird comparison failed");
doAssert(col.compare("black bird", "black-bird") < 0, "black bird < black-bird comparison failed");
doAssert(col.compare("Hello", "hello") > 0, "Hello > hello comparison failed");
logln("Test ctors ends.");
logln("testing Collator.getStrength() method ...");
doAssert(col.getStrength() == Collator.TERTIARY, "collation object has the wrong strength");
doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference");
logln("testing Collator.setStrength() method ...");
col.setStrength(Collator.SECONDARY);
doAssert(col.getStrength() != Collator.TERTIARY, "collation object's strength is secondary difference");
doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference");
doAssert(col.getStrength() == Collator.SECONDARY, "collation object has the wrong strength");
logln("testing Collator.setDecomposition() method ...");
col.setDecomposition(Collator.NO_DECOMPOSITION);
doAssert(col.getDecomposition() != Collator.FULL_DECOMPOSITION, "collation object's strength is secondary difference");
doAssert(col.getDecomposition() != Collator.CANONICAL_DECOMPOSITION, "collation object's strength is primary difference");
doAssert(col.getDecomposition() == Collator.NO_DECOMPOSITION, "collation object has the wrong strength");
} catch (Exception foo) {
errln("Error : " + foo.getMessage());
errln("Default Collator creation failed.");
}
logln("Default collation property test ended.");
logln("Collator.getRules() testing ...");
doAssert(((RuleBasedCollator)col).getRules().length() != 0, "getRules() result incorrect" );
logln("getRules tests end.");
try {
col = Collator.getInstance(Locale.FRENCH);
col.setStrength(Collator.PRIMARY);
logln("testing Collator.getStrength() method again ...");
doAssert(col.getStrength() != Collator.TERTIARY, "collation object has the wrong strength");
doAssert(col.getStrength() == Collator.PRIMARY, "collation object's strength is not primary difference");
logln("testing French Collator.setStrength() method ...");
col.setStrength(Collator.TERTIARY);
doAssert(col.getStrength() == Collator.TERTIARY, "collation object's strength is not tertiary difference");
doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference");
doAssert(col.getStrength() != Collator.SECONDARY, "collation object's strength is secondary difference");
} catch (Exception bar) {
errln("Error : " + bar.getMessage());
errln("Creating French collation failed.");
}
logln("Create junk collation: ");
Locale abcd = new Locale("ab", "CD", "");
Collator junk = null;
try {
junk = Collator.getInstance(abcd);
} catch (Exception err) {
errln("Error : " + err.getMessage());
errln("Junk collation creation failed, should at least return the collator for the base bundle.");
}
try {
col = Collator.getInstance(Locale.ROOT);
doAssert(col.equals(junk), "The base bundle's collation should be returned.");
} catch (Exception exc) {
errln("Error : " + exc.getMessage());
errln("Default collation comparison, caching not working.");
}
logln("Collator property test ended.");
}
public final void TestHashCode( )
{
logln("hashCode tests begin.");
Collator col1 = null;
try {
col1 = Collator.getInstance(Locale.ROOT);
} catch (Exception foo) {
errln("Error : " + foo.getMessage());
errln("Default collation creation failed.");
}
Collator col2 = null;
Locale dk = new Locale("da", "DK", "");
try {
col2 = Collator.getInstance(dk);
} catch (Exception bar) {
errln("Error : " + bar.getMessage());
errln("Danish collation creation failed.");
return;
}
Collator col3 = null;
try {
col3 = Collator.getInstance(Locale.ROOT);
} catch (Exception err) {
errln("Error : " + err.getMessage());
errln("2nd default collation creation failed.");
}
logln("Collator.hashCode() testing ...");
if (col1 != null) {
doAssert(col1.hashCode() != col2.hashCode(), "Hash test1 result incorrect");
if (col3 != null) {
doAssert(col1.hashCode() == col3.hashCode(), "Hash result not equal");
}
}
logln("hashCode tests end.");
}
//----------------------------------------------------------------------------
// ctor -- Tests the constructor methods
//
public final void TestCollationKey( )
{
logln("testing CollationKey begins...");
Collator col = null;
try {
col = Collator.getInstance(Locale.ROOT);
} catch (Exception foo) {
errln("Error : " + foo.getMessage());
errln("Default collation creation failed.");
}
if (col == null) {
return;
}
String test1 = "Abcda", test2 = "abcda";
logln("Use tertiary comparison level testing ....");
CollationKey sortk1 = col.getCollationKey(test1);
CollationKey sortk2 = col.getCollationKey(test2);
doAssert(sortk1.compareTo(sortk2) > 0,
"Result should be \"Abcda\" >>> \"abcda\"");
CollationKey sortk3 = sortk2;
CollationKey sortkNew = sortk1;
doAssert(sortk1 != sortk2, "The sort keys should be different");
doAssert(sortk1.hashCode() != sortk2.hashCode(), "sort key hashCode() failed");
doAssert(sortk2.compareTo(sortk3) == 0, "The sort keys should be the same");
doAssert(sortk1 == sortkNew, "The sort keys assignment failed");
doAssert(sortk1.hashCode() == sortkNew.hashCode(), "sort key hashCode() failed");
doAssert(sortkNew != sortk3, "The sort keys should be different");
doAssert(sortk1.compareTo(sortk3) > 0, "Result should be \"Abcda\" >>> \"abcda\"");
doAssert(sortk2.compareTo(sortk3) == 0, "Result should be \"abcda\" == \"abcda\"");
long cnt1, cnt2;
byte byteArray1[] = sortk1.toByteArray();
byte byteArray2[] = sortk2.toByteArray();
doAssert(byteArray1 != null && byteArray2 != null, "CollationKey.toByteArray failed.");
logln("testing sortkey ends...");
}
//----------------------------------------------------------------------------
// ctor -- Tests the constructor methods
//
public final void TestElemIter( )
{
logln("testing sortkey begins...");
Collator col = null;
try {
col = Collator.getInstance();
} catch (Exception foo) {
errln("Error : " + foo.getMessage());
errln("Default collation creation failed.");
}
RuleBasedCollator rbCol;
if (col instanceof RuleBasedCollator) {
rbCol = (RuleBasedCollator) col;
} else {
return;
}
String testString1 = "XFILE What subset of all possible test cases has the highest probability of detecting the most errors?";
String testString2 = "Xf ile What subset of all possible test cases has the lowest probability of detecting the least errors?";
logln("Constructors and comparison testing....");
CollationElementIterator iterator1 = rbCol.getCollationElementIterator(testString1);
CollationElementIterator iterator2 = rbCol.getCollationElementIterator(testString1);
CollationElementIterator iterator3 = rbCol.getCollationElementIterator(testString2);
int order1, order2, order3;
order1 = iterator1.next();
order2 = iterator2.next();
doAssert(order1 == order2, "The order result should be the same");
order3 = iterator3.next();
doAssert(CollationElementIterator.primaryOrder(order1)
== CollationElementIterator.primaryOrder(order3),
"The primary orders should be the same");
doAssert(CollationElementIterator.secondaryOrder(order1)
== CollationElementIterator.secondaryOrder(order3),
"The secondary orders should be the same");
doAssert(CollationElementIterator.tertiaryOrder(order1)
== CollationElementIterator.tertiaryOrder(order3),
"The tertiary orders should be the same");
order1 = iterator1.next();
order3 = iterator3.next();
doAssert(CollationElementIterator.primaryOrder(order1)
== CollationElementIterator.primaryOrder(order3),
"The primary orders should be identical");
doAssert(CollationElementIterator.tertiaryOrder(order1)
!= CollationElementIterator.tertiaryOrder(order3),
"The tertiary orders should be different");
order1 = iterator1.next();
order3 = iterator3.next();
doAssert(CollationElementIterator.secondaryOrder(order1)
!= CollationElementIterator.secondaryOrder(order3),
"The secondary orders should be different");
doAssert(order1 != CollationElementIterator.NULLORDER,
"Unexpected end of iterator reached");
iterator1.reset();
iterator2.reset();
iterator3.reset();
order1 = iterator1.next();
order2 = iterator2.next();
doAssert(order1 == order2, "The order result should be the same");
order3 = iterator3.next();
doAssert(CollationElementIterator.primaryOrder(order1)
== CollationElementIterator.primaryOrder(order3),
"The orders should be the same");
doAssert(CollationElementIterator.secondaryOrder(order1)
== CollationElementIterator.secondaryOrder(order3),
"The orders should be the same");
doAssert(CollationElementIterator.tertiaryOrder(order1)
== CollationElementIterator.tertiaryOrder(order3),
"The orders should be the same");
order1 = iterator1.next();
order2 = iterator2.next();
order3 = iterator3.next();
doAssert(CollationElementIterator.primaryOrder(order1)
== CollationElementIterator.primaryOrder(order3),
"The primary orders should be identical");
doAssert(CollationElementIterator.tertiaryOrder(order1)
!= CollationElementIterator.tertiaryOrder(order3),
"The tertiary orders should be different");
order1 = iterator1.next();
order3 = iterator3.next();
doAssert(CollationElementIterator.secondaryOrder(order1)
!= CollationElementIterator.secondaryOrder(order3),
"The secondary orders should be different");
doAssert(order1 != CollationElementIterator.NULLORDER, "Unexpected end of iterator reached");
logln("testing CollationElementIterator ends...");
}
public final void TestGetAll()
{
Locale[] list = Collator.getAvailableLocales();
for (int i = 0; i < list.length; ++i) {
log("Locale name: ");
log(list[i].toString());
log(" , the display name is : ");
logln(list[i].getDisplayName());
}
}
}

View File

@ -0,0 +1,194 @@
/*
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6271411
* @library /java/text/testlib
* @summary Confirm that three JCK testcases for CollationElementIterator pass.
*/
import java.text.*;
/*
* Based on JCK-runtime-15/tests/api/java_text/CollationElementIterator/ColltnElmtIterTests.java.
*/
public class Bug6271411 extends IntlTest {
public static void main(String argv[]) throws Exception {
Bug6271411 test = new Bug6271411();
test.run(argv);
}
/*
* Rule for RuleBasedCollator
*/
static final String rule = "< c, C < d; D";
/*
* Textdata
*/
static final String[] values = {
"", "c", "cH522Yd", "Hi, high school", "abcchCHidD"
};
/*
* Confirm that setOffset() throws IllegalArgumentException
* (not IndexOutOfBoundsException) if the given offset is invalid.
* Use CollationElementIterator.setText(String).
*/
public void Test_CollationElementIterator0007() throws Exception {
int[] offsets = {
Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -10000, -2, -1,
100, 101, // These two are customized for every test data later.
12345, Integer.MAX_VALUE - 1, Integer.MAX_VALUE
};
boolean err = false;
RuleBasedCollator rbc = new RuleBasedCollator(rule);
CollationElementIterator iterator = rbc.getCollationElementIterator("");
for (int i = 0; i < values.length; i++) {
String source = values[i];
iterator.setText(source);
int len = source.length();
offsets[5] = len + 1;
offsets[6] = len + 2;
for (int j = 0; j < offsets.length; j++) {
try {
iterator.setOffset(offsets[j]);
System.out.println("IllegalArgumentException should be thrown for setOffset(" +
offsets[j] + ") for <" + source + ">.");
err = true;
}
catch (IllegalArgumentException e) {
}
}
}
if (err) {
errln("CollationElementIterator.setOffset() didn't throw an expected IllegalArguemntException.");
}
}
/*
* Confirm that setText() doesn't throw an exception and setOffset() throws
* IllegalArgumentException if the given offset is invalid.
* Use CollationElementIterator.setText(CharacterIterator).
*/
public void Test_CollationElementIterator0010() throws Exception {
String prefix = "xyz abc";
String suffix = "1234567890";
int begin = prefix.length();
int[] offsets = {
Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -10000,
-2, -1, 0, 1, begin - 2, begin - 1, 9, 10, 11, 12, 13, 14,
15, 12345, Integer.MAX_VALUE - 1, Integer.MAX_VALUE
};
boolean err = false;
RuleBasedCollator rbc = new RuleBasedCollator(rule);
CollationElementIterator iterator = rbc.getCollationElementIterator("");
for (int i = 0; i < values.length; i++) {
String str = prefix + values[i] + suffix;
int len = str.length();
int end = len - suffix.length();
CharacterIterator source =
new StringCharacterIterator(str, begin, end, begin);
iterator.setText(source);
offsets[9] = end + 1;
offsets[10] = end + 2;
offsets[11] = (end + len) / 2;
offsets[12] = len - 1;
offsets[13] = len;
offsets[14] = len + 1;
offsets[15] = len + 2;
for (int j = 0; j < offsets.length; j++) {
try {
iterator.setOffset(offsets[j]);
System.out.println("IllegalArgumentException should be thrown for setOffset(" +
offsets[j] + ") for <" + str + ">.");
err = true;
}
catch (IllegalArgumentException e) {
}
}
}
if (err) {
errln("CollationElementIterator.setOffset() didn't throw an expected IllegalArguemntException.");
}
}
/*
* Confirm that setText() doesn't throw an exception and setOffset() sets
* an offset as expected.
* Use CollationElementIterator.setText(CharacterIterator).
*/
public void Test_CollationElementIterator0011() throws Exception {
String prefix = "xyz abc";
String suffix = "1234567890";
int begin = prefix.length();
int[] offsets = { begin, begin + 1, 2, 3, 4 };
RuleBasedCollator rbc = new RuleBasedCollator(rule);
CollationElementIterator iterator = rbc.getCollationElementIterator("");
for (int i = 0; i < values.length; i++) {
String str = prefix + values[i] + suffix;
int len = str.length();
int end = len - suffix.length();
CharacterIterator source =
new StringCharacterIterator(str, begin, end, begin);
iterator.setText(source);
offsets[2] = (end + len) / 2;
offsets[3] = len - 1;
offsets[4] = len;
for (int j = 0; j < offsets.length; j++) {
int offset = offsets[j];
if (offset < begin || offset > end) {
break;
}
iterator.setOffset(offset);
int newOffset = iterator.getOffset();
if (newOffset != offset) {
throw new RuntimeException("setOffset() didn't set a correct offset. Got: " +
newOffset + " Expected: " + offset + " for <" + str + ">.");
}
}
}
}
}

View File

@ -0,0 +1,41 @@
/*
* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4106263
* @summary Tests on the bug 4106263 - CollationKey became non-final extendable class.
* The implementation of CollationKey is moved to the new private class,
* RuleBasedCollationKey. This test basically tests on the two features:
* 1. Existing code using CollationKey works (backward compatiblility)
* 2. CollationKey can be extended by its subclass.
*/
public class CollationKeyTest {
public static void main(String[] args) {
CollationKeyTestImpl ck = new CollationKeyTestImpl("Testing the CollationKey");
ck.run();
}
}

View File

@ -0,0 +1,243 @@
/*
* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* 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.
*/
/*
*
* A part of tests on the bug 4106263. CollationKey became non-final extendable class.
* The implementation of CollationKey is moved to the new private class,
* RuleBasedCollationKey. This test basically tests on the two features:
* 1. Existing code using CollationKey works (backward compatiblility)
* 2. CollationKey can be extended by its subclass.
*/
import java.util.Locale;
import java.text.Collator;
import java.text.CollationKey;
import java.io.*;
import java.text.*;
public class CollationKeyTestImpl extends CollationKey {
private static String[] sourceData_ja = {
"\u3042\u3044\u3046\u3048\u3048",
"\u3041\u3043\u3045\u3047\u3049",
"\u3052\u3054\u3056\u3058\u3058",
"\u3051\u3053\u3055\u3057\u3059",
"\u3062\u3064\u3066\u3068\u3068",
"\u3061\u3063\u3065\u3067\u3069",
"\u3072\u3074\u3075\u3078\u3078",
"\u3071\u3073\u3075\u3077\u3079",
"\u3082\u3084\u3085\u3088\u3088",
"\u3081\u3083\u3085\u3087\u3089",
"\u30a2\u30a4\u30a6\u30a8\u30aa",
"\u30a1\u30a3\u30a5\u30a7\u30a9",
"\u30c2\u30c4\u30c6\u30c8\u30ca",
"\u30c1\u30c3\u30c5\u30c7\u30c9",
"\u30b2\u30b4\u30b6\u30b8\u30ba",
"\u30b1\u30b3\u30b5\u30b7\u30b9",
"\u30d2\u30d4\u30d6\u30d8\u30da",
"\u30d1\u30d3\u30d5\u30d7\u30d9",
"\u30e2\u30e4\u30e6\u30e8\u30ea",
"\u30e1\u30e3\u30e5\u30e7\u30e9"
};
private static final String[] targetData_ja = {
"\u3042\u3044\u3046\u3048\u3048",
"\u3041\u3043\u3045\u3047\u3049",
"\u30a2\u30a4\u30a6\u30a8\u30aa",
"\u30a1\u30a3\u30a5\u30a7\u30a9",
"\u3052\u3054\u3056\u3058\u3058",
"\u3051\u3053\u3055\u3057\u3059",
"\u30b1\u30b3\u30b5\u30b7\u30b9",
"\u30b2\u30b4\u30b6\u30b8\u30ba",
"\u3061\u3063\u3065\u3067\u3069",
"\u30c1\u30c3\u30c5\u30c7\u30c9",
"\u3062\u3064\u3066\u3068\u3068",
"\u30c2\u30c4\u30c6\u30c8\u30ca",
"\u3071\u3073\u3075\u3077\u3079",
"\u30d1\u30d3\u30d5\u30d7\u30d9",
"\u3072\u3074\u3075\u3078\u3078",
"\u30d2\u30d4\u30d6\u30d8\u30da",
"\u3081\u3083\u3085\u3087\u3089",
"\u30e1\u30e3\u30e5\u30e7\u30e9",
"\u3082\u3084\u3085\u3088\u3088",
"\u30e2\u30e4\u30e6\u30e8\u30ea"
};
public void run() {
/** debug: printout the test data
for (int i=0; i<sourceData_ja.length; i++){
System.out.println(i+": "+sourceData_ja[i]);
}
**/
/*
* 1. Test the backward compatibility
* note: targetData_ja.length is equal to sourceData_ja.length
*/
Collator myCollator = Collator.getInstance(Locale.JAPAN);
CollationKey[] keys = new CollationKey[sourceData_ja.length];
CollationKey[] target_keys = new CollationKey[targetData_ja.length];
for (int i=0; i<sourceData_ja.length; i++){
keys[i] = myCollator.getCollationKey(sourceData_ja[i]);
target_keys[i] = myCollator.getCollationKey(targetData_ja[i]); //used later
}
/* Sort the string using CollationKey */
InsertionSort(keys);
/** debug: printout the result after sort
System.out.println("--- After Sorting ---");
for (int i=0; i<sourceData_ja.length; i++){
System.out.println(i+" :"+keys[i].getSourceString());
}
**/
/*
* Compare the result using equals method and getSourceString method.
*/
boolean pass = true;
for (int i=0; i<sourceData_ja.length; i++){
/* Comparing using String.equals: in order to use getStringSource() */
if (! targetData_ja[i].equals(keys[i].getSourceString())){
throw new RuntimeException("FAILED: CollationKeyTest backward compatibility "
+"while comparing" +targetData_ja[i]+" vs "
+keys[i].getSourceString());
}
/* Comparing using CollaionKey.equals: in order to use equals() */
if (! target_keys[i].equals(keys[i])){
throw new RuntimeException("FAILED: CollationKeyTest backward compatibility."
+" Using CollationKey.equals " +targetData_ja[i]
+" vs " +keys[i].getSourceString());
}
/* Comparing using CollaionKey.hashCode(): in order to use hashCode() */
if (target_keys[i].hashCode() != keys[i].hashCode()){
throw new RuntimeException("FAILED: CollationKeyTest backward compatibility."
+" Using CollationKey.hashCode " +targetData_ja[i]
+" vs " +keys[i].getSourceString());
}
/* Comparing using CollaionKey.toByteArray(): in order to use toByteArray() */
byte[] target_bytes = target_keys[i].toByteArray();
byte[] source_bytes = keys[i].toByteArray();
for (int j=0; j<target_bytes.length; j++){
Byte targetByte = new Byte(target_bytes[j]);
Byte sourceByte = new Byte(source_bytes[j]);
if (targetByte.compareTo(sourceByte)!=0){
throw new RuntimeException("FAILED: CollationKeyTest backward "
+"compatibility. Using Byte.compareTo from CollationKey.toByteArray "
+targetData_ja[i]
+" vs " +keys[i].getSourceString());
}
}
}
testSubclassMethods();
testConstructor();
}
/*
* Sort the array of CollationKey using compareTo method in insertion sort.
*/
private void InsertionSort(CollationKey[] keys){
int f, i;
CollationKey tmp;
for (f=1; f < keys.length; f++){
if(keys[f].compareTo( keys[f-1]) > 0){
continue;
}
tmp = keys[f];
i = f-1;
while ( (i>=0) && (keys[i].compareTo(tmp) > 0) ) {
keys[i+1] = keys[i];
i--;
}
keys[i+1]=tmp;
}
}
/*
* From here is the bogus methods to test the subclass of
* the CollationKey class.
*/
public CollationKeyTestImpl(String str){
super (str);
// debug: System.out.println("CollationKeyTest extends CollationKey class: "+str);
}
/* abstract method: needs to be implemented */
public byte[] toByteArray(){
String foo= "Hello";
return foo.getBytes();
}
/* abstract method: needs to be implemented */
public int compareTo(CollationKey target){
return 0;
}
public boolean equals(Object target){
return true;
}
public String getSourceString(){
return "CollationKeyTestImpl";
}
/*
* This method tests the collection of bugus methods from the extended
* subclass of CollationKey class.
*/
private void testSubclassMethods() {
CollationKeyTestImpl clt1 = new CollationKeyTestImpl("testSubclassMethods-1");
CollationKeyTestImpl clt2 = new CollationKeyTestImpl("testSubclassMethods-2");
// extended method, equals always returns true
if (!clt1.equals(clt2)){
throw new RuntimeException("Failed: equals(CollationKeySubClass)");
}
// extended method, compareTo always returns 0
if (clt1.compareTo(clt2)!=0){
throw new RuntimeException("Failed: compareTo(CollationKeySubClass)");
}
// overriding extended method, getSourceString always returns "CollationKeyTestImpl"
if (! clt1.getSourceString().equals("CollationKeyTestImpl")){
throw new RuntimeException("Failed: CollationKey subclass overriding getSourceString()");
}
// extended method, toByteArray always returns bytes from "Hello"
String str2 = new String( clt2.toByteArray());
if (! clt2.equals("Hello")){
throw new RuntimeException("Failed: CollationKey subclass toByteArray()");
}
}
/*
* This method tests CollationKey constructor with null source string.
* It should throw NPE.
*/
private void testConstructor() {
boolean npe=false;
try{
CollationKeyTestImpl cltNull = new CollationKeyTestImpl(null);
} catch (NullPointerException npException){
npe=true;
// debug: System.out.println("--- NPE is thrown with NULL arguement: PASS ---");
}
if(!npe){
throw new RuntimeException("Failed: CollationKey Constructor with null source"+
" didn't throw NPE!");
}
}
}

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