This commit is contained in:
J. Duke 2017-07-05 21:16:36 +02:00
commit 0b0724965f
265 changed files with 84780 additions and 2279 deletions

View File

@ -345,3 +345,4 @@ cf1dc4c035fb84693d4ae5ad818785cb4d1465d1 jdk9-b90
c1f30ac14db0eaff398429c04cd9fab92e1b4b2a jdk-9+100
c4d72a1620835b5d657b7b6792c2879367d0154f jdk-9+101
6406ecf5d39482623225bb1b3098c2cac6f7d450 jdk-9+102
47d6462e514b2097663305a57d9c844c15d5b609 jdk-9+103

File diff suppressed because it is too large Load Diff

View File

@ -266,14 +266,3 @@ AC_DEFUN_ONCE([HOTSPOT_SETUP_BUILD_TWEAKS],
HOTSPOT_MAKE_ARGS="$HOTSPOT_TARGET"
AC_SUBST(HOTSPOT_MAKE_ARGS)
])
# -g is already added by ENABLE_DEBUG_SYMBOLS and the hotspot makefiles
# will basically do slowdebug builds when DEBUG_BINARIES is set for
# fastdebug builds
DEBUG_BINARIES=false
# Fastdebug builds with this setting will essentially be slowdebug
# in hotspot.
# -g is already added by ENABLE_DEBUG_SYMBOLS and the hotspot makefiles
# will basically do slowdebug builds when DEBUG_BINARIES is set for
# fastdebug builds
DEBUG_BINARIES=false

View File

@ -144,6 +144,10 @@ AC_DEFUN_ONCE([LIB_SETUP_LLVM],
fi
done
# Due to https://llvm.org/bugs/show_bug.cgi?id=16902, llvm does not
# always properly detect -ltinfo
LLVM_LIBS="${LLVM_LIBS} -ltinfo"
AC_SUBST(LLVM_CFLAGS)
AC_SUBST(LLVM_LDFLAGS)
AC_SUBST(LLVM_LIBS)

View File

@ -500,7 +500,7 @@ JAVAC_FLAGS?=@JAVAC_FLAGS@
INTERIM_LANGTOOLS_JAR = $(BUILDTOOLS_OUTPUTDIR)/interim_langtools.jar
INTERIM_LANGTOOLS_ARGS = "-Xbootclasspath/p:$(INTERIM_LANGTOOLS_JAR)" -cp $(INTERIM_LANGTOOLS_JAR)
NEW_JAVAC = $(INTERIM_LANGTOOLS_ARGS) com.sun.tools.javac.Main
NEW_JAVADOC = $(INTERIM_LANGTOOLS_ARGS) com.sun.tools.javadoc.Main
NEW_JAVADOC = $(INTERIM_LANGTOOLS_ARGS) jdk.javadoc.internal.tool.Main
# Base flags for RC
# Guarding this against resetting value. Legacy make files include spec multiple

View File

@ -433,39 +433,22 @@ AC_DEFUN([TOOLCHAIN_FIND_COMPILER],
# Now we have a compiler binary in $1. Make sure it's okay.
BASIC_FIXUP_EXECUTABLE($1)
TEST_COMPILER="[$]$1"
# Don't remove symbolic links on AIX because 'xlc_r' and 'xlC_r' may all be links
# to 'xlc' but it is crucial that we invoke the compiler with the right name!
if test "x$OPENJDK_BUILD_OS" != xaix; then
# FIXME: This test should not be needed anymore; we don't do that for any platform.
AC_MSG_CHECKING([resolved symbolic links for $1])
BASIC_REMOVE_SYMBOLIC_LINKS(TEST_COMPILER)
AC_MSG_RESULT([$TEST_COMPILER])
fi
AC_MSG_CHECKING([if $1 is disguised ccache])
COMPILER_BASENAME=`$BASENAME "$TEST_COMPILER"`
if test "x$COMPILER_BASENAME" = "xccache"; then
AC_MSG_RESULT([yes, trying to find proper $COMPILER_NAME compiler])
# We /usr/lib/ccache in the path, so cc is a symlink to /usr/bin/ccache.
# We want to control ccache invocation ourselves, so ignore this cc and try
# searching again.
# Remove the path to the fake ccache cc from the PATH
RETRY_COMPILER_SAVED_PATH="$PATH"
COMPILER_DIRNAME=`$DIRNAME [$]$1`
PATH="`$ECHO $PATH | $SED -e "s,$COMPILER_DIRNAME,,g" -e "s,::,:,g" -e "s,^:,,g"`"
# Try again looking for our compiler
AC_CHECK_TOOLS(PROPER_COMPILER_$1, $3)
BASIC_FIXUP_EXECUTABLE(PROPER_COMPILER_$1)
PATH="$RETRY_COMPILER_SAVED_PATH"
AC_MSG_CHECKING([for resolved symbolic links for $1])
BASIC_REMOVE_SYMBOLIC_LINKS(PROPER_COMPILER_$1)
AC_MSG_RESULT([$PROPER_COMPILER_$1])
$1="$PROPER_COMPILER_$1"
AC_MSG_CHECKING([resolved symbolic links for $1])
SYMLINK_ORIGINAL="$TEST_COMPILER"
BASIC_REMOVE_SYMBOLIC_LINKS(SYMLINK_ORIGINAL)
if test "x$TEST_COMPILER" = "x$SYMLINK_ORIGINAL"; then
AC_MSG_RESULT([no symlink])
else
AC_MSG_RESULT([no, keeping $1])
AC_MSG_RESULT([$SYMLINK_ORIGINAL])
# We can't handle ccache by gcc wrappers, since we need to know if we're
# using ccache. Instead ccache usage must be controlled by a configure option.
COMPILER_BASENAME=`$BASENAME "$SYMLINK_ORIGINAL"`
if test "x$COMPILER_BASENAME" = "xccache"; then
AC_MSG_NOTICE([Please use --enable-ccache instead of providing a wrapped compiler.])
AC_MSG_ERROR([$TEST_COMPILER is a symbolic link to ccache. This is not supported.])
fi
fi
TOOLCHAIN_CHECK_COMPILER_VERSION([$1], [$COMPILER_NAME])

View File

@ -306,7 +306,7 @@ compare_general_files() {
! -name "*.lib" ! -name "*.war" ! -name "JavaControlPanel" \
! -name "*.obj" ! -name "*.o" ! -name "JavaControlPanelHelper" \
! -name "JavaUpdater" ! -name "JavaWSApplicationStub" \
! -name "jspawnhelper" \
! -name "jspawnhelper" ! -name "*.a" \
| $GREP -v "./bin/" | $SORT | $FILTER)
echo Other files with binary differences...
@ -939,7 +939,7 @@ compare_all_libs() {
WORK_DIR=$3
LIBS=$(cd $THIS_DIR && $FIND . -type f \( -name 'lib*.so' -o -name '*.dylib' \
-o -name '*.dll' -o -name '*.obj' -o -name '*.o' \
-o -name '*.dll' -o -name '*.obj' -o -name '*.o' -o -name '*.a' \
-o -name '*.cpl' \) | $SORT | $FILTER)
if [ -n "$LIBS" ]; then

View File

@ -345,3 +345,4 @@ ea285530245cf4e0edf0479121a41347d3030eba jdk-9+98
791d0d3ac0138faeb6110bd840a4545bc1950df2 jdk-9+100
30dfb3bd3d06b4bb80a087babc0d1841edba187b jdk-9+101
9c4662334d933d299928d1f599d02ff50777cbf8 jdk-9+102
0680fb7dae4da1ee6cf783c4b74184e3e08d3179 jdk-9+103

View File

@ -505,3 +505,4 @@ f008e8cc10d5b3212fb22d58c96fa01d38654f19 jdk-9+99
bdb0acafc63c42e84d9d8195bf2e2b25ee9c3306 jdk-9+100
9f45d3d57d6948cf526fbc2e2891a9a74ac6941a jdk-9+101
d5239fc1b69749ae50793c61b899fcdacf3df857 jdk-9+102
c5f55130b1b69510d9a6f4a3105b58e21cd7ffe1 jdk-9+103

View File

@ -64,14 +64,18 @@ public class TestPerfCountersAndMemoryPools {
throws Exception {
MemoryPoolMXBean pool = getMemoryPool(memoryPoolName);
// First, call all the methods to let them allocate their own slab of metadata
getMinCapacity(perfNS);
getCapacity(perfNS);
getUsed(perfNS);
pool.getUsage().getInit();
pool.getUsage().getUsed();
pool.getUsage().getCommitted();
assertEQ(1L, 1L);
// Must do a GC to update performance counters
System.gc();
assertEQ(getMinCapacity(perfNS), pool.getUsage().getInit());
// Must do a second GC to update the perfomance counters again, since
// the call pool.getUsage().getInit() could have allocated some
// metadata.
System.gc();
assertEQ(getUsed(perfNS), pool.getUsage().getUsed());
assertEQ(getCapacity(perfNS), pool.getUsage().getCommitted());
}

View File

@ -345,3 +345,4 @@ e1a789be1535741274c9779f4d4ca3495196b5c3 jdk-9+99
3d452840f48299a36842760d17c0c8402f0e1266 jdk-9+100
5e8370fb3ed925335164afe340d1e54beab2d4d5 jdk-9+101
6eb3c8132e489dab81adde4ce29844904ce15482 jdk-9+102
eee1ced1d8e78293f2a004af818ca474387dbebf jdk-9+103

View File

@ -26,7 +26,7 @@
include LauncherCommon.gmk
$(eval $(call SetupBuildLauncher, javadoc, \
MAIN_CLASS := com.sun.tools.javadoc.Main, \
MAIN_CLASS := jdk.javadoc.internal.tool.Main, \
CFLAGS := -DEXPAND_CLASSPATH_WILDCARDS \
-DNEVER_ACT_AS_SERVER_CLASS_MACHINE, \
))

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1994, 2013, 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.
*
* This code is free software; you can redistribute it and/or modify it
@ -339,7 +339,6 @@ public final class Integer extends Number implements Comparable<Integer> {
// assert shift > 0 && shift <=5 : "Illegal shift value";
int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
int chars = Math.max(((mag + (shift - 1)) / shift), 1);
if (COMPACT_STRINGS) {
byte[] buf = new byte[chars];
formatUnsignedInt(val, shift, buf, 0, chars);
@ -477,8 +476,13 @@ public final class Integer extends Number implements Comparable<Integer> {
* values, to cover the Integer.MIN_VALUE case. Converting otherwise
* (negative to positive) will expose -Integer.MIN_VALUE that overflows
* integer.
*
* @param i value to convert
* @param index next index, after the least significant digit
* @param buf target buffer, Latin1-encoded
* @return index of the most significant digit or minus sign, if present
*/
static void getChars(int i, int index, byte[] buf) {
static int getChars(int i, int index, byte[] buf) {
int q, r;
int charPos = index;
@ -509,9 +513,19 @@ public final class Integer extends Number implements Comparable<Integer> {
if (negative) {
buf[--charPos] = (byte)'-';
}
return charPos;
}
static void getCharsUTF16(int i, int index, byte[] buf) {
/**
* This is a variant of {@link #getChars(int, int, byte[])}, but for
* UTF-16 coder.
*
* @param i value to convert
* @param index next index, after the least significant digit
* @param buf target buffer, UTF16-coded.
* @return index of the most significant digit or minus sign, if present
*/
static int getCharsUTF16(int i, int index, byte[] buf) {
int q, r;
int charPos = index;
@ -542,6 +556,7 @@ public final class Integer extends Number implements Comparable<Integer> {
if (negative) {
StringUTF16.putChar(buf, --charPos, '-');
}
return charPos;
}
// Left here for compatibility reasons, see JDK-8143900.

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1994, 2013, 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.
*
* This code is free software; you can redistribute it and/or modify it
@ -379,7 +379,6 @@ public final class Long extends Number implements Comparable<Long> {
// assert shift > 0 && shift <=5 : "Illegal shift value";
int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
int chars = Math.max(((mag + (shift - 1)) / shift), 1);
if (COMPACT_STRINGS) {
byte[] buf = new byte[chars];
formatUnsignedLong0(val, shift, buf, 0, chars);
@ -489,8 +488,13 @@ public final class Long extends Number implements Comparable<Long> {
* values, to cover the Long.MIN_VALUE case. Converting otherwise
* (negative to positive) will expose -Long.MIN_VALUE that overflows
* long.
*
* @param i value to convert
* @param index next index, after the least significant digit
* @param buf target buffer, Latin1-encoded
* @return index of the most significant digit or minus sign, if present
*/
static void getChars(long i, int index, byte[] buf) {
static int getChars(long i, int index, byte[] buf) {
long q;
int r;
int charPos = index;
@ -533,9 +537,19 @@ public final class Long extends Number implements Comparable<Long> {
if (negative) {
buf[--charPos] = (byte)'-';
}
return charPos;
}
static void getCharsUTF16(long i, int index, byte[] buf) {
/**
* This is a variant of {@link #getChars(long, int, byte[])}, but for
* UTF-16 coder.
*
* @param i value to convert
* @param index next index, after the least significant digit
* @param buf target buffer, UTF16-coded.
* @return index of the most significant digit or minus sign, if present
*/
static int getCharsUTF16(long i, int index, byte[] buf) {
long q;
int r;
int charPos = index;
@ -578,6 +592,7 @@ public final class Long extends Number implements Comparable<Long> {
if (negative) {
StringUTF16.putChar(buf, --charPos, '-');
}
return charPos;
}
/**

View File

@ -0,0 +1,345 @@
/*
* Copyright (c) 2015, 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 java.lang;
/**
* Helper for string concatenation. These methods are mostly looked up with private lookups
* from {@link java.lang.invoke.StringConcatFactory}, and used in {@link java.lang.invoke.MethodHandle}
* combinators there.
*/
final class StringConcatHelper {
private StringConcatHelper() {
// no instantiation
}
/**
* Check for overflow, throw the exception on overflow.
* @param len String length
* @return length
*/
private static int checkOverflow(int len) {
if (len < 0) {
throw new OutOfMemoryError("Overflow: String length out of range");
}
return len;
}
/**
* Mix value length into current length
* @param current current length
* @param value value to mix in
* @return new length
*/
static int mixLen(int current, boolean value) {
return checkOverflow(current + (value ? 4 : 5));
}
/**
* Mix value length into current length
* @param current current length
* @param value value to mix in
* @return new length
*/
static int mixLen(int current, byte value) {
return mixLen(current, (int)value);
}
/**
* Mix value length into current length
* @param current current length
* @param value value to mix in
* @return new length
*/
static int mixLen(int current, char value) {
return checkOverflow(current + 1);
}
/**
* Mix value length into current length
* @param current current length
* @param value value to mix in
* @return new length
*/
static int mixLen(int current, short value) {
return mixLen(current, (int)value);
}
/**
* Mix value length into current length
* @param current current length
* @param value value to mix in
* @return new length
*/
static int mixLen(int current, int value) {
return checkOverflow(current + Integer.stringSize(value));
}
/**
* Mix value length into current length
* @param current current length
* @param value value to mix in
* @return new length
*/
static int mixLen(int current, long value) {
return checkOverflow(current + Long.stringSize(value));
}
/**
* Mix value length into current length
* @param current current length
* @param value value to mix in
* @return new length
*/
static int mixLen(int current, String value) {
return checkOverflow(current + value.length());
}
/**
* Mix coder into current coder
* @param current current coder
* @param value value to mix in
* @return new coder
*/
static byte mixCoder(byte current, char value) {
return (byte)(current | (StringLatin1.canEncode(value) ? 0 : 1));
}
/**
* Mix coder into current coder
* @param current current coder
* @param value value to mix in
* @return new coder
*/
static byte mixCoder(byte current, String value) {
return (byte)(current | value.coder());
}
/**
* Mix coder into current coder
* @param current current coder
* @param value value to mix in
* @return new coder
*/
static byte mixCoder(byte current, boolean value) {
// Booleans are represented with Latin1
return current;
}
/**
* Mix coder into current coder
* @param current current coder
* @param value value to mix in
* @return new coder
*/
static byte mixCoder(byte current, byte value) {
// Bytes are represented with Latin1
return current;
}
/**
* Mix coder into current coder
* @param current current coder
* @param value value to mix in
* @return new coder
*/
static byte mixCoder(byte current, short value) {
// Shorts are represented with Latin1
return current;
}
/**
* Mix coder into current coder
* @param current current coder
* @param value value to mix in
* @return new coder
*/
static byte mixCoder(byte current, int value) {
// Ints are represented with Latin1
return current;
}
/**
* Mix coder into current coder
* @param current current coder
* @param value value to mix in
* @return new coder
*/
static byte mixCoder(byte current, long value) {
// Longs are represented with Latin1
return current;
}
/**
* Prepends the stringly representation of boolean value into buffer,
* given the coder and final index. Index is measured in chars, not in bytes!
*
* @param index final char index in the buffer
* @param buf buffer to append to
* @param coder coder to add with
* @param value boolean value to encode
* @return new index
*/
static int prepend(int index, byte[] buf, byte coder, boolean value) {
if (coder == String.LATIN1) {
if (value) {
buf[--index] = 'e';
buf[--index] = 'u';
buf[--index] = 'r';
buf[--index] = 't';
} else {
buf[--index] = 'e';
buf[--index] = 's';
buf[--index] = 'l';
buf[--index] = 'a';
buf[--index] = 'f';
}
} else {
if (value) {
StringUTF16.putChar(buf, --index, 'e');
StringUTF16.putChar(buf, --index, 'u');
StringUTF16.putChar(buf, --index, 'r');
StringUTF16.putChar(buf, --index, 't');
} else {
StringUTF16.putChar(buf, --index, 'e');
StringUTF16.putChar(buf, --index, 's');
StringUTF16.putChar(buf, --index, 'l');
StringUTF16.putChar(buf, --index, 'a');
StringUTF16.putChar(buf, --index, 'f');
}
}
return index;
}
/**
* Prepends the stringly representation of byte value into buffer,
* given the coder and final index. Index is measured in chars, not in bytes!
*
* @param index final char index in the buffer
* @param buf buffer to append to
* @param coder coder to add with
* @param value byte value to encode
* @return new index
*/
static int prepend(int index, byte[] buf, byte coder, byte value) {
return prepend(index, buf, coder, (int)value);
}
/**
* Prepends the stringly representation of char value into buffer,
* given the coder and final index. Index is measured in chars, not in bytes!
*
* @param index final char index in the buffer
* @param buf buffer to append to
* @param coder coder to add with
* @param value char value to encode
* @return new index
*/
static int prepend(int index, byte[] buf, byte coder, char value) {
if (coder == String.LATIN1) {
buf[--index] = (byte) (value & 0xFF);
} else {
StringUTF16.putChar(buf, --index, value);
}
return index;
}
/**
* Prepends the stringly representation of short value into buffer,
* given the coder and final index. Index is measured in chars, not in bytes!
*
* @param index final char index in the buffer
* @param buf buffer to append to
* @param coder coder to add with
* @param value short value to encode
* @return new index
*/
static int prepend(int index, byte[] buf, byte coder, short value) {
return prepend(index, buf, coder, (int)value);
}
/**
* Prepends the stringly representation of integer value into buffer,
* given the coder and final index. Index is measured in chars, not in bytes!
*
* @param index final char index in the buffer
* @param buf buffer to append to
* @param coder coder to add with
* @param value integer value to encode
* @return new index
*/
static int prepend(int index, byte[] buf, byte coder, int value) {
if (coder == String.LATIN1) {
return Integer.getChars(value, index, buf);
} else {
return Integer.getCharsUTF16(value, index, buf);
}
}
/**
* Prepends the stringly representation of long value into buffer,
* given the coder and final index. Index is measured in chars, not in bytes!
*
* @param index final char index in the buffer
* @param buf buffer to append to
* @param coder coder to add with
* @param value long value to encode
* @return new index
*/
static int prepend(int index, byte[] buf, byte coder, long value) {
if (coder == String.LATIN1) {
return Long.getChars(value, index, buf);
} else {
return Long.getCharsUTF16(value, index, buf);
}
}
/**
* Prepends the stringly representation of String value into buffer,
* given the coder and final index. Index is measured in chars, not in bytes!
*
* @param index final char index in the buffer
* @param buf buffer to append to
* @param coder coder to add with
* @param value String value to encode
* @return new index
*/
static int prepend(int index, byte[] buf, byte coder, String value) {
index -= value.length();
value.getBytes(buf, index, coder);
return index;
}
/**
* Instantiates the String with given buffer and coder
* @param buf buffer to use
* @param coder coder to use
* @return String resulting string
*/
static String newString(byte[] buf, byte coder) {
// Use the private, non-copying constructor (unsafe!)
return new String(buf, coder);
}
}

View File

@ -0,0 +1,51 @@
/*
* Copyright (c) 2015, 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 java.lang.invoke;
/**
* StringConcatException is thrown by {@link StringConcatFactory} when linkage
* invariants are violated.
*
* @since 9
*/
public class StringConcatException extends Exception {
private static final long serialVersionUID = 292L + 9L;
/**
* Constructs an exception with a message
* @param msg exception message
*/
public StringConcatException(String msg) {
super(msg);
}
/**
* Constructs an exception with a message and a linked throwable
* @param msg exception message
* @param cause throwable cause
*/
public StringConcatException(String msg, Throwable cause) {
super(msg, cause);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1080,11 +1080,8 @@ public final class URI
* If a protocol handler for the URL could not be found,
* or if some other error occurred while constructing the URL
*/
public URL toURL()
throws MalformedURLException {
if (!isAbsolute())
throw new IllegalArgumentException("URI is not absolute");
return new URL(toString());
public URL toURL() throws MalformedURLException {
return URL.fromURI(this);
}
// -- Component access methods --

View File

@ -36,6 +36,7 @@ import java.io.ObjectStreamException;
import java.io.ObjectStreamField;
import java.io.ObjectInputStream.GetField;
import java.util.Iterator;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
@ -405,7 +406,7 @@ public final class URL implements java.io.Serializable {
}
}
protocol = protocol.toLowerCase();
protocol = protocol.toLowerCase(Locale.ROOT);
this.protocol = protocol;
if (host != null) {
@ -579,8 +580,7 @@ public final class URL implements java.io.Serializable {
for (i = start ; !aRef && (i < limit) &&
((c = spec.charAt(i)) != '/') ; i++) {
if (c == ':') {
String s = spec.substring(start, i).toLowerCase();
String s = spec.substring(start, i).toLowerCase(Locale.ROOT);
if (isValidProtocol(s)) {
newProtocol = s;
start = i + 1;
@ -659,6 +659,44 @@ public final class URL implements java.io.Serializable {
}
}
/**
* Creates a URL from a URI, as if by invoking {@code uri.toURL()}.
*
* @see java.net.URI#toURL()
*/
static URL fromURI(URI uri) throws MalformedURLException {
if (!uri.isAbsolute()) {
throw new IllegalArgumentException("URI is not absolute");
}
String protocol = uri.getScheme();
// In general we need to go via Handler.parseURL, but for the jrt
// protocol we enforce that the Handler is not overrideable and can
// optimize URI to URL conversion.
//
// Case-sensitive comparison for performance; malformed protocols will
// be handled correctly by the slow path.
if (protocol.equals("jrt") && !uri.isOpaque()
&& uri.getRawFragment() == null) {
String query = uri.getRawQuery();
String path = uri.getRawPath();
String file = (query == null) ? path : path + "?" + query;
// URL represent undefined host as empty string while URI use null
String host = uri.getHost();
if (host == null) {
host = "";
}
int port = uri.getPort();
return new URL("jrt", host, port, file, null);
} else {
return new URL((URL)null, uri.toString(), null);
}
}
/*
* Returns true if specified string is a valid protocol name.
*/
@ -1275,11 +1313,28 @@ public final class URL implements java.io.Serializable {
}
}
private static final String[] NON_OVERRIDEABLE_PROTOCOLS = {"file", "jrt"};
private static boolean isOverrideable(String protocol) {
for (String p : NON_OVERRIDEABLE_PROTOCOLS)
if (protocol.equalsIgnoreCase(p))
/**
* Non-overrideable protocols: "jrt" and "file"
*
* Character-based comparison for performance reasons; also ensures
* case-insensitive comparison in a locale-independent fashion.
*/
static boolean isOverrideable(String protocol) {
if (protocol.length() == 3) {
if ((Character.toLowerCase(protocol.charAt(0)) == 'j') &&
(Character.toLowerCase(protocol.charAt(1)) == 'r') &&
(Character.toLowerCase(protocol.charAt(2)) == 't')) {
return false;
}
} else if (protocol.length() == 4) {
if ((Character.toLowerCase(protocol.charAt(0)) == 'f') &&
(Character.toLowerCase(protocol.charAt(1)) == 'i') &&
(Character.toLowerCase(protocol.charAt(2)) == 'l') &&
(Character.toLowerCase(protocol.charAt(3)) == 'e')) {
return false;
}
}
return true;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 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
@ -59,7 +59,7 @@ public interface FileOwnerAttributeView
/**
* Read the file owner.
*
* <p> It it implementation specific if the file owner can be a {@link
* <p> It is implementation specific if the file owner can be a {@link
* GroupPrincipal group}.
*
* @return the file owner
@ -78,7 +78,7 @@ public interface FileOwnerAttributeView
/**
* Updates the file owner.
*
* <p> It it implementation specific if the file owner can be a {@link
* <p> It is implementation specific if the file owner can be a {@link
* GroupPrincipal group}. To ensure consistent and correct behavior
* across platforms it is recommended that this method should only be used
* to set the file owner to a user principal that is not a group.

View File

@ -649,7 +649,7 @@ public interface Map<K, V> {
try {
k = entry.getKey();
v = entry.getValue();
} catch(IllegalStateException ise) {
} catch (IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
@ -704,7 +704,7 @@ public interface Map<K, V> {
try {
k = entry.getKey();
v = entry.getValue();
} catch(IllegalStateException ise) {
} catch (IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
@ -714,7 +714,7 @@ public interface Map<K, V> {
try {
entry.setValue(v);
} catch(IllegalStateException ise) {
} catch (IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
@ -887,7 +887,7 @@ public interface Map<K, V> {
* or atomicity properties of this method. Any implementation providing
* atomicity guarantees must override this method and document its
* concurrency properties.
*
*
* @param key key with which the specified value is associated
* @param value value to be associated with the specified key
* @return the previous value associated with the specified key, or
@ -984,6 +984,9 @@ public interface Map<K, V> {
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
* @since 1.8
*/
default V computeIfAbsent(K key,
@ -1058,6 +1061,9 @@ public interface Map<K, V> {
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
* @since 1.8
*/
default V computeIfPresent(K key,
@ -1103,7 +1109,7 @@ public interface Map<K, V> {
* <pre> {@code
* V oldValue = map.get(key);
* V newValue = remappingFunction.apply(key, oldValue);
* if (oldValue != null ) {
* if (oldValue != null) {
* if (newValue != null)
* map.put(key, newValue);
* else
@ -1147,6 +1153,9 @@ public interface Map<K, V> {
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
* @since 1.8
*/
default V compute(K key,
@ -1239,6 +1248,9 @@ public interface Map<K, V> {
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
* (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
* @throws IllegalArgumentException if some property of the specified key
* or value prevents it from being stored in this map
* (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified key is null and this map
* does not support null keys or the value or remappingFunction is
* null
@ -1251,7 +1263,7 @@ public interface Map<K, V> {
V oldValue = get(key);
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if(newValue == null) {
if (newValue == null) {
remove(key);
} else {
put(key, newValue);

View File

@ -129,14 +129,6 @@ package java.util;
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @see java.util.Collection
* @see LinkedList
* @see PriorityQueue
* @see java.util.concurrent.LinkedBlockingQueue
* @see java.util.concurrent.BlockingQueue
* @see java.util.concurrent.ArrayBlockingQueue
* @see java.util.concurrent.LinkedBlockingQueue
* @see java.util.concurrent.PriorityBlockingQueue
* @since 1.5
* @author Doug Lea
* @param <E> the type of elements held in this queue

View File

@ -233,42 +233,56 @@ public class Vector<E>
public synchronized void ensureCapacity(int minCapacity) {
if (minCapacity > 0) {
modCount++;
ensureCapacityHelper(minCapacity);
if (minCapacity > elementData.length)
grow(minCapacity);
}
}
/**
* This implements the unsynchronized semantics of ensureCapacity.
* Synchronized methods in this class can internally call this
* method for ensuring capacity without incurring the cost of an
* extra synchronization.
*
* @see #ensureCapacity(int)
*/
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* The maximum size of array to allocate.
* The maximum size of array to allocate (unless necessary).
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
* @throws OutOfMemoryError if minCapacity is less than zero
*/
private Object[] grow(int minCapacity) {
return elementData = Arrays.copyOf(elementData,
newCapacity(minCapacity));
}
private Object[] grow() {
return grow(elementCount + 1);
}
/**
* Returns a capacity at least as large as the given minimum capacity.
* Will not return a capacity greater than MAX_ARRAY_SIZE unless
* the given minimum capacity is greater than MAX_ARRAY_SIZE.
*
* @param minCapacity the desired minimum capacity
* @throws OutOfMemoryError if minCapacity is less than zero
*/
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
if (newCapacity - minCapacity <= 0) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return minCapacity;
}
return (newCapacity - MAX_ARRAY_SIZE <= 0)
? newCapacity
: hugeCapacity(minCapacity);
}
private static int hugeCapacity(int minCapacity) {
@ -290,13 +304,10 @@ public class Vector<E>
*/
public synchronized void setSize(int newSize) {
modCount++;
if (newSize > elementCount) {
ensureCapacityHelper(newSize);
} else {
for (int i = newSize ; i < elementCount ; i++) {
elementData[i] = null;
}
}
if (newSize > elementData.length)
grow(newSize);
for (int i = newSize; i < elementCount; i++)
elementData[i] = null;
elementCount = newSize;
}
@ -604,11 +615,16 @@ public class Vector<E>
throw new ArrayIndexOutOfBoundsException(index
+ " > " + elementCount);
}
ensureCapacityHelper(elementCount + 1);
System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
elementData[index] = obj;
modCount++;
elementCount++;
final int s = elementCount;
Object[] elementData = this.elementData;
if (s == elementData.length)
elementData = grow();
System.arraycopy(elementData, index,
elementData, index + 1,
s - index);
elementData[index] = obj;
elementCount = s + 1;
}
/**
@ -623,9 +639,8 @@ public class Vector<E>
* @param obj the component to be added
*/
public synchronized void addElement(E obj) {
ensureCapacityHelper(elementCount + 1);
modCount++;
elementData[elementCount++] = obj;
add(obj, elementData, elementCount);
}
/**
@ -780,6 +795,18 @@ public class Vector<E>
return oldValue;
}
/**
* This helper method split out from add(E) to keep method
* bytecode size under 35 (the -XX:MaxInlineSize default value),
* which helps when add(E) is called in a C1-compiled loop.
*/
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();
elementData[s] = e;
elementCount = s + 1;
}
/**
* Appends the specified element to the end of this Vector.
*
@ -788,9 +815,8 @@ public class Vector<E>
* @since 1.2
*/
public synchronized boolean add(E e) {
ensureCapacityHelper(elementCount + 1);
modCount++;
elementData[elementCount++] = e;
add(e, elementData, elementCount);
return true;
}
@ -891,16 +917,19 @@ public class Vector<E>
*/
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
modCount++;
int numNew = a.length;
if (numNew > 0) {
synchronized (this) {
ensureCapacityHelper(elementCount + numNew);
System.arraycopy(a, 0, elementData, elementCount, numNew);
modCount++;
elementCount += numNew;
}
if (numNew == 0)
return false;
synchronized (this) {
Object[] elementData = this.elementData;
final int s = elementCount;
if (numNew > elementData.length - s)
elementData = grow(s + numNew);
System.arraycopy(a, 0, elementData, s, numNew);
elementCount = s + numNew;
return true;
}
return numNew > 0;
}
/**
@ -969,21 +998,23 @@ public class Vector<E>
throw new ArrayIndexOutOfBoundsException(index);
Object[] a = c.toArray();
modCount++;
int numNew = a.length;
if (numNew == 0)
return false;
Object[] elementData = this.elementData;
final int s = elementCount;
if (numNew > elementData.length - s)
elementData = grow(s + numNew);
if (numNew > 0) {
ensureCapacityHelper(elementCount + numNew);
int numMoved = elementCount - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData,
index + numNew, numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
elementCount += numNew;
modCount++;
}
return numNew > 0;
int numMoved = s - index;
if (numMoved > 0)
System.arraycopy(elementData, index,
elementData, index + numNew,
numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
elementCount = s + numNew;
return true;
}
/**

View File

@ -301,19 +301,15 @@ public interface ConcurrentMap<K,V> extends Map<K,V> {
*
* @implSpec
* The default implementation is equivalent to the following steps for this
* {@code map}, then returning the current value or {@code null} if now
* absent:
* {@code map}:
*
* <pre> {@code
* if (map.get(key) == null) {
* V newValue = mappingFunction.apply(key);
* if (newValue != null)
* return map.putIfAbsent(key, newValue);
* }}</pre>
*
* The default implementation may retry these steps when multiple
* threads attempt updates including potentially calling the mapping
* function multiple times.
* V oldValue, newValue;
* return ((oldValue = map.get(key)) == null
* && (newValue = mappingFunction.apply(key)) != null
* && (oldValue = map.putIfAbsent(key, newValue)) == null)
* ? newValue
* : oldValue;}</pre>
*
* <p>This implementation assumes that the ConcurrentMap cannot contain null
* values and {@code get()} returning null unambiguously means the key is
@ -323,16 +319,19 @@ public interface ConcurrentMap<K,V> extends Map<K,V> {
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
* @since 1.8
*/
@Override
default V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v, newValue;
return ((v = get(key)) == null &&
(newValue = mappingFunction.apply(key)) != null &&
(v = putIfAbsent(key, newValue)) == null) ? newValue : v;
V oldValue, newValue;
return ((oldValue = get(key)) == null
&& (newValue = mappingFunction.apply(key)) != null
&& (oldValue = putIfAbsent(key, newValue)) == null)
? newValue
: oldValue;
}
/**
@ -340,22 +339,19 @@ public interface ConcurrentMap<K,V> extends Map<K,V> {
*
* @implSpec
* The default implementation is equivalent to performing the following
* steps for this {@code map}, then returning the current value or
* {@code null} if now absent:
* steps for this {@code map}:
*
* <pre> {@code
* if (map.get(key) != null) {
* V oldValue = map.get(key);
* for (V oldValue; (oldValue = map.get(key)) != null; ) {
* V newValue = remappingFunction.apply(key, oldValue);
* if (newValue != null)
* map.replace(key, oldValue, newValue);
* else
* map.remove(key, oldValue);
* }}</pre>
*
* The default implementation may retry these steps when multiple threads
* attempt updates including potentially calling the remapping function
* multiple times.
* if ((newValue == null)
* ? map.remove(key, oldValue)
* : map.replace(key, oldValue, newValue))
* return newValue;
* }
* return null;}</pre>
* When multiple threads attempt updates, map operations and the
* remapping function may be called multiple times.
*
* <p>This implementation assumes that the ConcurrentMap cannot contain null
* values and {@code get()} returning null unambiguously means the key is
@ -365,22 +361,21 @@ public interface ConcurrentMap<K,V> extends Map<K,V> {
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
* @since 1.8
*/
@Override
default V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue;
while ((oldValue = get(key)) != null) {
for (V oldValue; (oldValue = get(key)) != null; ) {
V newValue = remappingFunction.apply(key, oldValue);
if (newValue != null) {
if (replace(key, oldValue, newValue))
return newValue;
} else if (remove(key, oldValue))
return null;
if ((newValue == null)
? remove(key, oldValue)
: replace(key, oldValue, newValue))
return newValue;
}
return oldValue;
return null;
}
/**
@ -388,27 +383,23 @@ public interface ConcurrentMap<K,V> extends Map<K,V> {
*
* @implSpec
* The default implementation is equivalent to performing the following
* steps for this {@code map}, then returning the current value or
* {@code null} if absent:
* steps for this {@code map}:
*
* <pre> {@code
* V oldValue = map.get(key);
* V newValue = remappingFunction.apply(key, oldValue);
* if (oldValue != null ) {
* if (newValue != null)
* map.replace(key, oldValue, newValue);
* else
* map.remove(key, oldValue);
* } else {
* if (newValue != null)
* map.putIfAbsent(key, newValue);
* else
* for (;;) {
* V oldValue = map.get(key);
* V newValue = remappingFunction.apply(key, oldValue);
* if (newValue != null) {
* if ((oldValue != null)
* ? map.replace(key, oldValue, newValue)
* : map.putIfAbsent(key, newValue) == null)
* return newValue;
* } else if (oldValue == null || map.remove(key, oldValue)) {
* return null;
* }
* }}</pre>
*
* The default implementation may retry these steps when multiple
* threads attempt updates including potentially calling the remapping
* function multiple times.
* When multiple threads attempt updates, map operations and the
* remapping function may be called multiple times.
*
* <p>This implementation assumes that the ConcurrentMap cannot contain null
* values and {@code get()} returning null unambiguously means the key is
@ -418,50 +409,29 @@ public interface ConcurrentMap<K,V> extends Map<K,V> {
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
* @since 1.8
*/
@Override
default V compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue = get(key);
for (;;) {
V newValue = remappingFunction.apply(key, oldValue);
if (newValue == null) {
// delete mapping
if (oldValue != null || containsKey(key)) {
// something to remove
if (remove(key, oldValue)) {
// removed the old value as expected
return null;
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
retry: for (;;) {
V oldValue = get(key);
// if putIfAbsent fails, opportunistically use its return value
haveOldValue: for (;;) {
V newValue = remappingFunction.apply(key, oldValue);
if (newValue != null) {
if (oldValue != null) {
if (replace(key, oldValue, newValue))
return newValue;
}
// some other value replaced old value. try again.
oldValue = get(key);
} else {
// nothing to do. Leave things as they were.
else if ((oldValue = putIfAbsent(key, newValue)) == null)
return newValue;
else continue haveOldValue;
} else if (oldValue == null || remove(key, oldValue)) {
return null;
}
} else {
// add or replace old mapping
if (oldValue != null) {
// replace
if (replace(key, oldValue, newValue)) {
// replaced as expected.
return newValue;
}
// some other value replaced old value. try again.
oldValue = get(key);
} else {
// add (replace if oldValue was null)
if ((oldValue = putIfAbsent(key, newValue)) == null) {
// replaced
return newValue;
}
// some other value replaced old value. try again.
}
continue retry;
}
}
}
@ -471,21 +441,25 @@ public interface ConcurrentMap<K,V> extends Map<K,V> {
*
* @implSpec
* The default implementation is equivalent to performing the following
* steps for this {@code map}, then returning the current value or
* {@code null} if absent:
* steps for this {@code map}:
*
* <pre> {@code
* V oldValue = map.get(key);
* V newValue = (oldValue == null) ? value :
* remappingFunction.apply(oldValue, value);
* if (newValue == null)
* map.remove(key);
* else
* map.put(key, newValue);}</pre>
*
* <p>The default implementation may retry these steps when multiple
* threads attempt updates including potentially calling the remapping
* function multiple times.
* for (;;) {
* V oldValue = map.get(key);
* if (oldValue != null) {
* V newValue = remappingFunction.apply(oldValue, value);
* if (newValue != null) {
* if (map.replace(key, oldValue, newValue))
* return newValue;
* } else if (map.remove(key, oldValue)) {
* return null;
* }
* } else if (map.putIfAbsent(key, value) == null) {
* return value;
* }
* }}</pre>
* When multiple threads attempt updates, map operations and the
* remapping function may be called multiple times.
*
* <p>This implementation assumes that the ConcurrentMap cannot contain null
* values and {@code get()} returning null unambiguously means the key is
@ -495,6 +469,7 @@ public interface ConcurrentMap<K,V> extends Map<K,V> {
* @throws UnsupportedOperationException {@inheritDoc}
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
* @since 1.8
*/
@Override
@ -502,20 +477,23 @@ public interface ConcurrentMap<K,V> extends Map<K,V> {
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
Objects.requireNonNull(value);
V oldValue = get(key);
for (;;) {
if (oldValue != null) {
V newValue = remappingFunction.apply(oldValue, value);
if (newValue != null) {
if (replace(key, oldValue, newValue))
return newValue;
} else if (remove(key, oldValue)) {
return null;
}
oldValue = get(key);
} else {
if ((oldValue = putIfAbsent(key, value)) == null) {
return value;
retry: for (;;) {
V oldValue = get(key);
// if putIfAbsent fails, opportunistically use its return value
haveOldValue: for (;;) {
if (oldValue != null) {
V newValue = remappingFunction.apply(oldValue, value);
if (newValue != null) {
if (replace(key, oldValue, newValue))
return newValue;
} else if (remove(key, oldValue)) {
return null;
}
continue retry;
} else {
if ((oldValue = putIfAbsent(key, value)) == null)
return value;
continue haveOldValue;
}
}
}

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.
*
* This code is free software; you can redistribute it and/or modify it
@ -44,6 +44,9 @@ public class Util {
// The number of temp buffers in our pool
private static final int TEMP_BUF_POOL_SIZE = IOUtil.IOV_MAX;
// The max size allowed for a cached temp buffer, in bytes
private static final long MAX_CACHED_BUFFER_SIZE = getMaxCachedBufferSize();
// Per-thread cache of temporary direct buffers
private static ThreadLocal<BufferCache> bufferCache =
new ThreadLocal<BufferCache>()
@ -54,6 +57,52 @@ public class Util {
}
};
/**
* Returns the max size allowed for a cached temp buffers, in
* bytes. It defaults to Long.MAX_VALUE. It can be set with the
* jdk.nio.maxCachedBufferSize property. Even though
* ByteBuffer.capacity() returns an int, we're using a long here
* for potential future-proofing.
*/
private static long getMaxCachedBufferSize() {
String s = java.security.AccessController.doPrivileged(
new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty("jdk.nio.maxCachedBufferSize");
}
});
if (s != null) {
try {
long m = Long.parseLong(s);
if (m >= 0) {
return m;
} else {
// if it's negative, ignore the system property
}
} catch (NumberFormatException e) {
// if the string is not well formed, ignore the system property
}
}
return Long.MAX_VALUE;
}
/**
* Returns true if a buffer of this size is too large to be
* added to the buffer cache, false otherwise.
*/
private static boolean isBufferTooLarge(int size) {
return size > MAX_CACHED_BUFFER_SIZE;
}
/**
* Returns true if the buffer is too large to be added to the
* buffer cache, false otherwise.
*/
private static boolean isBufferTooLarge(ByteBuffer buf) {
return isBufferTooLarge(buf.capacity());
}
/**
* A simple cache of direct buffers.
*/
@ -80,6 +129,9 @@ public class Util {
* size (or null if no suitable buffer is found).
*/
ByteBuffer get(int size) {
// Don't call this if the buffer would be too large.
assert !isBufferTooLarge(size);
if (count == 0)
return null; // cache is empty
@ -117,6 +169,9 @@ public class Util {
}
boolean offerFirst(ByteBuffer buf) {
// Don't call this if the buffer is too large.
assert !isBufferTooLarge(buf);
if (count >= TEMP_BUF_POOL_SIZE) {
return false;
} else {
@ -128,6 +183,9 @@ public class Util {
}
boolean offerLast(ByteBuffer buf) {
// Don't call this if the buffer is too large.
assert !isBufferTooLarge(buf);
if (count >= TEMP_BUF_POOL_SIZE) {
return false;
} else {
@ -156,6 +214,15 @@ public class Util {
* Returns a temporary buffer of at least the given size
*/
public static ByteBuffer getTemporaryDirectBuffer(int size) {
// If a buffer of this size is too large for the cache, there
// should not be a buffer in the cache that is at least as
// large. So we'll just create a new one. Also, we don't have
// to remove the buffer from the cache (as this method does
// below) given that we won't put the new buffer in the cache.
if (isBufferTooLarge(size)) {
return ByteBuffer.allocateDirect(size);
}
BufferCache cache = bufferCache.get();
ByteBuffer buf = cache.get(size);
if (buf != null) {
@ -185,6 +252,13 @@ public class Util {
* likely to be returned by a subsequent call to getTemporaryDirectBuffer.
*/
static void offerFirstTemporaryDirectBuffer(ByteBuffer buf) {
// If the buffer is too large for the cache we don't have to
// check the cache. We'll just free it.
if (isBufferTooLarge(buf)) {
free(buf);
return;
}
assert buf != null;
BufferCache cache = bufferCache.get();
if (!cache.offerFirst(buf)) {
@ -200,6 +274,13 @@ public class Util {
* cache in same order that they were obtained.
*/
static void offerLastTemporaryDirectBuffer(ByteBuffer buf) {
// If the buffer is too large for the cache we don't have to
// check the cache. We'll just free it.
if (isBufferTooLarge(buf)) {
free(buf);
return;
}
assert buf != null;
BufferCache cache = bufferCache.get();
if (!cache.offerLast(buf)) {

View File

@ -59,7 +59,11 @@ abstract class AbstractPoller implements Runnable {
AccessController.doPrivileged(new PrivilegedAction<>() {
@Override
public Object run() {
Thread thr = new Thread(null, thisRunnable, "FileSystemWatchService", 0, false);
Thread thr = new Thread(null,
thisRunnable,
"FileSystemWatchService",
0,
false);
thr.setDaemon(true);
thr.start();
return null;
@ -216,10 +220,10 @@ abstract class AbstractPoller implements Runnable {
throw new ClosedWatchServiceException();
}
requestList.add(req);
}
// wakeup thread
wakeup();
// wakeup thread
wakeup();
}
// wait for result
Object result = req.awaitResult();
@ -244,6 +248,7 @@ abstract class AbstractPoller implements Runnable {
// if in process of shutdown then reject request
if (shutdown) {
req.release(new ClosedWatchServiceException());
continue;
}
switch (req.type()) {

View File

@ -0,0 +1,183 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static java.util.Collections.*;
import jdk.internal.joptsimple.internal.Reflection;
import jdk.internal.joptsimple.internal.ReflectionException;
import static jdk.internal.joptsimple.internal.Strings.*;
/**
* @param <V> represents the type of the arguments this option accepts
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
abstract class AbstractOptionSpec<V> implements OptionSpec<V>, OptionDescriptor {
private final List<String> options = new ArrayList<String>();
private final String description;
private boolean forHelp;
protected AbstractOptionSpec( String option ) {
this( singletonList( option ), EMPTY );
}
protected AbstractOptionSpec( Collection<String> options, String description ) {
arrangeOptions( options );
this.description = description;
}
public final Collection<String> options() {
return unmodifiableList( options );
}
public final List<V> values( OptionSet detectedOptions ) {
return detectedOptions.valuesOf( this );
}
public final V value( OptionSet detectedOptions ) {
return detectedOptions.valueOf( this );
}
public String description() {
return description;
}
public final AbstractOptionSpec<V> forHelp() {
forHelp = true;
return this;
}
public final boolean isForHelp() {
return forHelp;
}
public boolean representsNonOptions() {
return false;
}
protected abstract V convert( String argument );
protected V convertWith( ValueConverter<V> converter, String argument ) {
try {
return Reflection.convertWith( converter, argument );
}
catch ( ReflectionException ex ) {
throw new OptionArgumentConversionException( options(), argument, ex );
}
catch ( ValueConversionException ex ) {
throw new OptionArgumentConversionException( options(), argument, ex );
}
}
protected String argumentTypeIndicatorFrom( ValueConverter<V> converter ) {
if ( converter == null )
return null;
String pattern = converter.valuePattern();
return pattern == null ? converter.valueType().getName() : pattern;
}
abstract void handleOption( OptionParser parser, ArgumentList arguments, OptionSet detectedOptions,
String detectedArgument );
private void arrangeOptions( Collection<String> unarranged ) {
if ( unarranged.size() == 1 ) {
options.addAll( unarranged );
return;
}
List<String> shortOptions = new ArrayList<String>();
List<String> longOptions = new ArrayList<String>();
for ( String each : unarranged ) {
if ( each.length() == 1 )
shortOptions.add( each );
else
longOptions.add( each );
}
sort( shortOptions );
sort( longOptions );
options.addAll( shortOptions );
options.addAll( longOptions );
}
@Override
public boolean equals( Object that ) {
if ( !( that instanceof AbstractOptionSpec<?> ) )
return false;
AbstractOptionSpec<?> other = (AbstractOptionSpec<?>) that;
return options.equals( other.options );
}
@Override
public int hashCode() {
return options.hashCode();
}
@Override
public String toString() {
return options.toString();
}
}

View File

@ -0,0 +1,81 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import static java.util.Collections.*;
import static jdk.internal.joptsimple.ParserRules.*;
/**
* Represents the <kbd>"-W"</kbd> form of long option specification.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class AlternativeLongOptionSpec extends ArgumentAcceptingOptionSpec<String> {
AlternativeLongOptionSpec() {
super( singletonList( RESERVED_FOR_EXTENSIONS ), true, "Alternative form of long options" );
describedAs( "opt=value" );
}
@Override
protected void detectOptionArgument( OptionParser parser, ArgumentList arguments, OptionSet detectedOptions ) {
if ( !arguments.hasMore() )
throw new OptionMissingRequiredArgumentException( options() );
arguments.treatNextAsLongOption();
}
}

View File

@ -0,0 +1,360 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;
import static java.util.Collections.*;
import static jdk.internal.joptsimple.internal.Objects.*;
import static jdk.internal.joptsimple.internal.Reflection.*;
import static jdk.internal.joptsimple.internal.Strings.*;
/**
* <p>Specification of an option that accepts an argument.</p>
*
* <p>Instances are returned from {@link OptionSpecBuilder} methods to allow the formation of parser directives as
* sentences in a "fluent interface" language. For example:</p>
*
* <pre>
* <code>
* OptionParser parser = new OptionParser();
* parser.accepts( "c" ).withRequiredArg().<strong>ofType( Integer.class )</strong>;
* </code>
* </pre>
*
* <p>If no methods are invoked on an instance of this class, then that instance's option will treat its argument as
* a {@link String}.</p>
*
* @param <V> represents the type of the arguments this option accepts
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public abstract class ArgumentAcceptingOptionSpec<V> extends AbstractOptionSpec<V> {
private static final char NIL_VALUE_SEPARATOR = '\u0000';
private boolean optionRequired;
private final boolean argumentRequired;
private ValueConverter<V> converter;
private String argumentDescription = "";
private String valueSeparator = String.valueOf( NIL_VALUE_SEPARATOR );
private final List<V> defaultValues = new ArrayList<V>();
ArgumentAcceptingOptionSpec( String option, boolean argumentRequired ) {
super( option );
this.argumentRequired = argumentRequired;
}
ArgumentAcceptingOptionSpec( Collection<String> options, boolean argumentRequired, String description ) {
super( options, description );
this.argumentRequired = argumentRequired;
}
/**
* <p>Specifies a type to which arguments of this spec's option are to be converted.</p>
*
* <p>JOpt Simple accepts types that have either:</p>
*
* <ol>
* <li>a public static method called {@code valueOf} which accepts a single argument of type {@link String}
* and whose return type is the same as the class on which the method is declared. The {@code java.lang}
* primitive wrapper classes have such methods.</li>
*
* <li>a public constructor which accepts a single argument of type {@link String}.</li>
* </ol>
*
* <p>This class converts arguments using those methods in that order; that is, {@code valueOf} would be invoked
* before a one-{@link String}-arg constructor would.</p>
*
* <p>Invoking this method will trump any previous calls to this method or to
* {@link #withValuesConvertedBy(ValueConverter)}.</p>
*
* @param <T> represents the runtime class of the desired option argument type
* @param argumentType desired type of arguments to this spec's option
* @return self, so that the caller can add clauses to the fluent interface sentence
* @throws NullPointerException if the type is {@code null}
* @throws IllegalArgumentException if the type does not have the standard conversion methods
*/
public final <T> ArgumentAcceptingOptionSpec<T> ofType( Class<T> argumentType ) {
return withValuesConvertedBy( findConverter( argumentType ) );
}
/**
* <p>Specifies a converter to use to translate arguments of this spec's option into Java objects. This is useful
* when converting to types that do not have the requisite factory method or constructor for
* {@link #ofType(Class)}.</p>
*
* <p>Invoking this method will trump any previous calls to this method or to {@link #ofType(Class)}.
*
* @param <T> represents the runtime class of the desired option argument type
* @param aConverter the converter to use
* @return self, so that the caller can add clauses to the fluent interface sentence
* @throws NullPointerException if the converter is {@code null}
*/
@SuppressWarnings( "unchecked" )
public final <T> ArgumentAcceptingOptionSpec<T> withValuesConvertedBy( ValueConverter<T> aConverter ) {
if ( aConverter == null )
throw new NullPointerException( "illegal null converter" );
converter = (ValueConverter<V>) aConverter;
return (ArgumentAcceptingOptionSpec<T>) this;
}
/**
* <p>Specifies a description for the argument of the option that this spec represents. This description is used
* when generating help information about the parser.</p>
*
* @param description describes the nature of the argument of this spec's option
* @return self, so that the caller can add clauses to the fluent interface sentence
*/
public final ArgumentAcceptingOptionSpec<V> describedAs( String description ) {
argumentDescription = description;
return this;
}
/**
* <p>Specifies a value separator for the argument of the option that this spec represents. This allows a single
* option argument to represent multiple values for the option. For example:</p>
*
* <pre>
* <code>
* parser.accepts( "z" ).withRequiredArg()
* .<strong>withValuesSeparatedBy( ',' )</strong>;
* OptionSet options = parser.parse( new String[] { "-z", "foo,bar,baz", "-z",
* "fizz", "-z", "buzz" } );
* </code>
* </pre>
*
* <p>Then {@code options.valuesOf( "z" )} would yield the list {@code [foo, bar, baz, fizz, buzz]}.</p>
*
* <p>You cannot use Unicode U+0000 as the separator.</p>
*
* @param separator a character separator
* @return self, so that the caller can add clauses to the fluent interface sentence
* @throws IllegalArgumentException if the separator is Unicode U+0000
*/
public final ArgumentAcceptingOptionSpec<V> withValuesSeparatedBy( char separator ) {
if ( separator == NIL_VALUE_SEPARATOR )
throw new IllegalArgumentException( "cannot use U+0000 as separator" );
valueSeparator = String.valueOf( separator );
return this;
}
/**
* <p>Specifies a value separator for the argument of the option that this spec represents. This allows a single
* option argument to represent multiple values for the option. For example:</p>
*
* <pre>
* <code>
* parser.accepts( "z" ).withRequiredArg()
* .<strong>withValuesSeparatedBy( ":::" )</strong>;
* OptionSet options = parser.parse( new String[] { "-z", "foo:::bar:::baz", "-z",
* "fizz", "-z", "buzz" } );
* </code>
* </pre>
*
* <p>Then {@code options.valuesOf( "z" )} would yield the list {@code [foo, bar, baz, fizz, buzz]}.</p>
*
* <p>You cannot use Unicode U+0000 in the separator.</p>
*
* @param separator a string separator
* @return self, so that the caller can add clauses to the fluent interface sentence
* @throws IllegalArgumentException if the separator contains Unicode U+0000
*/
public final ArgumentAcceptingOptionSpec<V> withValuesSeparatedBy( String separator ) {
if ( separator.indexOf( NIL_VALUE_SEPARATOR ) != -1 )
throw new IllegalArgumentException( "cannot use U+0000 in separator" );
valueSeparator = separator;
return this;
}
/**
* Specifies a set of default values for the argument of the option that this spec represents.
*
* @param value the first in the set of default argument values for this spec's option
* @param values the (optional) remainder of the set of default argument values for this spec's option
* @return self, so that the caller can add clauses to the fluent interface sentence
* @throws NullPointerException if {@code value}, {@code values}, or any elements of {@code values} are
* {@code null}
*/
@SuppressWarnings("unchecked")
public ArgumentAcceptingOptionSpec<V> defaultsTo( V value, V... values ) {
addDefaultValue( value );
defaultsTo( values );
return this;
}
/**
* Specifies a set of default values for the argument of the option that this spec represents.
*
* @param values the set of default argument values for this spec's option
* @return self, so that the caller can add clauses to the fluent interface sentence
* @throws NullPointerException if {@code values} or any elements of {@code values} are {@code null}
*/
public ArgumentAcceptingOptionSpec<V> defaultsTo( V[] values ) {
for ( V each : values )
addDefaultValue( each );
return this;
}
/**
* Marks this option as required. An {@link OptionException} will be thrown when
* {@link OptionParser#parse(java.lang.String...)} is called, if an option is marked as required and not specified
* on the command line.
*
* @return self, so that the caller can add clauses to the fluent interface sentence
*/
public ArgumentAcceptingOptionSpec<V> required() {
optionRequired = true;
return this;
}
public boolean isRequired() {
return optionRequired;
}
private void addDefaultValue( V value ) {
ensureNotNull( value );
defaultValues.add( value );
}
@Override
final void handleOption( OptionParser parser, ArgumentList arguments, OptionSet detectedOptions,
String detectedArgument ) {
if ( isNullOrEmpty( detectedArgument ) )
detectOptionArgument( parser, arguments, detectedOptions );
else
addArguments( detectedOptions, detectedArgument );
}
protected void addArguments( OptionSet detectedOptions, String detectedArgument ) {
StringTokenizer lexer = new StringTokenizer( detectedArgument, valueSeparator );
if ( !lexer.hasMoreTokens() )
detectedOptions.addWithArgument( this, detectedArgument );
else {
while ( lexer.hasMoreTokens() )
detectedOptions.addWithArgument( this, lexer.nextToken() );
}
}
protected abstract void detectOptionArgument( OptionParser parser, ArgumentList arguments,
OptionSet detectedOptions );
@Override
protected final V convert( String argument ) {
return convertWith( converter, argument );
}
protected boolean canConvertArgument( String argument ) {
StringTokenizer lexer = new StringTokenizer( argument, valueSeparator );
try {
while ( lexer.hasMoreTokens() )
convert( lexer.nextToken() );
return true;
}
catch ( OptionException ignored ) {
return false;
}
}
protected boolean isArgumentOfNumberType() {
return converter != null && Number.class.isAssignableFrom( converter.valueType() );
}
public boolean acceptsArguments() {
return true;
}
public boolean requiresArgument() {
return argumentRequired;
}
public String argumentDescription() {
return argumentDescription;
}
public String argumentTypeIndicator() {
return argumentTypeIndicatorFrom( converter );
}
public List<V> defaultValues() {
return unmodifiableList( defaultValues );
}
@Override
public boolean equals( Object that ) {
if ( !super.equals( that ) )
return false;
ArgumentAcceptingOptionSpec<?> other = (ArgumentAcceptingOptionSpec<?>) that;
return requiresArgument() == other.requiresArgument();
}
@Override
public int hashCode() {
return super.hashCode() ^ ( argumentRequired ? 0 : 1 );
}
}

View File

@ -0,0 +1,89 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import static jdk.internal.joptsimple.ParserRules.*;
/**
* <p>Wrapper for an array of command line arguments.</p>
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class ArgumentList {
private final String[] arguments;
private int currentIndex;
ArgumentList( String... arguments ) {
this.arguments = arguments.clone();
}
boolean hasMore() {
return currentIndex < arguments.length;
}
String next() {
return arguments[ currentIndex++ ];
}
String peek() {
return arguments[ currentIndex ];
}
void treatNextAsLongOption() {
if ( HYPHEN_CHAR != arguments[ currentIndex ].charAt( 0 ) )
arguments[ currentIndex ] = DOUBLE_HYPHEN + arguments[ currentIndex ];
}
}

View File

@ -0,0 +1,282 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import jdk.internal.joptsimple.internal.Rows;
import jdk.internal.joptsimple.internal.Strings;
import static jdk.internal.joptsimple.ParserRules.*;
import static jdk.internal.joptsimple.internal.Classes.*;
import static jdk.internal.joptsimple.internal.Strings.*;
/**
* <p>A help formatter that allows configuration of overall row width and column separator width.</p>
*
* <p>The formatter produces a two-column output. The left column is for the options, and the right column for their
* descriptions. The formatter will allow as much space as possible for the descriptions, by minimizing the option
* column's width, no greater than slightly less than half the overall desired width.</p>
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public class BuiltinHelpFormatter implements HelpFormatter {
private final Rows nonOptionRows;
private final Rows optionRows;
/**
* Makes a formatter with a pre-configured overall row width and column separator width.
*/
BuiltinHelpFormatter() {
this( 80, 2 );
}
/**
* Makes a formatter with a given overall row width and column separator width.
*
* @param desiredOverallWidth how many characters wide to make the overall help display
* @param desiredColumnSeparatorWidth how many characters wide to make the separation between option column and
* description column
*/
public BuiltinHelpFormatter( int desiredOverallWidth, int desiredColumnSeparatorWidth ) {
nonOptionRows = new Rows( desiredOverallWidth * 2, 0 );
optionRows = new Rows( desiredOverallWidth, desiredColumnSeparatorWidth );
}
public String format( Map<String, ? extends OptionDescriptor> options ) {
Comparator<OptionDescriptor> comparator =
new Comparator<OptionDescriptor>() {
public int compare( OptionDescriptor first, OptionDescriptor second ) {
return first.options().iterator().next().compareTo( second.options().iterator().next() );
}
};
Set<OptionDescriptor> sorted = new TreeSet<OptionDescriptor>( comparator );
sorted.addAll( options.values() );
addRows( sorted );
return formattedHelpOutput();
}
private String formattedHelpOutput() {
StringBuilder formatted = new StringBuilder();
String nonOptionDisplay = nonOptionRows.render();
if ( !Strings.isNullOrEmpty( nonOptionDisplay ) )
formatted.append( nonOptionDisplay ).append( LINE_SEPARATOR );
formatted.append( optionRows.render() );
return formatted.toString();
}
private void addRows( Collection<? extends OptionDescriptor> options ) {
addNonOptionsDescription( options );
if ( options.isEmpty() )
optionRows.add( "No options specified", "" );
else {
addHeaders( options );
addOptions( options );
}
fitRowsToWidth();
}
private void addNonOptionsDescription( Collection<? extends OptionDescriptor> options ) {
OptionDescriptor nonOptions = findAndRemoveNonOptionsSpec( options );
if ( shouldShowNonOptionArgumentDisplay( nonOptions ) ) {
nonOptionRows.add( "Non-option arguments:", "" );
nonOptionRows.add(createNonOptionArgumentsDisplay(nonOptions), "");
}
}
private boolean shouldShowNonOptionArgumentDisplay( OptionDescriptor nonOptions ) {
return !Strings.isNullOrEmpty( nonOptions.description() )
|| !Strings.isNullOrEmpty( nonOptions.argumentTypeIndicator() )
|| !Strings.isNullOrEmpty( nonOptions.argumentDescription() );
}
private String createNonOptionArgumentsDisplay(OptionDescriptor nonOptions) {
StringBuilder buffer = new StringBuilder();
maybeAppendOptionInfo( buffer, nonOptions );
maybeAppendNonOptionsDescription( buffer, nonOptions );
return buffer.toString();
}
private void maybeAppendNonOptionsDescription( StringBuilder buffer, OptionDescriptor nonOptions ) {
buffer.append( buffer.length() > 0 && !Strings.isNullOrEmpty( nonOptions.description() ) ? " -- " : "" )
.append( nonOptions.description() );
}
private OptionDescriptor findAndRemoveNonOptionsSpec( Collection<? extends OptionDescriptor> options ) {
for ( Iterator<? extends OptionDescriptor> it = options.iterator(); it.hasNext(); ) {
OptionDescriptor next = it.next();
if ( next.representsNonOptions() ) {
it.remove();
return next;
}
}
throw new AssertionError( "no non-options argument spec" );
}
private void addHeaders( Collection<? extends OptionDescriptor> options ) {
if ( hasRequiredOption( options ) ) {
optionRows.add("Option (* = required)", "Description");
optionRows.add("---------------------", "-----------");
} else {
optionRows.add("Option", "Description");
optionRows.add("------", "-----------");
}
}
private boolean hasRequiredOption( Collection<? extends OptionDescriptor> options ) {
for ( OptionDescriptor each : options ) {
if ( each.isRequired() )
return true;
}
return false;
}
private void addOptions( Collection<? extends OptionDescriptor> options ) {
for ( OptionDescriptor each : options ) {
if ( !each.representsNonOptions() )
optionRows.add( createOptionDisplay( each ), createDescriptionDisplay( each ) );
}
}
private String createOptionDisplay( OptionDescriptor descriptor ) {
StringBuilder buffer = new StringBuilder( descriptor.isRequired() ? "* " : "" );
for ( Iterator<String> i = descriptor.options().iterator(); i.hasNext(); ) {
String option = i.next();
buffer.append( option.length() > 1 ? DOUBLE_HYPHEN : HYPHEN );
buffer.append( option );
if ( i.hasNext() )
buffer.append( ", " );
}
maybeAppendOptionInfo( buffer, descriptor );
return buffer.toString();
}
private void maybeAppendOptionInfo( StringBuilder buffer, OptionDescriptor descriptor ) {
String indicator = extractTypeIndicator( descriptor );
String description = descriptor.argumentDescription();
if ( indicator != null || !isNullOrEmpty( description ) )
appendOptionHelp( buffer, indicator, description, descriptor.requiresArgument() );
}
private String extractTypeIndicator( OptionDescriptor descriptor ) {
String indicator = descriptor.argumentTypeIndicator();
if ( !isNullOrEmpty( indicator ) && !String.class.getName().equals( indicator ) )
return shortNameOf( indicator );
return null;
}
private void appendOptionHelp( StringBuilder buffer, String typeIndicator, String description, boolean required ) {
if ( required )
appendTypeIndicator( buffer, typeIndicator, description, '<', '>' );
else
appendTypeIndicator( buffer, typeIndicator, description, '[', ']' );
}
private void appendTypeIndicator( StringBuilder buffer, String typeIndicator, String description,
char start, char end ) {
buffer.append( ' ' ).append( start );
if ( typeIndicator != null )
buffer.append( typeIndicator );
if ( !Strings.isNullOrEmpty( description ) ) {
if ( typeIndicator != null )
buffer.append( ": " );
buffer.append( description );
}
buffer.append( end );
}
private String createDescriptionDisplay( OptionDescriptor descriptor ) {
List<?> defaultValues = descriptor.defaultValues();
if ( defaultValues.isEmpty() )
return descriptor.description();
String defaultValuesDisplay = createDefaultValuesDisplay( defaultValues );
return ( descriptor.description() + ' ' + surround( "default: " + defaultValuesDisplay, '(', ')' ) ).trim();
}
private String createDefaultValuesDisplay( List<?> defaultValues ) {
return defaultValues.size() == 1 ? defaultValues.get( 0 ).toString() : defaultValues.toString();
}
private void fitRowsToWidth() {
nonOptionRows.fitToWidth();
optionRows.fitToWidth();
}
}

View File

@ -0,0 +1,75 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.Map;
/**
* <p>Represents objects charged with taking a set of option descriptions and producing some help text from them.</p>
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public interface HelpFormatter {
/**
* Produces help text, given a set of option descriptors.
*
* @param options descriptors for the configured options of a parser
* @return text to be used as help
* @see OptionParser#printHelpOn(java.io.Writer)
* @see OptionParser#formatHelpWith(HelpFormatter)
*/
String format( Map<String, ? extends OptionDescriptor> options );
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import static java.util.Collections.*;
/**
* Thrown when the option parser is asked to recognize an option with illegal characters in it.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class IllegalOptionSpecificationException extends OptionException {
private static final long serialVersionUID = -1L;
IllegalOptionSpecificationException( String option ) {
super( singletonList( option ) );
}
@Override
public String getMessage() {
return singleOptionMessage() + " is not a legal option character";
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.Collection;
/**
* Thrown when an option is marked as required, but not specified on the command line.
*
* @author <a href="https://github.com/TC1">Emils Solmanis</a>
*/
class MissingRequiredOptionException extends OptionException {
private static final long serialVersionUID = -1L;
protected MissingRequiredOptionException( Collection<String> options ) {
super( options );
}
@Override
public String getMessage() {
return "Missing required option(s) " + multipleOptionMessage();
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.Collection;
/**
* Thrown when asking an {@link OptionSet} for a single argument of an option when many have been specified.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class MultipleArgumentsForOptionException extends OptionException {
private static final long serialVersionUID = -1L;
MultipleArgumentsForOptionException( Collection<String> options ) {
super( options );
}
@Override
public String getMessage() {
return "Found multiple arguments for option " + multipleOptionMessage() + ", but you asked for only one";
}
}

View File

@ -0,0 +1,112 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.Collection;
import java.util.List;
import static java.util.Collections.*;
/**
* A specification for an option that does not accept arguments.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class NoArgumentOptionSpec extends AbstractOptionSpec<Void> {
NoArgumentOptionSpec( String option ) {
this( singletonList( option ), "" );
}
NoArgumentOptionSpec( Collection<String> options, String description ) {
super( options, description );
}
@Override
void handleOption( OptionParser parser, ArgumentList arguments, OptionSet detectedOptions,
String detectedArgument ) {
detectedOptions.add( this );
}
public boolean acceptsArguments() {
return false;
}
public boolean requiresArgument() {
return false;
}
public boolean isRequired() {
return false;
}
public String argumentDescription() {
return "";
}
public String argumentTypeIndicator() {
return "";
}
@Override
protected Void convert( String argument ) {
return null;
}
public List<Void> defaultValues() {
return emptyList();
}
}

View File

@ -0,0 +1,200 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.List;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static jdk.internal.joptsimple.internal.Reflection.*;
/**
* <p>Specification of a command line's non-option arguments.</p>
*
* <p>Instances are returned from {@link OptionParser} methods to allow the formation of parser directives as
* sentences in a "fluent interface" language. For example:</p>
*
* <pre>
* <code>
* OptionParser parser = new OptionParser();
* parser.nonOptions( "files to be processed" ).<strong>ofType( File.class )</strong>;
* </code>
* </pre>
*
* <p>If no methods are invoked on an instance of this class, then that instance's option will treat the non-option
* arguments as {@link String}s.</p>
*
* @param <V> represents the type of the non-option arguments
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public class NonOptionArgumentSpec<V> extends AbstractOptionSpec<V> {
static final String NAME = "[arguments]";
private ValueConverter<V> converter;
private String argumentDescription = "";
NonOptionArgumentSpec() {
this("");
}
NonOptionArgumentSpec( String description ) {
super( asList( NAME ), description );
}
/**
* <p>Specifies a type to which the non-option arguments are to be converted.</p>
*
* <p>JOpt Simple accepts types that have either:</p>
*
* <ol>
* <li>a public static method called {@code valueOf} which accepts a single argument of type {@link String}
* and whose return type is the same as the class on which the method is declared. The {@code java.lang}
* primitive wrapper classes have such methods.</li>
*
* <li>a public constructor which accepts a single argument of type {@link String}.</li>
* </ol>
*
* <p>This class converts arguments using those methods in that order; that is, {@code valueOf} would be invoked
* before a one-{@link String}-arg constructor would.</p>
*
* <p>Invoking this method will trump any previous calls to this method or to
* {@link #withValuesConvertedBy(ValueConverter)}.</p>
*
* @param <T> represents the runtime class of the desired option argument type
* @param argumentType desired type of arguments to this spec's option
* @return self, so that the caller can add clauses to the fluent interface sentence
* @throws NullPointerException if the type is {@code null}
* @throws IllegalArgumentException if the type does not have the standard conversion methods
*/
@SuppressWarnings( "unchecked" )
public <T> NonOptionArgumentSpec<T> ofType( Class<T> argumentType ) {
converter = (ValueConverter<V>) findConverter( argumentType );
return (NonOptionArgumentSpec<T>) this;
}
/**
* <p>Specifies a converter to use to translate non-option arguments into Java objects. This is useful
* when converting to types that do not have the requisite factory method or constructor for
* {@link #ofType(Class)}.</p>
*
* <p>Invoking this method will trump any previous calls to this method or to {@link #ofType(Class)}.
*
* @param <T> represents the runtime class of the desired non-option argument type
* @param aConverter the converter to use
* @return self, so that the caller can add clauses to the fluent interface sentence
* @throws NullPointerException if the converter is {@code null}
*/
@SuppressWarnings( "unchecked" )
public final <T> NonOptionArgumentSpec<T> withValuesConvertedBy( ValueConverter<T> aConverter ) {
if ( aConverter == null )
throw new NullPointerException( "illegal null converter" );
converter = (ValueConverter<V>) aConverter;
return (NonOptionArgumentSpec<T>) this;
}
/**
* <p>Specifies a description for the non-option arguments that this spec represents. This description is used
* when generating help information about the parser.</p>
*
* @param description describes the nature of the argument of this spec's option
* @return self, so that the caller can add clauses to the fluent interface sentence
*/
public NonOptionArgumentSpec<V> describedAs( String description ) {
argumentDescription = description;
return this;
}
@Override
protected final V convert( String argument ) {
return convertWith( converter, argument );
}
@Override
void handleOption( OptionParser parser, ArgumentList arguments, OptionSet detectedOptions,
String detectedArgument ) {
detectedOptions.addWithArgument( this, detectedArgument );
}
public List<?> defaultValues() {
return emptyList();
}
public boolean isRequired() {
return false;
}
public boolean acceptsArguments() {
return false;
}
public boolean requiresArgument() {
return false;
}
public String argumentDescription() {
return argumentDescription;
}
public String argumentTypeIndicator() {
return argumentTypeIndicatorFrom( converter );
}
public boolean representsNonOptions() {
return true;
}
}

View File

@ -0,0 +1,80 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.Collection;
/**
* Thrown when a problem occurs converting an argument of an option from {@link String} to another type.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class OptionArgumentConversionException extends OptionException {
private static final long serialVersionUID = -1L;
private final String argument;
OptionArgumentConversionException( Collection<String> options, String argument, Throwable cause ) {
super( options, cause );
this.argument = argument;
}
@Override
public String getMessage() {
return "Cannot parse argument '" + argument + "' of option " + multipleOptionMessage();
}
}

View File

@ -0,0 +1,135 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.joptsimple;
import java.util.Collection;
/**
* Trains the option parser. This interface aids integration with other code which may expose declaration of options but
* not actual command-line parsing.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
* @see OptionParser
*/
public interface OptionDeclarer {
/**
* Tells the parser to recognize the given option.
*
* <p>This method returns an instance of {@link OptionSpecBuilder} to allow the formation of parser directives
* as sentences in a fluent interface language. For example:</p>
*
* <pre><code>
* OptionDeclarer parser = new OptionParser();
* parser.<strong>accepts( "c" )</strong>.withRequiredArg().ofType( Integer.class );
* </code></pre>
*
* <p>If no methods are invoked on the returned {@link OptionSpecBuilder}, then the parser treats the option as
* accepting no argument.</p>
*
* @param option the option to recognize
* @return an object that can be used to flesh out more detail about the option
* @throws OptionException if the option contains illegal characters
* @throws NullPointerException if the option is {@code null}
*/
OptionSpecBuilder accepts( String option );
/**
* Tells the parser to recognize the given option.
*
* @see #accepts(String)
* @param option the option to recognize
* @param description a string that describes the purpose of the option. This is used when generating help
* information about the parser.
* @return an object that can be used to flesh out more detail about the option
* @throws OptionException if the option contains illegal characters
* @throws NullPointerException if the option is {@code null}
*/
OptionSpecBuilder accepts( String option, String description );
/**
* Tells the parser to recognize the given options, and treat them as synonymous.
*
* @see #accepts(String)
* @param options the options to recognize and treat as synonymous
* @return an object that can be used to flesh out more detail about the options
* @throws OptionException if any of the options contain illegal characters
* @throws NullPointerException if the option list or any of its elements are {@code null}
*/
OptionSpecBuilder acceptsAll( Collection<String> options );
/**
* Tells the parser to recognize the given options, and treat them as synonymous.
*
* @see #acceptsAll(Collection)
* @param options the options to recognize and treat as synonymous
* @param description a string that describes the purpose of the option. This is used when generating help
* information about the parser.
* @return an object that can be used to flesh out more detail about the options
* @throws OptionException if any of the options contain illegal characters
* @throws NullPointerException if the option list or any of its elements are {@code null}
* @throws IllegalArgumentException if the option list is empty
*/
OptionSpecBuilder acceptsAll( Collection<String> options, String description );
/**
* Gives an object that represents an access point for non-option arguments on a command line.
*
* @return an object that can be used to flesh out more detail about the non-option arguments
*/
NonOptionArgumentSpec<String> nonOptions();
/**
* Gives an object that represents an access point for non-option arguments on a command line.
*
* @see #nonOptions()
* @param description a string that describes the purpose of the non-option arguments. This is used when generating
* help information about the parser.
* @return an object that can be used to flesh out more detail about the non-option arguments
*/
NonOptionArgumentSpec<String> nonOptions( String description );
/**
* Tells the parser whether or not to behave "POSIX-ly correct"-ly.
*
* @param setting {@code true} if the parser should behave "POSIX-ly correct"-ly
*/
void posixlyCorrect( boolean setting );
/**
* <p>Tells the parser to treat unrecognized options as non-option arguments.</p>
*
* <p>If not called, then the parser raises an {@link OptionException} when it encounters an unrecognized
* option.</p>
*/
void allowsUnrecognizedOptions();
/**
* Tells the parser either to recognize or ignore <kbd>"-W"</kbd>-style long options.
*
* @param recognize {@code true} if the parser is to recognize the special style of long options
*/
void recognizeAlternativeLongOptions( boolean recognize );
}

View File

@ -0,0 +1,131 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.Collection;
import java.util.List;
/**
* Describes options that an option parser recognizes, in ways that might be useful to {@linkplain HelpFormatter
* help screens}.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public interface OptionDescriptor {
/**
* A set of options that are mutually synonymous.
*
* @return synonymous options
*/
Collection<String> options();
/**
* Description of this option's purpose.
*
* @return a description for the option
*/
String description();
/**
* What values will the option take if none are specified on the command line?
*
* @return any default values for the option
*/
List<?> defaultValues();
/**
* Is this option {@linkplain ArgumentAcceptingOptionSpec#required() required} on a command line?
*
* @return whether the option is required
*/
boolean isRequired();
/**
* Does this option {@linkplain ArgumentAcceptingOptionSpec accept arguments}?
*
* @return whether the option accepts arguments
*/
boolean acceptsArguments();
/**
* Does this option {@linkplain OptionSpecBuilder#withRequiredArg() require an argument}?
*
* @return whether the option requires an argument
*/
boolean requiresArgument();
/**
* Gives a short {@linkplain ArgumentAcceptingOptionSpec#describedAs(String) description} of the option's argument.
*
* @return a description for the option's argument
*/
String argumentDescription();
/**
* Gives an indication of the {@linkplain ArgumentAcceptingOptionSpec#ofType(Class) expected type} of the option's
* argument.
*
* @return a description for the option's argument type
*/
String argumentTypeIndicator();
/**
* Tells whether this object represents the non-option arguments of a command line.
*
* @return {@code true} if this represents non-option arguments
*/
boolean representsNonOptions();
}

View File

@ -0,0 +1,121 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import static java.util.Collections.*;
import static jdk.internal.joptsimple.internal.Strings.*;
/**
* Thrown when a problem occurs during option parsing.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public abstract class OptionException extends RuntimeException {
private static final long serialVersionUID = -1L;
private final List<String> options = new ArrayList<String>();
protected OptionException( Collection<String> options ) {
this.options.addAll( options );
}
protected OptionException( Collection<String> options, Throwable cause ) {
super( cause );
this.options.addAll( options );
}
/**
* Gives the option being considered when the exception was created.
*
* @return the option being considered when the exception was created
*/
public Collection<String> options() {
return unmodifiableCollection( options );
}
protected final String singleOptionMessage() {
return singleOptionMessage( options.get( 0 ) );
}
protected final String singleOptionMessage( String option ) {
return SINGLE_QUOTE + option + SINGLE_QUOTE;
}
protected final String multipleOptionMessage() {
StringBuilder buffer = new StringBuilder( "[" );
for ( Iterator<String> iter = options.iterator(); iter.hasNext(); ) {
buffer.append( singleOptionMessage( iter.next() ) );
if ( iter.hasNext() )
buffer.append( ", " );
}
buffer.append( ']' );
return buffer.toString();
}
static OptionException unrecognizedOption( String option ) {
return new UnrecognizedOptionException( option );
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.Collection;
/**
* Thrown when the option parser discovers an option that requires an argument, but that argument is missing.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class OptionMissingRequiredArgumentException extends OptionException {
private static final long serialVersionUID = -1L;
OptionMissingRequiredArgumentException( Collection<String> options ) {
super( options );
}
@Override
public String getMessage() {
return "Option " + multipleOptionMessage() + " requires an argument";
}
}

View File

@ -0,0 +1,580 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import jdk.internal.joptsimple.internal.AbbreviationMap;
import jdk.internal.joptsimple.util.KeyValuePair;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static java.util.Collections.*;
import static jdk.internal.joptsimple.OptionException.*;
import static jdk.internal.joptsimple.OptionParserState.*;
import static jdk.internal.joptsimple.ParserRules.*;
/**
* <p>Parses command line arguments, using a syntax that attempts to take from the best of POSIX {@code getopt()}
* and GNU {@code getopt_long()}.</p>
*
* <p>This parser supports short options and long options.</p>
*
* <ul>
* <li><dfn>Short options</dfn> begin with a single hyphen ("<kbd>-</kbd>") followed by a single letter or digit,
* or question mark ("<kbd>?</kbd>"), or dot ("<kbd>.</kbd>").</li>
*
* <li>Short options can accept single arguments. The argument can be made required or optional. The option's
* argument can occur:
* <ul>
* <li>in the slot after the option, as in <kbd>-d /tmp</kbd></li>
* <li>right up against the option, as in <kbd>-d/tmp</kbd></li>
* <li>right up against the option separated by an equals sign (<kbd>"="</kbd>), as in <kbd>-d=/tmp</kbd></li>
* </ul>
* To specify <em>n</em> arguments for an option, specify the option <em>n</em> times, once for each argument,
* as in <kbd>-d /tmp -d /var -d /opt</kbd>; or, when using the
* {@linkplain ArgumentAcceptingOptionSpec#withValuesSeparatedBy(char) "separated values"} clause of the "fluent
* interface" (see below), give multiple values separated by a given character as a single argument to the
* option.</li>
*
* <li>Short options can be clustered, so that <kbd>-abc</kbd> is treated as <kbd>-a -b -c</kbd>. If a short option
* in the cluster can accept an argument, the remaining characters are interpreted as the argument for that
* option.</li>
*
* <li>An argument consisting only of two hyphens (<kbd>"--"</kbd>) signals that the remaining arguments are to be
* treated as non-options.</li>
*
* <li>An argument consisting only of a single hyphen is considered a non-option argument (though it can be an
* argument of an option). Many Unix programs treat single hyphens as stand-ins for the standard input or standard
* output streams.</li>
*
* <li><dfn>Long options</dfn> begin with two hyphens (<kbd>"--"</kbd>), followed by multiple letters, digits,
* hyphens, question marks, or dots. A hyphen cannot be the first character of a long option specification when
* configuring the parser.</li>
*
* <li>You can abbreviate long options, so long as the abbreviation is unique.</li>
*
* <li>Long options can accept single arguments. The argument can be made required or optional. The option's
* argument can occur:
* <ul>
* <li>in the slot after the option, as in <kbd>--directory /tmp</kbd></li>
* <li>right up against the option separated by an equals sign (<kbd>"="</kbd>), as in
* <kbd>--directory=/tmp</kbd>
* </ul>
* Specify multiple arguments for a long option in the same manner as for short options (see above).</li>
*
* <li>You can use a single hyphen (<kbd>"-"</kbd>) instead of a double hyphen (<kbd>"--"</kbd>) for a long
* option.</li>
*
* <li>The option <kbd>-W</kbd> is reserved. If you tell the parser to {@linkplain
* #recognizeAlternativeLongOptions(boolean) recognize alternative long options}, then it will treat, for example,
* <kbd>-W foo=bar</kbd> as the long option <kbd>foo</kbd> with argument <kbd>bar</kbd>, as though you had written
* <kbd>--foo=bar</kbd>.</li>
*
* <li>You can specify <kbd>-W</kbd> as a valid short option, or use it as an abbreviation for a long option, but
* {@linkplain #recognizeAlternativeLongOptions(boolean) recognizing alternative long options} will always supersede
* this behavior.</li>
*
* <li>You can specify a given short or long option multiple times on a single command line. The parser collects
* any arguments specified for those options as a list.</li>
*
* <li>If the parser detects an option whose argument is optional, and the next argument "looks like" an option,
* that argument is not treated as the argument to the option, but as a potentially valid option. If, on the other
* hand, the optional argument is typed as a derivative of {@link Number}, then that argument is treated as the
* negative number argument of the option, even if the parser recognizes the corresponding numeric option.
* For example:
* <pre><code>
* OptionParser parser = new OptionParser();
* parser.accepts( "a" ).withOptionalArg().ofType( Integer.class );
* parser.accepts( "2" );
* OptionSet options = parser.parse( "-a", "-2" );
* </code></pre>
* In this case, the option set contains <kbd>"a"</kbd> with argument <kbd>-2</kbd>, not both <kbd>"a"</kbd> and
* <kbd>"2"</kbd>. Swapping the elements in the <em>args</em> array gives the latter.</li>
* </ul>
*
* <p>There are two ways to tell the parser what options to recognize:</p>
*
* <ol>
* <li>A "fluent interface"-style API for specifying options, available since version 2. Sentences in this fluent
* interface language begin with a call to {@link #accepts(String) accepts} or {@link #acceptsAll(Collection)
* acceptsAll} methods; calls on the ensuing chain of objects describe whether the options can take an argument,
* whether the argument is required or optional, to what type arguments of the options should be converted if any,
* etc. Since version 3, these calls return an instance of {@link OptionSpec}, which can subsequently be used to
* retrieve the arguments of the associated option in a type-safe manner.</li>
*
* <li>Since version 1, a more concise way of specifying short options has been to use the special {@linkplain
* #OptionParser(String) constructor}. Arguments of options specified in this manner will be of type {@link String}.
* Here are the rules for the format of the specification strings this constructor accepts:
*
* <ul>
* <li>Any letter or digit is treated as an option character.</li>
*
* <li>An option character can be immediately followed by an asterisk (*) to indicate that the option is a
* "help" option.</li>
*
* <li>If an option character (with possible trailing asterisk) is followed by a single colon (<kbd>":"</kbd>),
* then the option requires an argument.</li>
*
* <li>If an option character (with possible trailing asterisk) is followed by two colons (<kbd>"::"</kbd>),
* then the option accepts an optional argument.</li>
*
* <li>Otherwise, the option character accepts no argument.</li>
*
* <li>If the option specification string begins with a plus sign (<kbd>"+"</kbd>), the parser will behave
* "POSIX-ly correct".</li>
*
* <li>If the option specification string contains the sequence <kbd>"W;"</kbd> (capital W followed by a
* semicolon), the parser will recognize the alternative form of long options.</li>
* </ul>
* </li>
* </ol>
*
* <p>Each of the options in a list of options given to {@link #acceptsAll(Collection) acceptsAll} is treated as a
* synonym of the others. For example:
* <pre>
* <code>
* OptionParser parser = new OptionParser();
* parser.acceptsAll( asList( "w", "interactive", "confirmation" ) );
* OptionSet options = parser.parse( "-w" );
* </code>
* </pre>
* In this case, <code>options.{@link OptionSet#has(String) has}</code> would answer {@code true} when given arguments
* <kbd>"w"</kbd>, <kbd>"interactive"</kbd>, and <kbd>"confirmation"</kbd>. The {@link OptionSet} would give the same
* responses to these arguments for its other methods as well.</p>
*
* <p>By default, as with GNU {@code getopt()}, the parser allows intermixing of options and non-options. If, however,
* the parser has been created to be "POSIX-ly correct", then the first argument that does not look lexically like an
* option, and is not a required argument of a preceding option, signals the end of options. You can still bind
* optional arguments to their options using the abutting (for short options) or <kbd>=</kbd> syntax.</p>
*
* <p>Unlike GNU {@code getopt()}, this parser does not honor the environment variable {@code POSIXLY_CORRECT}.
* "POSIX-ly correct" parsers are configured by either:</p>
*
* <ol>
* <li>using the method {@link #posixlyCorrect(boolean)}, or</li>
*
* <li>using the {@linkplain #OptionParser(String) constructor} with an argument whose first character is a plus sign
* (<kbd>"+"</kbd>)</li>
* </ol>
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
* @see <a href="http://www.gnu.org/software/libc/manual">The GNU C Library</a>
*/
public class OptionParser implements OptionDeclarer {
private final AbbreviationMap<AbstractOptionSpec<?>> recognizedOptions;
private final Map<Collection<String>, Set<OptionSpec<?>>> requiredIf;
private final Map<Collection<String>, Set<OptionSpec<?>>> requiredUnless;
private OptionParserState state;
private boolean posixlyCorrect;
private boolean allowsUnrecognizedOptions;
private HelpFormatter helpFormatter = new BuiltinHelpFormatter();
/**
* Creates an option parser that initially recognizes no options, and does not exhibit "POSIX-ly correct"
* behavior.
*/
public OptionParser() {
recognizedOptions = new AbbreviationMap<AbstractOptionSpec<?>>();
requiredIf = new HashMap<Collection<String>, Set<OptionSpec<?>>>();
requiredUnless = new HashMap<Collection<String>, Set<OptionSpec<?>>>();
state = moreOptions( false );
recognize( new NonOptionArgumentSpec<String>() );
}
/**
* Creates an option parser and configures it to recognize the short options specified in the given string.
*
* Arguments of options specified this way will be of type {@link String}.
*
* @param optionSpecification an option specification
* @throws NullPointerException if {@code optionSpecification} is {@code null}
* @throws OptionException if the option specification contains illegal characters or otherwise cannot be
* recognized
*/
public OptionParser( String optionSpecification ) {
this();
new OptionSpecTokenizer( optionSpecification ).configure( this );
}
public OptionSpecBuilder accepts( String option ) {
return acceptsAll( singletonList( option ) );
}
public OptionSpecBuilder accepts( String option, String description ) {
return acceptsAll( singletonList( option ), description );
}
public OptionSpecBuilder acceptsAll( Collection<String> options ) {
return acceptsAll( options, "" );
}
public OptionSpecBuilder acceptsAll( Collection<String> options, String description ) {
if ( options.isEmpty() )
throw new IllegalArgumentException( "need at least one option" );
ensureLegalOptions( options );
return new OptionSpecBuilder( this, options, description );
}
public NonOptionArgumentSpec<String> nonOptions() {
NonOptionArgumentSpec<String> spec = new NonOptionArgumentSpec<String>();
recognize( spec );
return spec;
}
public NonOptionArgumentSpec<String> nonOptions( String description ) {
NonOptionArgumentSpec<String> spec = new NonOptionArgumentSpec<String>( description );
recognize( spec );
return spec;
}
public void posixlyCorrect( boolean setting ) {
posixlyCorrect = setting;
state = moreOptions( setting );
}
boolean posixlyCorrect() {
return posixlyCorrect;
}
public void allowsUnrecognizedOptions() {
allowsUnrecognizedOptions = true;
}
boolean doesAllowsUnrecognizedOptions() {
return allowsUnrecognizedOptions;
}
public void recognizeAlternativeLongOptions( boolean recognize ) {
if ( recognize )
recognize( new AlternativeLongOptionSpec() );
else
recognizedOptions.remove( String.valueOf( RESERVED_FOR_EXTENSIONS ) );
}
void recognize( AbstractOptionSpec<?> spec ) {
recognizedOptions.putAll( spec.options(), spec );
}
/**
* Writes information about the options this parser recognizes to the given output sink.
*
* The output sink is flushed, but not closed.
*
* @param sink the sink to write information to
* @throws IOException if there is a problem writing to the sink
* @throws NullPointerException if {@code sink} is {@code null}
* @see #printHelpOn(Writer)
*/
public void printHelpOn( OutputStream sink ) throws IOException {
printHelpOn( new OutputStreamWriter( sink ) );
}
/**
* Writes information about the options this parser recognizes to the given output sink.
*
* The output sink is flushed, but not closed.
*
* @param sink the sink to write information to
* @throws IOException if there is a problem writing to the sink
* @throws NullPointerException if {@code sink} is {@code null}
* @see #printHelpOn(OutputStream)
*/
public void printHelpOn( Writer sink ) throws IOException {
sink.write( helpFormatter.format( recognizedOptions.toJavaUtilMap() ) );
sink.flush();
}
/**
* Tells the parser to use the given formatter when asked to {@linkplain #printHelpOn(java.io.Writer) print help}.
*
* @param formatter the formatter to use for printing help
* @throws NullPointerException if the formatter is {@code null}
*/
public void formatHelpWith( HelpFormatter formatter ) {
if ( formatter == null )
throw new NullPointerException();
helpFormatter = formatter;
}
/**
* Retrieves all the options which have been configured for the parser.
*
* @return a {@link Map} containing all the configured options and their corresponding {@link OptionSpec}
*/
public Map<String, OptionSpec<?>> recognizedOptions() {
return new HashMap<String, OptionSpec<?>>( recognizedOptions.toJavaUtilMap() );
}
/**
* Parses the given command line arguments according to the option specifications given to the parser.
*
* @param arguments arguments to parse
* @return an {@link OptionSet} describing the parsed options, their arguments, and any non-option arguments found
* @throws OptionException if problems are detected while parsing
* @throws NullPointerException if the argument list is {@code null}
*/
public OptionSet parse( String... arguments ) {
ArgumentList argumentList = new ArgumentList( arguments );
OptionSet detected = new OptionSet( recognizedOptions.toJavaUtilMap() );
detected.add( recognizedOptions.get( NonOptionArgumentSpec.NAME ) );
while ( argumentList.hasMore() )
state.handleArgument( this, argumentList, detected );
reset();
ensureRequiredOptions( detected );
return detected;
}
private void ensureRequiredOptions( OptionSet options ) {
Collection<String> missingRequiredOptions = missingRequiredOptions( options );
boolean helpOptionPresent = isHelpOptionPresent( options );
if ( !missingRequiredOptions.isEmpty() && !helpOptionPresent )
throw new MissingRequiredOptionException( missingRequiredOptions );
}
private Collection<String> missingRequiredOptions( OptionSet options ) {
Collection<String> missingRequiredOptions = new HashSet<String>();
for ( AbstractOptionSpec<?> each : recognizedOptions.toJavaUtilMap().values() ) {
if ( each.isRequired() && !options.has( each ) )
missingRequiredOptions.addAll( each.options() );
}
for ( Map.Entry<Collection<String>, Set<OptionSpec<?>>> eachEntry : requiredIf.entrySet() ) {
AbstractOptionSpec<?> required = specFor( eachEntry.getKey().iterator().next() );
if ( optionsHasAnyOf( options, eachEntry.getValue() ) && !options.has( required ) ) {
missingRequiredOptions.addAll( required.options() );
}
}
for ( Map.Entry<Collection<String>, Set<OptionSpec<?>>> eachEntry : requiredUnless.entrySet() ) {
AbstractOptionSpec<?> required = specFor( eachEntry.getKey().iterator().next() );
if ( !optionsHasAnyOf( options, eachEntry.getValue() ) && !options.has( required ) ) {
missingRequiredOptions.addAll( required.options() );
}
}
return missingRequiredOptions;
}
private boolean optionsHasAnyOf( OptionSet options, Collection<OptionSpec<?>> specs ) {
for ( OptionSpec<?> each : specs ) {
if ( options.has( each ) )
return true;
}
return false;
}
private boolean isHelpOptionPresent( OptionSet options ) {
boolean helpOptionPresent = false;
for ( AbstractOptionSpec<?> each : recognizedOptions.toJavaUtilMap().values() ) {
if ( each.isForHelp() && options.has( each ) ) {
helpOptionPresent = true;
break;
}
}
return helpOptionPresent;
}
void handleLongOptionToken( String candidate, ArgumentList arguments, OptionSet detected ) {
KeyValuePair optionAndArgument = parseLongOptionWithArgument( candidate );
if ( !isRecognized( optionAndArgument.key ) )
throw unrecognizedOption( optionAndArgument.key );
AbstractOptionSpec<?> optionSpec = specFor( optionAndArgument.key );
optionSpec.handleOption( this, arguments, detected, optionAndArgument.value );
}
void handleShortOptionToken( String candidate, ArgumentList arguments, OptionSet detected ) {
KeyValuePair optionAndArgument = parseShortOptionWithArgument( candidate );
if ( isRecognized( optionAndArgument.key ) ) {
specFor( optionAndArgument.key ).handleOption( this, arguments, detected, optionAndArgument.value );
}
else
handleShortOptionCluster( candidate, arguments, detected );
}
private void handleShortOptionCluster( String candidate, ArgumentList arguments, OptionSet detected ) {
char[] options = extractShortOptionsFrom( candidate );
validateOptionCharacters( options );
for ( int i = 0; i < options.length; i++ ) {
AbstractOptionSpec<?> optionSpec = specFor( options[ i ] );
if ( optionSpec.acceptsArguments() && options.length > i + 1 ) {
String detectedArgument = String.valueOf( options, i + 1, options.length - 1 - i );
optionSpec.handleOption( this, arguments, detected, detectedArgument );
break;
}
optionSpec.handleOption( this, arguments, detected, null );
}
}
void handleNonOptionArgument( String candidate, ArgumentList arguments, OptionSet detectedOptions ) {
specFor( NonOptionArgumentSpec.NAME ).handleOption( this, arguments, detectedOptions, candidate );
}
void noMoreOptions() {
state = OptionParserState.noMoreOptions();
}
boolean looksLikeAnOption( String argument ) {
return isShortOptionToken( argument ) || isLongOptionToken( argument );
}
boolean isRecognized( String option ) {
return recognizedOptions.contains( option );
}
void requiredIf( Collection<String> precedentSynonyms, String required ) {
requiredIf( precedentSynonyms, specFor( required ) );
}
void requiredIf( Collection<String> precedentSynonyms, OptionSpec<?> required ) {
putRequiredOption( precedentSynonyms, required, requiredIf );
}
void requiredUnless( Collection<String> precedentSynonyms, String required ) {
requiredUnless( precedentSynonyms, specFor( required ) );
}
void requiredUnless( Collection<String> precedentSynonyms, OptionSpec<?> required ) {
putRequiredOption( precedentSynonyms, required, requiredUnless );
}
private void putRequiredOption( Collection<String> precedentSynonyms, OptionSpec<?> required,
Map<Collection<String>, Set<OptionSpec<?>>> target ) {
for ( String each : precedentSynonyms ) {
AbstractOptionSpec<?> spec = specFor( each );
if ( spec == null )
throw new UnconfiguredOptionException( precedentSynonyms );
}
Set<OptionSpec<?>> associated = target.get( precedentSynonyms );
if ( associated == null ) {
associated = new HashSet<OptionSpec<?>>();
target.put( precedentSynonyms, associated );
}
associated.add( required );
}
private AbstractOptionSpec<?> specFor( char option ) {
return specFor( String.valueOf( option ) );
}
private AbstractOptionSpec<?> specFor( String option ) {
return recognizedOptions.get( option );
}
private void reset() {
state = moreOptions( posixlyCorrect );
}
private static char[] extractShortOptionsFrom( String argument ) {
char[] options = new char[ argument.length() - 1 ];
argument.getChars( 1, argument.length(), options, 0 );
return options;
}
private void validateOptionCharacters( char[] options ) {
for ( char each : options ) {
String option = String.valueOf( each );
if ( !isRecognized( option ) )
throw unrecognizedOption( option );
if ( specFor( option ).acceptsArguments() )
return;
}
}
private static KeyValuePair parseLongOptionWithArgument( String argument ) {
return KeyValuePair.valueOf( argument.substring( 2 ) );
}
private static KeyValuePair parseShortOptionWithArgument( String argument ) {
return KeyValuePair.valueOf( argument.substring( 1 ) );
}
}

View File

@ -0,0 +1,106 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import static jdk.internal.joptsimple.ParserRules.*;
/**
* Abstraction of parser state; mostly serves to model how a parser behaves depending on whether end-of-options
* has been detected.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
abstract class OptionParserState {
static OptionParserState noMoreOptions() {
return new OptionParserState() {
@Override
protected void handleArgument( OptionParser parser, ArgumentList arguments, OptionSet detectedOptions ) {
parser.handleNonOptionArgument( arguments.next(), arguments, detectedOptions );
}
};
}
static OptionParserState moreOptions( final boolean posixlyCorrect ) {
return new OptionParserState() {
@Override
protected void handleArgument( OptionParser parser, ArgumentList arguments, OptionSet detectedOptions ) {
String candidate = arguments.next();
try {
if ( isOptionTerminator( candidate ) ) {
parser.noMoreOptions();
return;
} else if ( isLongOptionToken( candidate ) ) {
parser.handleLongOptionToken( candidate, arguments, detectedOptions );
return;
} else if ( isShortOptionToken( candidate ) ) {
parser.handleShortOptionToken( candidate, arguments, detectedOptions );
return;
}
} catch ( UnrecognizedOptionException e ) {
if ( !parser.doesAllowsUnrecognizedOptions() )
throw e;
}
if ( posixlyCorrect )
parser.noMoreOptions();
parser.handleNonOptionArgument( candidate, arguments, detectedOptions );
}
};
}
protected abstract void handleArgument( OptionParser parser, ArgumentList arguments, OptionSet detectedOptions );
}

View File

@ -0,0 +1,351 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.*;
import static java.util.Collections.*;
import static jdk.internal.joptsimple.internal.Objects.*;
/**
* Representation of a group of detected command line options, their arguments, and non-option arguments.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public class OptionSet {
private final List<OptionSpec<?>> detectedSpecs;
private final Map<String, AbstractOptionSpec<?>> detectedOptions;
private final Map<AbstractOptionSpec<?>, List<String>> optionsToArguments;
private final Map<String, AbstractOptionSpec<?>> recognizedSpecs;
private final Map<String, List<?>> defaultValues;
/*
* Package-private because clients don't create these.
*/
OptionSet( Map<String, AbstractOptionSpec<?>> recognizedSpecs ) {
detectedSpecs = new ArrayList<OptionSpec<?>>();
detectedOptions = new HashMap<String, AbstractOptionSpec<?>>();
optionsToArguments = new IdentityHashMap<AbstractOptionSpec<?>, List<String>>();
defaultValues = defaultValues( recognizedSpecs );
this.recognizedSpecs = recognizedSpecs;
}
/**
* Tells whether any options were detected.
*
* @return {@code true} if any options were detected
*/
public boolean hasOptions() {
return !detectedOptions.isEmpty();
}
/**
* Tells whether the given option was detected.
*
* @param option the option to search for
* @return {@code true} if the option was detected
* @see #has(OptionSpec)
*/
public boolean has( String option ) {
return detectedOptions.containsKey( option );
}
/**
* Tells whether the given option was detected.
*
* <p>This method recognizes only instances of options returned from the fluent interface methods.</p>
*
* <p>Specifying a {@linkplain ArgumentAcceptingOptionSpec#defaultsTo(Object, Object[])} default argument value}
* for an option does not cause this method to return {@code true} if the option was not detected on the command
* line.</p>
*
* @param option the option to search for
* @return {@code true} if the option was detected
* @see #has(String)
*/
public boolean has( OptionSpec<?> option ) {
return optionsToArguments.containsKey( option );
}
/**
* Tells whether there are any arguments associated with the given option.
*
* @param option the option to search for
* @return {@code true} if the option was detected and at least one argument was detected for the option
* @see #hasArgument(OptionSpec)
*/
public boolean hasArgument( String option ) {
AbstractOptionSpec<?> spec = detectedOptions.get( option );
return spec != null && hasArgument( spec );
}
/**
* Tells whether there are any arguments associated with the given option.
*
* <p>This method recognizes only instances of options returned from the fluent interface methods.</p>
*
* <p>Specifying a {@linkplain ArgumentAcceptingOptionSpec#defaultsTo(Object, Object[]) default argument value}
* for an option does not cause this method to return {@code true} if the option was not detected on the command
* line, or if the option can take an optional argument but did not have one on the command line.</p>
*
* @param option the option to search for
* @return {@code true} if the option was detected and at least one argument was detected for the option
* @throws NullPointerException if {@code option} is {@code null}
* @see #hasArgument(String)
*/
public boolean hasArgument( OptionSpec<?> option ) {
ensureNotNull( option );
List<String> values = optionsToArguments.get( option );
return values != null && !values.isEmpty();
}
/**
* Gives the argument associated with the given option. If the option was given an argument type, the argument
* will take on that type; otherwise, it will be a {@link String}.
*
* <p>Specifying a {@linkplain ArgumentAcceptingOptionSpec#defaultsTo(Object, Object[]) default argument value}
* for an option will cause this method to return that default value even if the option was not detected on the
* command line, or if the option can take an optional argument but did not have one on the command line.</p>
*
* @param option the option to search for
* @return the argument of the given option; {@code null} if no argument is present, or that option was not
* detected
* @throws NullPointerException if {@code option} is {@code null}
* @throws OptionException if more than one argument was detected for the option
*/
public Object valueOf( String option ) {
ensureNotNull( option );
AbstractOptionSpec<?> spec = detectedOptions.get( option );
if ( spec == null ) {
List<?> defaults = defaultValuesFor( option );
return defaults.isEmpty() ? null : defaults.get( 0 );
}
return valueOf( spec );
}
/**
* Gives the argument associated with the given option.
*
* <p>This method recognizes only instances of options returned from the fluent interface methods.</p>
*
* @param <V> represents the type of the arguments the given option accepts
* @param option the option to search for
* @return the argument of the given option; {@code null} if no argument is present, or that option was not
* detected
* @throws OptionException if more than one argument was detected for the option
* @throws NullPointerException if {@code option} is {@code null}
* @throws ClassCastException if the arguments of this option are not of the expected type
*/
public <V> V valueOf( OptionSpec<V> option ) {
ensureNotNull( option );
List<V> values = valuesOf( option );
switch ( values.size() ) {
case 0:
return null;
case 1:
return values.get( 0 );
default:
throw new MultipleArgumentsForOptionException( option.options() );
}
}
/**
* <p>Gives any arguments associated with the given option. If the option was given an argument type, the
* arguments will take on that type; otherwise, they will be {@link String}s.</p>
*
* @param option the option to search for
* @return the arguments associated with the option, as a list of objects of the type given to the arguments; an
* empty list if no such arguments are present, or if the option was not detected
* @throws NullPointerException if {@code option} is {@code null}
*/
public List<?> valuesOf( String option ) {
ensureNotNull( option );
AbstractOptionSpec<?> spec = detectedOptions.get( option );
return spec == null ? defaultValuesFor( option ) : valuesOf( spec );
}
/**
* <p>Gives any arguments associated with the given option. If the option was given an argument type, the
* arguments will take on that type; otherwise, they will be {@link String}s.</p>
*
* <p>This method recognizes only instances of options returned from the fluent interface methods.</p>
*
* @param <V> represents the type of the arguments the given option accepts
* @param option the option to search for
* @return the arguments associated with the option; an empty list if no such arguments are present, or if the
* option was not detected
* @throws NullPointerException if {@code option} is {@code null}
* @throws OptionException if there is a problem converting the option's arguments to the desired type; for
* example, if the type does not implement a correct conversion constructor or method
*/
public <V> List<V> valuesOf( OptionSpec<V> option ) {
ensureNotNull( option );
List<String> values = optionsToArguments.get( option );
if ( values == null || values.isEmpty() )
return defaultValueFor( option );
AbstractOptionSpec<V> spec = (AbstractOptionSpec<V>) option;
List<V> convertedValues = new ArrayList<V>();
for ( String each : values )
convertedValues.add( spec.convert( each ) );
return unmodifiableList( convertedValues );
}
/**
* Gives the set of options that were detected, in the form of {@linkplain OptionSpec}s, in the order in which the
* options were found on the command line.
*
* @return the set of detected command line options
*/
public List<OptionSpec<?>> specs() {
List<OptionSpec<?>> specs = detectedSpecs;
specs.remove( detectedOptions.get( NonOptionArgumentSpec.NAME ) );
return unmodifiableList( specs );
}
/**
* Gives all declared options as a map of string to {@linkplain OptionSpec}.
*
* @return the declared options as a map
*/
public Map<OptionSpec<?>, List<?>> asMap() {
Map<OptionSpec<?>, List<?>> map = new HashMap<OptionSpec<?>, List<?>>();
for ( AbstractOptionSpec<?> spec : recognizedSpecs.values() )
if ( !spec.representsNonOptions() )
map.put( spec, valuesOf( spec ) );
return unmodifiableMap( map );
}
/**
* @return the detected non-option arguments
*/
public List<?> nonOptionArguments() {
return unmodifiableList( valuesOf( detectedOptions.get( NonOptionArgumentSpec.NAME ) ) );
}
void add( AbstractOptionSpec<?> spec ) {
addWithArgument( spec, null );
}
void addWithArgument( AbstractOptionSpec<?> spec, String argument ) {
detectedSpecs.add( spec );
for ( String each : spec.options() )
detectedOptions.put( each, spec );
List<String> optionArguments = optionsToArguments.get( spec );
if ( optionArguments == null ) {
optionArguments = new ArrayList<String>();
optionsToArguments.put( spec, optionArguments );
}
if ( argument != null )
optionArguments.add( argument );
}
@Override
public boolean equals( Object that ) {
if ( this == that )
return true;
if ( that == null || !getClass().equals( that.getClass() ) )
return false;
OptionSet other = (OptionSet) that;
Map<AbstractOptionSpec<?>, List<String>> thisOptionsToArguments =
new HashMap<AbstractOptionSpec<?>, List<String>>( optionsToArguments );
Map<AbstractOptionSpec<?>, List<String>> otherOptionsToArguments =
new HashMap<AbstractOptionSpec<?>, List<String>>( other.optionsToArguments );
return detectedOptions.equals( other.detectedOptions )
&& thisOptionsToArguments.equals( otherOptionsToArguments );
}
@Override
public int hashCode() {
Map<AbstractOptionSpec<?>, List<String>> thisOptionsToArguments =
new HashMap<AbstractOptionSpec<?>, List<String>>( optionsToArguments );
return detectedOptions.hashCode() ^ thisOptionsToArguments.hashCode();
}
@SuppressWarnings( "unchecked" )
private <V> List<V> defaultValuesFor( String option ) {
if ( defaultValues.containsKey( option ) )
return (List<V>) defaultValues.get( option );
return emptyList();
}
private <V> List<V> defaultValueFor( OptionSpec<V> option ) {
return defaultValuesFor( option.options().iterator().next() );
}
private static Map<String, List<?>> defaultValues( Map<String, AbstractOptionSpec<?>> recognizedSpecs ) {
Map<String, List<?>> defaults = new HashMap<String, List<?>>();
for ( Map.Entry<String, AbstractOptionSpec<?>> each : recognizedSpecs.entrySet() )
defaults.put( each.getKey(), each.getValue().defaultValues() );
return defaults;
}
}

View File

@ -0,0 +1,128 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.Collection;
import java.util.List;
/**
* Describes options that an option parser recognizes.
*
* <p>Instances of this interface are returned by the "fluent interface" methods to allow retrieval of option arguments
* in a type-safe manner. Here's an example:</p>
*
* <pre><code>
* OptionParser parser = new OptionParser();
* <strong>OptionSpec&lt;Integer&gt;</strong> count =
* parser.accepts( "count" ).withRequiredArg().ofType( Integer.class );
* OptionSet options = parser.parse( "--count", "2" );
* assert options.has( count );
* int countValue = options.valueOf( count );
* assert countValue == count.value( options );
* List&lt;Integer&gt; countValues = options.valuesOf( count );
* assert countValues.equals( count.values( options ) );
* </code></pre>
*
* @param <V> represents the type of the arguments this option accepts
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public interface OptionSpec<V> {
/**
* Gives any arguments associated with the given option in the given set of detected options.
*
* <p>Specifying a {@linkplain ArgumentAcceptingOptionSpec#defaultsTo(Object, Object[]) default argument value}
* for this option will cause this method to return that default value even if this option was not detected on the
* command line, or if this option can take an optional argument but did not have one on the command line.</p>
*
* @param detectedOptions the detected options to search in
* @return the arguments associated with this option; an empty list if no such arguments are present, or if this
* option was not detected
* @throws OptionException if there is a problem converting this option's arguments to the desired type; for
* example, if the type does not implement a correct conversion constructor or method
* @throws NullPointerException if {@code detectedOptions} is {@code null}
* @see OptionSet#valuesOf(OptionSpec)
*/
List<V> values( OptionSet detectedOptions );
/**
* Gives the argument associated with the given option in the given set of detected options.
*
* <p>Specifying a {@linkplain ArgumentAcceptingOptionSpec#defaultsTo(Object, Object[]) default argument value}
* for this option will cause this method to return that default value even if this option was not detected on the
* command line, or if this option can take an optional argument but did not have one on the command line.</p>
*
* @param detectedOptions the detected options to search in
* @return the argument of the this option; {@code null} if no argument is present, or that option was not detected
* @throws OptionException if more than one argument was detected for the option
* @throws NullPointerException if {@code detectedOptions} is {@code null}
* @throws ClassCastException if the arguments of this option are not of the expected type
* @see OptionSet#valueOf(OptionSpec)
*/
V value( OptionSet detectedOptions );
/**
* @return the string representations of this option
*/
Collection<String> options();
/**
* Tells whether this option is designated as a "help" option. The presence of a "help" option on a command line
* means that missing "required" options will not cause parsing to fail.
*
* @return whether this option is designated as a "help" option
*/
boolean isForHelp();
}

View File

@ -0,0 +1,225 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Allows callers to specify whether a given option accepts arguments (required or optional).
*
* <p>Instances are returned from {@link OptionParser#accepts(String)} to allow the formation of parser directives as
* sentences in a "fluent interface" language. For example:</p>
*
* <pre><code>
* OptionParser parser = new OptionParser();
* parser.accepts( "c" ).<strong>withRequiredArg()</strong>.ofType( Integer.class );
* </code></pre>
*
* <p>If no methods are invoked on an instance of this class, then that instance's option will accept no argument.</p>
*
* <p>Note that you should not use the fluent interface clauses in a way that would defeat the typing of option
* arguments:</p>
*
* <pre><code>
* OptionParser parser = new OptionParser();
* ArgumentAcceptingOptionSpec&lt;String&gt; optionC =
* parser.accepts( "c" ).withRequiredArg();
* <strong>optionC.ofType( Integer.class ); // DON'T THROW AWAY THE TYPE!</strong>
*
* String value = parser.parse( "-c", "2" ).valueOf( optionC ); // ClassCastException
* </code></pre>
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public class OptionSpecBuilder extends NoArgumentOptionSpec {
private final OptionParser parser;
OptionSpecBuilder( OptionParser parser, Collection<String> options, String description ) {
super( options, description );
this.parser = parser;
attachToParser();
}
private void attachToParser() {
parser.recognize( this );
}
/**
* Informs an option parser that this builder's option requires an argument.
*
* @return a specification for the option
*/
public ArgumentAcceptingOptionSpec<String> withRequiredArg() {
ArgumentAcceptingOptionSpec<String> newSpec =
new RequiredArgumentOptionSpec<String>( options(), description() );
parser.recognize( newSpec );
return newSpec;
}
/**
* Informs an option parser that this builder's option accepts an optional argument.
*
* @return a specification for the option
*/
public ArgumentAcceptingOptionSpec<String> withOptionalArg() {
ArgumentAcceptingOptionSpec<String> newSpec =
new OptionalArgumentOptionSpec<String>( options(), description() );
parser.recognize( newSpec );
return newSpec;
}
/**
* <p>Informs an option parser that this builder's option is required if the given option is present on the command
* line.</p>
*
* <p>For a given option, you <em>should not</em> mix this with {@link #requiredUnless(String, String...)
* requiredUnless} to avoid conflicts.</p>
*
* @param dependent an option whose presence on a command line makes this builder's option required
* @param otherDependents other options whose presence on a command line makes this builder's option required
* @return self, so that the caller can add clauses to the fluent interface sentence
* @throws OptionException if any of the dependent options haven't been configured in the parser yet
*/
public OptionSpecBuilder requiredIf( String dependent, String... otherDependents ) {
List<String> dependents = validatedDependents( dependent, otherDependents );
for ( String each : dependents ) {
parser.requiredIf( options(), each );
}
return this;
}
/**
* <p>Informs an option parser that this builder's option is required if the given option is present on the command
* line.</p>
*
* <p>For a given option, you <em>should not</em> mix this with {@link #requiredUnless(OptionSpec, OptionSpec[])
* requiredUnless} to avoid conflicts.</p>
*
* <p>This method recognizes only instances of options returned from the fluent interface methods.</p>
*
* @param dependent the option whose presence on a command line makes this builder's option required
* @param otherDependents other options whose presence on a command line makes this builder's option required
* @return self, so that the caller can add clauses to the fluent interface sentence
*/
public OptionSpecBuilder requiredIf( OptionSpec<?> dependent, OptionSpec<?>... otherDependents ) {
parser.requiredIf( options(), dependent );
for ( OptionSpec<?> each : otherDependents )
parser.requiredIf( options(), each );
return this;
}
/**
* <p>Informs an option parser that this builder's option is required if the given option is absent on the command
* line.</p>
*
* <p>For a given option, you <em>should not</em> mix this with {@link #requiredIf(OptionSpec, OptionSpec[])
* requiredIf} to avoid conflicts.</p>
*
* @param dependent an option whose absence on a command line makes this builder's option required
* @param otherDependents other options whose absence on a command line makes this builder's option required
* @return self, so that the caller can add clauses to the fluent interface sentence
* @throws OptionException if any of the dependent options haven't been configured in the parser yet
*/
public OptionSpecBuilder requiredUnless( String dependent, String... otherDependents ) {
List<String> dependents = validatedDependents( dependent, otherDependents );
for ( String each : dependents ) {
parser.requiredUnless( options(), each );
}
return this;
}
/**
* <p>Informs an option parser that this builder's option is required if the given option is absent on the command
* line.</p>
*
* <p>For a given option, you <em>should not</em> mix this with {@link #requiredIf(OptionSpec, OptionSpec[])
* requiredIf} to avoid conflicts.</p>
*
* <p>This method recognizes only instances of options returned from the fluent interface methods.</p>
*
* @param dependent the option whose absence on a command line makes this builder's option required
* @param otherDependents other options whose absence on a command line makes this builder's option required
* @return self, so that the caller can add clauses to the fluent interface sentence
*/
public OptionSpecBuilder requiredUnless( OptionSpec<?> dependent, OptionSpec<?>... otherDependents ) {
parser.requiredUnless( options(), dependent );
for ( OptionSpec<?> each : otherDependents )
parser.requiredUnless( options(), each );
return this;
}
private List<String> validatedDependents( String dependent, String... otherDependents ) {
List<String> dependents = new ArrayList<String>();
dependents.add( dependent );
Collections.addAll( dependents, otherDependents );
for ( String each : dependents ) {
if ( !parser.isRecognized( each ) )
throw new UnconfiguredOptionException( each );
}
return dependents;
}
}

View File

@ -0,0 +1,156 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.NoSuchElementException;
import static jdk.internal.joptsimple.ParserRules.*;
/**
* Tokenizes a short option specification string.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class OptionSpecTokenizer {
private static final char POSIXLY_CORRECT_MARKER = '+';
private static final char HELP_MARKER = '*';
private String specification;
private int index;
OptionSpecTokenizer( String specification ) {
if ( specification == null )
throw new NullPointerException( "null option specification" );
this.specification = specification;
}
boolean hasMore() {
return index < specification.length();
}
AbstractOptionSpec<?> next() {
if ( !hasMore() )
throw new NoSuchElementException();
String optionCandidate = String.valueOf( specification.charAt( index ) );
index++;
AbstractOptionSpec<?> spec;
if ( RESERVED_FOR_EXTENSIONS.equals( optionCandidate ) ) {
spec = handleReservedForExtensionsToken();
if ( spec != null )
return spec;
}
ensureLegalOption( optionCandidate );
if ( hasMore() ) {
boolean forHelp = false;
if ( specification.charAt( index ) == HELP_MARKER ) {
forHelp = true;
++index;
}
spec = hasMore() && specification.charAt( index ) == ':'
? handleArgumentAcceptingOption( optionCandidate )
: new NoArgumentOptionSpec( optionCandidate );
if ( forHelp )
spec.forHelp();
} else
spec = new NoArgumentOptionSpec( optionCandidate );
return spec;
}
void configure( OptionParser parser ) {
adjustForPosixlyCorrect( parser );
while ( hasMore() )
parser.recognize( next() );
}
private void adjustForPosixlyCorrect( OptionParser parser ) {
if ( POSIXLY_CORRECT_MARKER == specification.charAt( 0 ) ) {
parser.posixlyCorrect( true );
specification = specification.substring( 1 );
}
}
private AbstractOptionSpec<?> handleReservedForExtensionsToken() {
if ( !hasMore() )
return new NoArgumentOptionSpec( RESERVED_FOR_EXTENSIONS );
if ( specification.charAt( index ) == ';' ) {
++index;
return new AlternativeLongOptionSpec();
}
return null;
}
private AbstractOptionSpec<?> handleArgumentAcceptingOption( String candidate ) {
index++;
if ( hasMore() && specification.charAt( index ) == ':' ) {
index++;
return new OptionalArgumentOptionSpec<String>( candidate );
}
return new RequiredArgumentOptionSpec<String>( candidate );
}
}

View File

@ -0,0 +1,99 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.Collection;
/**
* Specification of an option that accepts an optional argument.
*
* @param <V> represents the type of the arguments this option accepts
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class OptionalArgumentOptionSpec<V> extends ArgumentAcceptingOptionSpec<V> {
OptionalArgumentOptionSpec( String option ) {
super( option, false );
}
OptionalArgumentOptionSpec( Collection<String> options, String description ) {
super( options, false, description );
}
@Override
protected void detectOptionArgument( OptionParser parser, ArgumentList arguments, OptionSet detectedOptions ) {
if ( arguments.hasMore() ) {
String nextArgument = arguments.peek();
if ( !parser.looksLikeAnOption( nextArgument ) )
handleOptionArgument( parser, detectedOptions, arguments );
else if ( isArgumentOfNumberType() && canConvertArgument( nextArgument ) )
addArguments( detectedOptions, arguments.next() );
else
detectedOptions.add( this );
}
else
detectedOptions.add( this );
}
private void handleOptionArgument( OptionParser parser, OptionSet detectedOptions, ArgumentList arguments ) {
if ( parser.posixlyCorrect() ) {
detectedOptions.add( this );
parser.noMoreOptions();
}
else
addArguments( detectedOptions, arguments.next() );
}
}

View File

@ -0,0 +1,114 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.Collection;
import static java.lang.Character.*;
/**
* Can tell whether or not options are well-formed.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
final class ParserRules {
static final char HYPHEN_CHAR = '-';
static final String HYPHEN = String.valueOf( HYPHEN_CHAR );
static final String DOUBLE_HYPHEN = "--";
static final String OPTION_TERMINATOR = DOUBLE_HYPHEN;
static final String RESERVED_FOR_EXTENSIONS = "W";
private ParserRules() {
throw new UnsupportedOperationException();
}
static boolean isShortOptionToken( String argument ) {
return argument.startsWith( HYPHEN )
&& !HYPHEN.equals( argument )
&& !isLongOptionToken( argument );
}
static boolean isLongOptionToken( String argument ) {
return argument.startsWith( DOUBLE_HYPHEN ) && !isOptionTerminator( argument );
}
static boolean isOptionTerminator( String argument ) {
return OPTION_TERMINATOR.equals( argument );
}
static void ensureLegalOption( String option ) {
if ( option.startsWith( HYPHEN ) )
throw new IllegalOptionSpecificationException( String.valueOf( option ) );
for ( int i = 0; i < option.length(); ++i )
ensureLegalOptionCharacter( option.charAt( i ) );
}
static void ensureLegalOptions( Collection<String> options ) {
for ( String each : options )
ensureLegalOption( each );
}
private static void ensureLegalOptionCharacter( char option ) {
if ( !( isLetterOrDigit( option ) || isAllowedPunctuation( option ) ) )
throw new IllegalOptionSpecificationException( String.valueOf( option ) );
}
private static boolean isAllowedPunctuation( char option ) {
String allowedPunctuation = "?." + HYPHEN_CHAR;
return allowedPunctuation.indexOf( option ) != -1;
}
}

View File

@ -0,0 +1,3 @@
JOpt Simple, Version 4.6
https://pholser.github.io/jopt-simple/

View File

@ -0,0 +1,82 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.Collection;
/**
* Specification of an option that accepts a required argument.
*
* @param <V> represents the type of the arguments this option accepts
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class RequiredArgumentOptionSpec<V> extends ArgumentAcceptingOptionSpec<V> {
RequiredArgumentOptionSpec( String option ) {
super( option, true );
}
RequiredArgumentOptionSpec( Collection<String> options, String description ) {
super( options, true, description );
}
@Override
protected void detectOptionArgument( OptionParser parser, ArgumentList arguments, OptionSet detectedOptions ) {
if ( !arguments.hasMore() )
throw new OptionMissingRequiredArgumentException( options() );
addArguments( detectedOptions, arguments.next() );
}
}

View File

@ -0,0 +1,84 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import static java.util.Collections.*;
/**
* Thrown when the option parser detects an unacceptable number of {@code linkplain NonOptionArgumentSpec
* non-option arguments}.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class UnacceptableNumberOfNonOptionsException extends OptionException {
private static final long serialVersionUID = -1L;
private final int minimum;
private final int maximum;
private final int actual;
UnacceptableNumberOfNonOptionsException( int minimum, int maximum, int actual ) {
super( singletonList( NonOptionArgumentSpec.NAME ) );
this.minimum = minimum;
this.maximum = maximum;
this.actual = actual;
}
@Override
public String getMessage() {
return String.format( "actual = %d, minimum = %d, maximum = %d", actual, minimum, maximum );
}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import java.util.Collection;
import static java.util.Collections.*;
/**
* Thrown when an option parser refers to an option that is not in fact configured already on the parser.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class UnconfiguredOptionException extends OptionException {
private static final long serialVersionUID = -1L;
UnconfiguredOptionException( String option ) {
this( singletonList( option ) );
}
UnconfiguredOptionException( Collection<String> options ) {
super( options );
}
@Override
public String getMessage() {
return "Option " + multipleOptionMessage() + " has not been configured on this parser";
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
import static java.util.Collections.*;
/**
* Thrown when the option parser encounters an unrecognized option.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class UnrecognizedOptionException extends OptionException {
private static final long serialVersionUID = -1L;
UnrecognizedOptionException( String option ) {
super( singletonList( option ) );
}
@Override
public String getMessage() {
return singleOptionMessage() + " is not a recognized option";
}
}

View File

@ -0,0 +1,84 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
/**
* Thrown by {@link ValueConverter}s when problems occur in converting string values to other Java types.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public class ValueConversionException extends RuntimeException {
private static final long serialVersionUID = -1L;
/**
* Creates a new exception with the specified detail message.
*
* @param message the detail message
*/
public ValueConversionException( String message ) {
this( message, null );
}
/**
* Creates a new exception with the specified detail message and cause.
*
* @param message the detail message
* @param cause the original exception
*/
public ValueConversionException( String message, Throwable cause ) {
super( message, cause );
}
}

View File

@ -0,0 +1,88 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple;
/**
* Instances of this interface are used to convert arguments of options into specific Java types.
*
* @param <V> constraint on the type of values being converted to
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public interface ValueConverter<V> {
/**
* Converts the given string value into a Java type.
*
* @param value the string to convert
* @return the converted value
* @throws ValueConversionException if a problem occurs while converting the value
*/
V convert( String value );
/**
* Gives the class of the type of values this converter converts to.
*
* @return the target class for conversion
*/
Class<V> valueType();
/**
* Gives a string that describes the pattern of the values this converter expects, if any. For example, a date
* converter can respond with a {@link java.text.SimpleDateFormat date format string}.
*
* @return a value pattern, or {@code null} if there's nothing interesting here
*/
String valuePattern();
}

View File

@ -0,0 +1,264 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.internal;
import java.util.Map;
import java.util.TreeMap;
/**
* <p>A map whose keys are strings; when a key/value pair is added to the map, the longest unique abbreviations of that
* key are added as well, and associated with the value. Thus:</p>
*
* <pre>
* <code>
* abbreviations.put( "good", "bye" );
* </code>
* </pre>
*
* <p>would make it such that you could retrieve the value {@code "bye"} from the map using the keys {@code "good"},
* {@code "goo"}, {@code "go"}, and {@code "g"}. A subsequent invocation of:</p>
* <pre>
* <code>
* abbreviations.put( "go", "fish" );
* </code>
* </pre>
*
* <p>would make it such that you could retrieve the value {@code "bye"} using the keys {@code "good"} and
* {@code "goo"}, and the value {@code "fish"} using the key {@code "go"}. The key {@code "g"} would yield
* {@code null}, since it would no longer be a unique abbreviation.</p>
*
* <p>The data structure is much like a "trie".</p>
*
* @param <V> a constraint on the types of the values in the map
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
* @see <a href="http://www.perldoc.com/perl5.8.0/lib/Text/Abbrev.html">Perl's Text::Abbrev module</a>
*/
public class AbbreviationMap<V> {
private String key;
private V value;
private final Map<Character, AbbreviationMap<V>> children = new TreeMap<Character, AbbreviationMap<V>>();
private int keysBeyond;
/**
* <p>Tells whether the given key is in the map, or whether the given key is a unique
* abbreviation of a key that is in the map.</p>
*
* @param aKey key to look up
* @return {@code true} if {@code key} is present in the map
* @throws NullPointerException if {@code key} is {@code null}
*/
public boolean contains( String aKey ) {
return get( aKey ) != null;
}
/**
* <p>Answers the value associated with the given key. The key can be a unique
* abbreviation of a key that is in the map. </p>
*
* @param aKey key to look up
* @return the value associated with {@code aKey}; or {@code null} if there is no
* such value or {@code aKey} is not a unique abbreviation of a key in the map
* @throws NullPointerException if {@code aKey} is {@code null}
*/
public V get( String aKey ) {
char[] chars = charsOf( aKey );
AbbreviationMap<V> child = this;
for ( char each : chars ) {
child = child.children.get( each );
if ( child == null )
return null;
}
return child.value;
}
/**
* <p>Associates a given value with a given key. If there was a previous
* association, the old value is replaced with the new one.</p>
*
* @param aKey key to create in the map
* @param newValue value to associate with the key
* @throws NullPointerException if {@code aKey} or {@code newValue} is {@code null}
* @throws IllegalArgumentException if {@code aKey} is a zero-length string
*/
public void put( String aKey, V newValue ) {
if ( newValue == null )
throw new NullPointerException();
if ( aKey.length() == 0 )
throw new IllegalArgumentException();
char[] chars = charsOf( aKey );
add( chars, newValue, 0, chars.length );
}
/**
* <p>Associates a given value with a given set of keys. If there was a previous
* association, the old value is replaced with the new one.</p>
*
* @param keys keys to create in the map
* @param newValue value to associate with the key
* @throws NullPointerException if {@code keys} or {@code newValue} is {@code null}
* @throws IllegalArgumentException if any of {@code keys} is a zero-length string
*/
public void putAll( Iterable<String> keys, V newValue ) {
for ( String each : keys )
put( each, newValue );
}
private boolean add( char[] chars, V newValue, int offset, int length ) {
if ( offset == length ) {
value = newValue;
boolean wasAlreadyAKey = key != null;
key = new String( chars );
return !wasAlreadyAKey;
}
char nextChar = chars[ offset ];
AbbreviationMap<V> child = children.get( nextChar );
if ( child == null ) {
child = new AbbreviationMap<V>();
children.put( nextChar, child );
}
boolean newKeyAdded = child.add( chars, newValue, offset + 1, length );
if ( newKeyAdded )
++keysBeyond;
if ( key == null )
value = keysBeyond > 1 ? null : newValue;
return newKeyAdded;
}
/**
* <p>If the map contains the given key, dissociates the key from its value.</p>
*
* @param aKey key to remove
* @throws NullPointerException if {@code aKey} is {@code null}
* @throws IllegalArgumentException if {@code aKey} is a zero-length string
*/
public void remove( String aKey ) {
if ( aKey.length() == 0 )
throw new IllegalArgumentException();
char[] keyChars = charsOf( aKey );
remove( keyChars, 0, keyChars.length );
}
private boolean remove( char[] aKey, int offset, int length ) {
if ( offset == length )
return removeAtEndOfKey();
char nextChar = aKey[ offset ];
AbbreviationMap<V> child = children.get( nextChar );
if ( child == null || !child.remove( aKey, offset + 1, length ) )
return false;
--keysBeyond;
if ( child.keysBeyond == 0 )
children.remove( nextChar );
if ( keysBeyond == 1 && key == null )
setValueToThatOfOnlyChild();
return true;
}
private void setValueToThatOfOnlyChild() {
Map.Entry<Character, AbbreviationMap<V>> entry = children.entrySet().iterator().next();
AbbreviationMap<V> onlyChild = entry.getValue();
value = onlyChild.value;
}
private boolean removeAtEndOfKey() {
if ( key == null )
return false;
key = null;
if ( keysBeyond == 1 )
setValueToThatOfOnlyChild();
else
value = null;
return true;
}
/**
* Gives a Java map representation of this abbreviation map.
*
* @return a Java map corresponding to this abbreviation map
*/
public Map<String, V> toJavaUtilMap() {
Map<String, V> mappings = new TreeMap<String, V>();
addToMappings( mappings );
return mappings;
}
private void addToMappings( Map<String, V> mappings ) {
if ( key != null )
mappings.put( key, value );
for ( AbbreviationMap<V> each : children.values() )
each.addToMappings( mappings );
}
private static char[] charsOf( String aKey ) {
char[] chars = new char[ aKey.length() ];
aKey.getChars( 0, aKey.length(), chars, 0 );
return chars;
}
}

View File

@ -0,0 +1,105 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.internal;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public final class Classes {
private static final Map<Class<?>, Class<?>> WRAPPERS = new HashMap<Class<?>, Class<?>>( 13 );
static {
WRAPPERS.put( boolean.class, Boolean.class );
WRAPPERS.put( byte.class, Byte.class );
WRAPPERS.put( char.class, Character.class );
WRAPPERS.put( double.class, Double.class );
WRAPPERS.put( float.class, Float.class );
WRAPPERS.put( int.class, Integer.class );
WRAPPERS.put( long.class, Long.class );
WRAPPERS.put( short.class, Short.class );
WRAPPERS.put( void.class, Void.class );
}
private Classes() {
throw new UnsupportedOperationException();
}
/**
* Gives the "short version" of the given class name. Somewhat naive to inner classes.
*
* @param className class name to chew on
* @return the short name of the class
*/
public static String shortNameOf( String className ) {
return className.substring( className.lastIndexOf( '.' ) + 1 );
}
/**
* Gives the primitive wrapper class for the given class. If the given class is not
* {@linkplain Class#isPrimitive() primitive}, returns the class itself.
*
* @param <T> generic class type
* @param clazz the class to check
* @return primitive wrapper type if {@code clazz} is primitive, otherwise {@code clazz}
*/
@SuppressWarnings( "unchecked" )
public static <T> Class<T> wrapperOf( Class<T> clazz ) {
return clazz.isPrimitive() ? (Class<T>) WRAPPERS.get( clazz ) : clazz;
}
}

View File

@ -0,0 +1,137 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.internal;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static java.text.BreakIterator.*;
import static jdk.internal.joptsimple.internal.Strings.*;
/**
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class Columns {
private static final int INDENT_WIDTH = 2;
private final int optionWidth;
private final int descriptionWidth;
Columns( int optionWidth, int descriptionWidth ) {
this.optionWidth = optionWidth;
this.descriptionWidth = descriptionWidth;
}
List<Row> fit( Row row ) {
List<String> options = piecesOf( row.option, optionWidth );
List<String> descriptions = piecesOf( row.description, descriptionWidth );
List<Row> rows = new ArrayList<Row>();
for ( int i = 0; i < Math.max( options.size(), descriptions.size() ); ++i )
rows.add( new Row( itemOrEmpty( options, i ), itemOrEmpty( descriptions, i ) ) );
return rows;
}
private static String itemOrEmpty( List<String> items, int index ) {
return index >= items.size() ? "" : items.get( index );
}
private List<String> piecesOf( String raw, int width ) {
List<String> pieces = new ArrayList<String>();
for ( String each : raw.trim().split( LINE_SEPARATOR ) )
pieces.addAll( piecesOfEmbeddedLine( each, width ) );
return pieces;
}
private List<String> piecesOfEmbeddedLine( String line, int width ) {
List<String> pieces = new ArrayList<String>();
BreakIterator words = BreakIterator.getLineInstance( Locale.US );
words.setText( line );
StringBuilder nextPiece = new StringBuilder();
int start = words.first();
for ( int end = words.next(); end != DONE; start = end, end = words.next() )
nextPiece = processNextWord( line, nextPiece, start, end, width, pieces );
if ( nextPiece.length() > 0 )
pieces.add( nextPiece.toString() );
return pieces;
}
private StringBuilder processNextWord( String source, StringBuilder nextPiece, int start, int end, int width,
List<String> pieces ) {
StringBuilder augmented = nextPiece;
String word = source.substring( start, end );
if ( augmented.length() + word.length() > width ) {
pieces.add( augmented.toString().replaceAll( "\\s+$", "" ) );
augmented = new StringBuilder( repeat( ' ', INDENT_WIDTH ) ).append( word );
}
else
augmented.append( word );
return augmented;
}
}

View File

@ -0,0 +1,86 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.internal;
import java.lang.reflect.Constructor;
import jdk.internal.joptsimple.ValueConverter;
import static jdk.internal.joptsimple.internal.Reflection.*;
/**
* @param <V> constraint on the type of values being converted to
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class ConstructorInvokingValueConverter<V> implements ValueConverter<V> {
private final Constructor<V> ctor;
ConstructorInvokingValueConverter( Constructor<V> ctor ) {
this.ctor = ctor;
}
public V convert( String value ) {
return instantiate( ctor, value );
}
public Class<V> valueType() {
return ctor.getDeclaringClass();
}
public String valuePattern() {
return null;
}
}

View File

@ -0,0 +1,88 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.internal;
import java.lang.reflect.Method;
import jdk.internal.joptsimple.ValueConverter;
import static jdk.internal.joptsimple.internal.Reflection.*;
/**
* @param <V> constraint on the type of values being converted to
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class MethodInvokingValueConverter<V> implements ValueConverter<V> {
private final Method method;
private final Class<V> clazz;
MethodInvokingValueConverter( Method method, Class<V> clazz ) {
this.method = method;
this.clazz = clazz;
}
public V convert( String value ) {
return clazz.cast( invoke( method, value ) );
}
public Class<V> valueType() {
return clazz;
}
public String valuePattern() {
return null;
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.internal;
/**
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public final class Objects {
private Objects() {
throw new UnsupportedOperationException();
}
/**
* Rejects {@code null} references.
*
* @param target reference to check
* @throws NullPointerException if {@code target} is {@code null}
*/
public static void ensureNotNull( Object target ) {
if ( target == null )
throw new NullPointerException();
}
}

View File

@ -0,0 +1,176 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.internal;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static java.lang.reflect.Modifier.*;
import jdk.internal.joptsimple.ValueConverter;
import static jdk.internal.joptsimple.internal.Classes.*;
/**
* Helper methods for reflection.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public final class Reflection {
private Reflection() {
throw new UnsupportedOperationException();
}
/**
* Finds an appropriate value converter for the given class.
*
* @param <V> a constraint on the class object to introspect
* @param clazz class to introspect on
* @return a converter method or constructor
*/
public static <V> ValueConverter<V> findConverter( Class<V> clazz ) {
Class<V> maybeWrapper = wrapperOf( clazz );
ValueConverter<V> valueOf = valueOfConverter( maybeWrapper );
if ( valueOf != null )
return valueOf;
ValueConverter<V> constructor = constructorConverter( maybeWrapper );
if ( constructor != null )
return constructor;
throw new IllegalArgumentException( clazz + " is not a value type" );
}
private static <V> ValueConverter<V> valueOfConverter( Class<V> clazz ) {
try {
Method valueOf = clazz.getDeclaredMethod( "valueOf", String.class );
if ( meetsConverterRequirements( valueOf, clazz ) )
return new MethodInvokingValueConverter<V>( valueOf, clazz );
return null;
}
catch ( NoSuchMethodException ignored ) {
return null;
}
}
private static <V> ValueConverter<V> constructorConverter( Class<V> clazz ) {
try {
return new ConstructorInvokingValueConverter<V>( clazz.getConstructor( String.class ) );
}
catch ( NoSuchMethodException ignored ) {
return null;
}
}
/**
* Invokes the given constructor with the given arguments.
*
* @param <T> constraint on the type of the objects yielded by the constructor
* @param constructor constructor to invoke
* @param args arguments to hand to the constructor
* @return the result of invoking the constructor
* @throws ReflectionException in lieu of the gaggle of reflection-related exceptions
*/
public static <T> T instantiate( Constructor<T> constructor, Object... args ) {
try {
return constructor.newInstance( args );
}
catch ( Exception ex ) {
throw reflectionException( ex );
}
}
/**
* Invokes the given static method with the given arguments.
*
* @param method method to invoke
* @param args arguments to hand to the method
* @return the result of invoking the method
* @throws ReflectionException in lieu of the gaggle of reflection-related exceptions
*/
public static Object invoke( Method method, Object... args ) {
try {
return method.invoke( null, args );
}
catch ( Exception ex ) {
throw reflectionException( ex );
}
}
@SuppressWarnings( "unchecked" )
public static <V> V convertWith( ValueConverter<V> converter, String raw ) {
return converter == null ? (V) raw : converter.convert( raw );
}
private static boolean meetsConverterRequirements( Method method, Class<?> expectedReturnType ) {
int modifiers = method.getModifiers();
return isPublic( modifiers ) && isStatic( modifiers ) && expectedReturnType.equals( method.getReturnType() );
}
private static RuntimeException reflectionException( Exception ex ) {
if ( ex instanceof IllegalArgumentException )
return new ReflectionException( ex );
if ( ex instanceof InvocationTargetException )
return new ReflectionException( ex.getCause() );
if ( ex instanceof RuntimeException )
return (RuntimeException) ex;
return new ReflectionException( ex );
}
}

View File

@ -0,0 +1,69 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.internal;
/**
* This unchecked exception wraps reflection-oriented exceptions.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public class ReflectionException extends RuntimeException {
private static final long serialVersionUID = -2L;
ReflectionException( Throwable cause ) {
super( cause );
}
}

View File

@ -0,0 +1,85 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.internal;
/**
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
class Row {
final String option;
final String description;
Row( String option, String description ) {
this.option = option;
this.description = description;
}
@Override
public boolean equals( Object that ) {
if ( that == this )
return true;
if ( that == null || !getClass().equals( that.getClass() ) )
return false;
Row other = (Row) that;
return option.equals( other.option ) && description.equals( other.description );
}
@Override
public int hashCode() {
return option.hashCode() ^ description.hashCode();
}
}

View File

@ -0,0 +1,132 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.internal;
import java.util.LinkedHashSet;
import java.util.Set;
import static java.lang.Math.*;
import static jdk.internal.joptsimple.internal.Strings.*;
/**
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public class Rows {
private final int overallWidth;
private final int columnSeparatorWidth;
private final Set<Row> rows = new LinkedHashSet<Row>();
private int widthOfWidestOption;
private int widthOfWidestDescription;
public Rows( int overallWidth, int columnSeparatorWidth ) {
this.overallWidth = overallWidth;
this.columnSeparatorWidth = columnSeparatorWidth;
}
public void add( String option, String description ) {
add( new Row( option, description ) );
}
private void add( Row row ) {
rows.add( row );
widthOfWidestOption = max( widthOfWidestOption, row.option.length() );
widthOfWidestDescription = max( widthOfWidestDescription, row.description.length() );
}
private void reset() {
rows.clear();
widthOfWidestOption = 0;
widthOfWidestDescription = 0;
}
public void fitToWidth() {
Columns columns = new Columns( optionWidth(), descriptionWidth() );
Set<Row> fitted = new LinkedHashSet<Row>();
for ( Row each : rows )
fitted.addAll( columns.fit( each ) );
reset();
for ( Row each : fitted )
add( each );
}
public String render() {
StringBuilder buffer = new StringBuilder();
for ( Row each : rows ) {
pad( buffer, each.option, optionWidth() ).append( repeat( ' ', columnSeparatorWidth ) );
pad( buffer, each.description, descriptionWidth() ).append( LINE_SEPARATOR );
}
return buffer.toString();
}
private int optionWidth() {
return min( ( overallWidth - columnSeparatorWidth ) / 2, widthOfWidestOption );
}
private int descriptionWidth() {
return min( ( overallWidth - columnSeparatorWidth ) / 2, widthOfWidestDescription );
}
private StringBuilder pad( StringBuilder buffer, String s, int length ) {
buffer.append( s ).append( repeat( ' ', length - s.length() ) );
return buffer;
}
}

View File

@ -0,0 +1,147 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.internal;
import java.util.Iterator;
import java.util.List;
import static java.lang.System.*;
import static java.util.Arrays.*;
/**
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public final class Strings {
public static final String EMPTY = "";
public static final String SINGLE_QUOTE = "'";
public static final String LINE_SEPARATOR = getProperty( "line.separator" );
private Strings() {
throw new UnsupportedOperationException();
}
/**
* Gives a string consisting of the given character repeated the given number of times.
*
* @param ch the character to repeat
* @param count how many times to repeat the character
* @return the resultant string
*/
public static String repeat( char ch, int count ) {
StringBuilder buffer = new StringBuilder();
for ( int i = 0; i < count; ++i )
buffer.append( ch );
return buffer.toString();
}
/**
* Tells whether the given string is either {@code} or consists solely of whitespace characters.
*
* @param target string to check
* @return {@code true} if the target string is null or empty
*/
public static boolean isNullOrEmpty( String target ) {
return target == null || EMPTY.equals( target );
}
/**
* Gives a string consisting of a given string prepended and appended with surrounding characters.
*
* @param target a string
* @param begin character to prepend
* @param end character to append
* @return the surrounded string
*/
public static String surround( String target, char begin, char end ) {
return begin + target + end;
}
/**
* Gives a string consisting of the elements of a given array of strings, each separated by a given separator
* string.
*
* @param pieces the strings to join
* @param separator the separator
* @return the joined string
*/
public static String join( String[] pieces, String separator ) {
return join( asList( pieces ), separator );
}
/**
* Gives a string consisting of the string representations of the elements of a given array of objects,
* each separated by a given separator string.
*
* @param pieces the elements whose string representations are to be joined
* @param separator the separator
* @return the joined string
*/
public static String join( List<String> pieces, String separator ) {
StringBuilder buffer = new StringBuilder();
for ( Iterator<String> iter = pieces.iterator(); iter.hasNext(); ) {
buffer.append( iter.next() );
if ( iter.hasNext() )
buffer.append( separator );
}
return buffer.toString();
}
}

View File

@ -0,0 +1,130 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.util;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import jdk.internal.joptsimple.ValueConversionException;
import jdk.internal.joptsimple.ValueConverter;
/**
* Converts values to {@link Date}s using a {@link DateFormat} object.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public class DateConverter implements ValueConverter<Date> {
private final DateFormat formatter;
/**
* Creates a converter that uses the given date formatter/parser.
*
* @param formatter the formatter/parser to use
* @throws NullPointerException if {@code formatter} is {@code null}
*/
public DateConverter( DateFormat formatter ) {
if ( formatter == null )
throw new NullPointerException( "illegal null formatter" );
this.formatter = formatter;
}
/**
* Creates a converter that uses a {@link SimpleDateFormat} with the given date/time pattern. The date formatter
* created is not {@link SimpleDateFormat#setLenient(boolean) lenient}.
*
* @param pattern expected date/time pattern
* @return the new converter
* @throws NullPointerException if {@code pattern} is {@code null}
* @throws IllegalArgumentException if {@code pattern} is invalid
*/
public static DateConverter datePattern( String pattern ) {
SimpleDateFormat formatter = new SimpleDateFormat( pattern );
formatter.setLenient( false );
return new DateConverter( formatter );
}
public Date convert( String value ) {
ParsePosition position = new ParsePosition( 0 );
Date date = formatter.parse( value, position );
if ( position.getIndex() != value.length() )
throw new ValueConversionException( message( value ) );
return date;
}
public Class<Date> valueType() {
return Date.class;
}
public String valuePattern() {
return formatter instanceof SimpleDateFormat
? ( (SimpleDateFormat) formatter ).toPattern()
: "";
}
private String message( String value ) {
String message = "Value [" + value + "] does not match date/time pattern";
if ( formatter instanceof SimpleDateFormat )
message += " [" + ( (SimpleDateFormat) formatter ).toPattern() + ']';
return message;
}
}

View File

@ -0,0 +1,85 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.util;
import java.net.InetAddress;
import java.net.UnknownHostException;
import jdk.internal.joptsimple.ValueConversionException;
import jdk.internal.joptsimple.ValueConverter;
/**
* Converts values to {@link java.net.InetAddress} using {@link InetAddress#getByName(String) getByName}.
*
* @author <a href="mailto:r@ymund.de">Raymund F\u00FCl\u00F6p</a>
*/
public class InetAddressConverter implements ValueConverter<InetAddress> {
public InetAddress convert( String value ) {
try {
return InetAddress.getByName( value );
} catch ( UnknownHostException e ) {
throw new ValueConversionException( "Cannot convert value [" + value + " into an InetAddress", e );
}
}
public Class<InetAddress> valueType() {
return InetAddress.class;
}
public String valuePattern() {
return null;
}
}

View File

@ -0,0 +1,113 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.util;
import static jdk.internal.joptsimple.internal.Strings.*;
/**
* <p>A simple string key/string value pair.</p>
*
* <p>This is useful as an argument type for options whose values take on the form <kbd>key=value</kbd>, such as JVM
* command line system properties.</p>
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public final class KeyValuePair {
public final String key;
public final String value;
private KeyValuePair( String key, String value ) {
this.key = key;
this.value = value;
}
/**
* Parses a string assumed to be of the form <kbd>key=value</kbd> into its parts.
*
* @param asString key-value string
* @return a key-value pair
* @throws NullPointerException if {@code stringRepresentation} is {@code null}
*/
public static KeyValuePair valueOf( String asString ) {
int equalsIndex = asString.indexOf( '=' );
if ( equalsIndex == -1 )
return new KeyValuePair( asString, EMPTY );
String aKey = asString.substring( 0, equalsIndex );
String aValue = equalsIndex == asString.length() - 1 ? EMPTY : asString.substring( equalsIndex + 1 );
return new KeyValuePair( aKey, aValue );
}
@Override
public boolean equals( Object that ) {
if ( !( that instanceof KeyValuePair ) )
return false;
KeyValuePair other = (KeyValuePair) that;
return key.equals( other.key ) && value.equals( other.value );
}
@Override
public int hashCode() {
return key.hashCode() ^ value.hashCode();
}
@Override
public String toString() {
return key + '=' + value;
}
}

View File

@ -0,0 +1,113 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* The MIT License
*
* Copyright (c) 2004-2014 Paul R. Holser, Jr.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package jdk.internal.joptsimple.util;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.*;
import jdk.internal.joptsimple.ValueConversionException;
import jdk.internal.joptsimple.ValueConverter;
/**
* Ensures that values entirely match a regular expression.
*
* @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
*/
public class RegexMatcher implements ValueConverter<String> {
private final Pattern pattern;
/**
* Creates a matcher that uses the given regular expression, modified by the given flags.
*
* @param pattern the regular expression pattern
* @param flags modifying regex flags
* @throws IllegalArgumentException if bit values other than those corresponding to the defined match flags are
* set in {@code flags}
* @throws java.util.regex.PatternSyntaxException if the expression's syntax is invalid
*/
public RegexMatcher( String pattern, int flags ) {
this.pattern = compile( pattern, flags );
}
/**
* Gives a matcher that uses the given regular expression.
*
* @param pattern the regular expression pattern
* @return the new converter
* @throws java.util.regex.PatternSyntaxException if the expression's syntax is invalid
*/
public static ValueConverter<String> regex( String pattern ) {
return new RegexMatcher( pattern, 0 );
}
public String convert( String value ) {
if ( !pattern.matcher( value ).matches() ) {
throw new ValueConversionException(
"Value [" + value + "] did not match regex [" + pattern.pattern() + ']' );
}
return value;
}
public Class<String> valueType() {
return String.class;
}
public String valuePattern() {
return pattern.pattern();
}
}

View File

@ -65,8 +65,11 @@ import javax.swing.border.EmptyBorder;
*
* @see java.security.Policy
* @since 1.2
* @deprecated The policytool tool has been deprecated and
* is planned to be removed in a future release.
*/
@Deprecated
public class PolicyTool {
// for i18n
@ -738,6 +741,8 @@ public class PolicyTool {
* run the PolicyTool
*/
public static void main(String args[]) {
System.out.println("Note: The policytool tool has been deprecated and" +
" is planned to be removed in a future release.\n");
parseArgs(args);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
@ -873,6 +878,7 @@ public class PolicyTool {
* The Permission contains the (Type, Name, Action) triplet.
*
*/
@SuppressWarnings("deprecation")
class PolicyEntry {
private CodeSource codesource;
@ -1012,6 +1018,7 @@ class PolicyEntry {
/**
* The main window for the PolicyTool
*/
@SuppressWarnings("deprecation")
class ToolWindow extends JFrame {
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 5682568601210376777L;
@ -1549,6 +1556,7 @@ class ToolWindow extends JFrame {
/**
* General dialog window
*/
@SuppressWarnings("deprecation")
class ToolDialog extends JDialog {
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = -372244357011301190L;
@ -2912,6 +2920,7 @@ class ToolDialog extends JDialog {
/**
* Event handler for the PolicyTool window
*/
@SuppressWarnings("deprecation")
class ToolWindowListener implements WindowListener {
private PolicyTool tool;
@ -2956,6 +2965,7 @@ class ToolWindowListener implements WindowListener {
/**
* Event handler for the Policy List
*/
@SuppressWarnings("deprecation")
class PolicyListListener extends MouseAdapter implements ActionListener {
private PolicyTool tool;
@ -2985,6 +2995,7 @@ class PolicyListListener extends MouseAdapter implements ActionListener {
/**
* Event handler for the File Menu
*/
@SuppressWarnings("deprecation")
class FileMenuListener implements ActionListener {
private PolicyTool tool;
@ -3083,6 +3094,7 @@ class FileMenuListener implements ActionListener {
/**
* Event handler for the main window buttons and Edit Menu
*/
@SuppressWarnings("deprecation")
class MainWindowListener implements ActionListener {
private PolicyTool tool;
@ -3158,6 +3170,7 @@ class MainWindowListener implements ActionListener {
* if edit is FALSE, then we are ADDing a new PolicyEntry,
* so we only need to update the GUI listing.
*/
@SuppressWarnings("deprecation")
class AddEntryDoneButtonListener implements ActionListener {
private PolicyTool tool;
@ -3224,6 +3237,7 @@ class AddEntryDoneButtonListener implements ActionListener {
/**
* Event handler for ChangeKeyStoreOKButton button
*/
@SuppressWarnings("deprecation")
class ChangeKeyStoreOKButtonListener implements ActionListener {
private PolicyTool tool;
@ -3270,6 +3284,7 @@ class ChangeKeyStoreOKButtonListener implements ActionListener {
/**
* Event handler for AddPrinButton button
*/
@SuppressWarnings("deprecation")
class AddPrinButtonListener implements ActionListener {
private PolicyTool tool;
@ -3295,6 +3310,7 @@ class AddPrinButtonListener implements ActionListener {
/**
* Event handler for AddPermButton button
*/
@SuppressWarnings("deprecation")
class AddPermButtonListener implements ActionListener {
private PolicyTool tool;
@ -3320,6 +3336,7 @@ class AddPermButtonListener implements ActionListener {
/**
* Event handler for AddPrinOKButton button
*/
@SuppressWarnings("deprecation")
class NewPolicyPrinOKButtonListener implements ActionListener {
private PolicyTool tool;
@ -3383,6 +3400,7 @@ class NewPolicyPrinOKButtonListener implements ActionListener {
/**
* Event handler for AddPermOKButton button
*/
@SuppressWarnings("deprecation")
class NewPolicyPermOKButtonListener implements ActionListener {
private PolicyTool tool;
@ -3446,6 +3464,7 @@ class NewPolicyPermOKButtonListener implements ActionListener {
/**
* Event handler for RemovePrinButton button
*/
@SuppressWarnings("deprecation")
class RemovePrinButtonListener implements ActionListener {
private PolicyTool tool;
@ -3481,6 +3500,7 @@ class RemovePrinButtonListener implements ActionListener {
/**
* Event handler for RemovePermButton button
*/
@SuppressWarnings("deprecation")
class RemovePermButtonListener implements ActionListener {
private PolicyTool tool;
@ -3523,6 +3543,7 @@ class RemovePermButtonListener implements ActionListener {
* GUI listing. If the user is editing an existing PolicyEntry, we
* update both the GUI listing and the actual PolicyEntry.
*/
@SuppressWarnings("deprecation")
class EditPrinButtonListener extends MouseAdapter implements ActionListener {
private PolicyTool tool;
@ -3569,6 +3590,7 @@ class EditPrinButtonListener extends MouseAdapter implements ActionListener {
* GUI listing. If the user is editing an existing PolicyEntry, we
* update both the GUI listing and the actual PolicyEntry.
*/
@SuppressWarnings("deprecation")
class EditPermButtonListener extends MouseAdapter implements ActionListener {
private PolicyTool tool;
@ -3609,6 +3631,7 @@ class EditPermButtonListener extends MouseAdapter implements ActionListener {
/**
* Event handler for Principal Popup Menu
*/
@SuppressWarnings("deprecation")
class PrincipalTypeMenuListener implements ItemListener {
private ToolDialog td;
@ -3660,6 +3683,7 @@ class PrincipalTypeMenuListener implements ItemListener {
/**
* Event handler for Permission Popup Menu
*/
@SuppressWarnings("deprecation")
class PermissionMenuListener implements ItemListener {
private ToolDialog td;
@ -3734,6 +3758,7 @@ class PermissionMenuListener implements ItemListener {
/**
* Event handler for Permission Name Popup Menu
*/
@SuppressWarnings("deprecation")
class PermissionNameMenuListener implements ItemListener {
private ToolDialog td;
@ -3887,6 +3912,7 @@ class StatusOKButtonListener implements ActionListener {
/**
* Event handler for UserSaveYes button
*/
@SuppressWarnings("deprecation")
class UserSaveYesButtonListener implements ActionListener {
private ToolDialog us;
@ -3941,6 +3967,7 @@ class UserSaveYesButtonListener implements ActionListener {
/**
* Event handler for UserSaveNoButton
*/
@SuppressWarnings("deprecation")
class UserSaveNoButtonListener implements ActionListener {
private PolicyTool tool;
@ -3989,6 +4016,7 @@ class UserSaveCancelButtonListener implements ActionListener {
/**
* Event handler for ConfirmRemovePolicyEntryOKButtonListener
*/
@SuppressWarnings("deprecation")
class ConfirmRemovePolicyEntryOKButtonListener implements ActionListener {
private PolicyTool tool;
@ -4144,6 +4172,7 @@ class AudioPerm extends Perm {
}
}
@SuppressWarnings("deprecation")
class AuthPerm extends Perm {
AuthPerm() {
super(javax.security.auth.AuthPermission.class,
@ -4216,6 +4245,7 @@ class FilePerm extends Perm {
}
}
@SuppressWarnings("deprecation")
class URLPerm extends Perm {
URLPerm() {
super(java.net.URLPermission.class,
@ -4380,6 +4410,7 @@ class ReflectPerm extends Perm {
}
}
@SuppressWarnings("deprecation")
class RuntimePerm extends Perm {
RuntimePerm() {
super(java.lang.RuntimePermission.class,
@ -4420,6 +4451,7 @@ class RuntimePerm extends Perm {
}
}
@SuppressWarnings("deprecation")
class SecurityPerm extends Perm {
SecurityPerm() {
super(java.security.SecurityPermission.class,

View File

@ -77,6 +77,7 @@ jdk_lang = \
sun/misc \
sun/reflect \
jdk/lambda \
jdk/internal/misc \
vm
# All of the java.util package
@ -144,7 +145,8 @@ jdk_stream = \
java/util/stream
jdk_math = \
java/math
java/math \
jdk/internal/math
jdk_io = \
java/io

View File

@ -29,7 +29,7 @@
*
* @modules jdk.jdi
* @run build TestScaffold VMConnection TargetListener TargetAdapter
* @run compile -g LineNumberInfo.java ControlFlow.java
* @run compile -XDstringConcat=inline -g LineNumberInfo.java ControlFlow.java
*
* @run driver LineNumberInfo
*/

View File

@ -253,12 +253,16 @@ class InstallSDE {
case 3: // Integer
case 4: // Float
case 12: // NameAndType
case 18: // InvokeDynamic
copy(4);
break;
case 5: // Long
case 6: // Double
copy(8);
break;
case 15: // MethodHandle
copy(3);
break;
case 1: // Utf8
int len = readU2();
writeU2(len);

View File

@ -0,0 +1,216 @@
/*
* Copyright (c) 2015, 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 implicit String concatenations
*
* @compile ImplicitStringConcat.java
* @run main/othervm ImplicitStringConcat
*
* @compile -XDstringConcat=inline ImplicitStringConcat.java
* @run main/othervm ImplicitStringConcat
*
* @compile -XDstringConcat=indy -source 1.9 -target 1.9 ImplicitStringConcat.java
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT ImplicitStringConcat
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcat
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
*
* @compile -XDstringConcat=indyWithConstants -source 1.9 -target 1.9 ImplicitStringConcat.java
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT ImplicitStringConcat
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcat
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcat
*/
import java.lang.StringBuilder;
public class ImplicitStringConcat {
static boolean b = true;
static byte by = 42;
static short sh = 42;
static char ch = 'a';
static int i = 42;
static float fl = 42.0f;
static long l = 42;
static double d = 42.0d;
static String s = "foo";
static String sNull = null;
static Object o = "bar";
static Object oNull = null;
static CharSequence cs = "bar";
static char[] chars = new char[] {'a'};
static MyClass myCl = new MyClass();
static MyClassNull myClNull = new MyClassNull();
static Object myCl2 = new MyClass();
static Object[] myArr = new Object[] { myCl };
static final Object[] s_myArr = new Object[] { myCl };
static StringBuffer sb = new StringBuffer("a");
public static void main(String[] args) throws Exception {
test("footrue", s + b);
test("foo42", s + by);
test("foo42", s + sh);
test("fooa", s + ch);
test("foo42", s + i);
test("foo42", s + l);
test("foo42.0", s + fl);
test("foo42.0", s + d);
test("foofoo", s + s);
test("foonull", s + sNull);
test("foobar", s + o);
test("foonull", s + oNull);
test("foobar", s + cs);
{
StringBuilder sb = new StringBuilder();
sb.append("foo");
sb.append(myArr.toString());
test(sb.toString(), s + myArr);
}
{
StringBuilder sb = new StringBuilder();
sb.append("foo");
sb.append(s_myArr.toString());
test(sb.toString(), s + s_myArr);
}
{
StringBuilder sb = new StringBuilder();
sb.append("foo[C@");
sb.append(Integer.toHexString(System.identityHashCode(chars)));
test(sb.toString(), s + chars);
}
test("fooa", s + ImplicitStringConcat.sb);
test("foonull", s + null);
test("fooMyClass", s + myCl);
test("foonull", s + myClNull);
test("fooMyClass", s + myCl2);
s = "foo"; s += b; test("footrue", s);
s = "foo"; s += by; test("foo42", s);
s = "foo"; s += sh; test("foo42", s);
s = "foo"; s += ch; test("fooa", s);
s = "foo"; s += i; test("foo42", s);
s = "foo"; s += l; test("foo42", s);
s = "foo"; s += fl; test("foo42.0", s);
s = "foo"; s += d; test("foo42.0", s);
s = "foo"; s += s; test("foofoo", s);
s = "foo"; s += sNull; test("foonull", s);
s = "foo"; s += o; test("foobar", s);
s = "foo"; s += oNull; test("foonull", s);
s = "foo"; s += cs; test("foobar", s);
{
StringBuilder sb = new StringBuilder();
sb.append("foo[C@");
sb.append(Integer.toHexString(System.identityHashCode(chars)));
s = "foo";
s += chars;
test(sb.toString(), s);
}
s = "foo"; s += ImplicitStringConcat.sb; test("fooa", s);
s = "foo"; s += null; test("foonull", s);
s = "foo"; s += myCl; test("fooMyClass", s);
s = "foo"; s += myCl2; test("fooMyClass", s);
}
public static void test(String expected, String actual) {
// Fingers crossed: String concat should work.
if (!expected.equals(actual)) {
StringBuilder sb = new StringBuilder();
sb.append("Expected = ");
sb.append(expected);
sb.append(", actual = ");
sb.append(actual);
throw new IllegalStateException(sb.toString());
}
}
static class MyClass {
public String toString() {
return "MyClass";
}
}
static class MyClassNull {
public String toString() {
return null;
}
}
}

View File

@ -0,0 +1,123 @@
/*
* Copyright (c) 2015, 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 multiple number of arguments to concatenate.
*
* @compile ImplicitStringConcatArgCount.java
* @run main/othervm ImplicitStringConcatArgCount
*
* @compile -XDallowStringFolding=false -XDstringConcat=inline ImplicitStringConcatArgCount.java
* @run main/othervm ImplicitStringConcatArgCount
*
* @compile -XDallowStringFolding=false -XDstringConcat=indy -source 1.9 -target 1.9 ImplicitStringConcatArgCount.java
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT ImplicitStringConcatArgCount
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatArgCount
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
*
* @compile -XDallowStringFolding=false -XDstringConcat=indyWithConstants -source 1.9 -target 1.9 ImplicitStringConcatArgCount.java
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT ImplicitStringConcatArgCount
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatArgCount
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatArgCount
*/
public class ImplicitStringConcatArgCount {
static final String s = "f";
static final String s1 = "o";
static String s2 = "o";
static int i = 7;
public static void main(String[] args) throws Exception {
test("fo", s + s1);
test("foo", s + s1 + s2);
test("foo7", s + s1 + s2 + i);
test("foo77", s + s1 + s2 + i + i);
test("foo777", s + s1 + s2 + i + i + i);
test("foo7777", s + s1 + s2 + i + i + i + i);
test("foo77777", s + s1 + s2 + i + i + i + i + i);
test("foo777777", s + s1 + s2 + i + i + i + i + i + i);
test("foo7777777", s + s1 + s2 + i + i + i + i + i + i + i);
test("foo77777777", s + s1 + s2 + i + i + i + i + i + i + i + i);
}
public static void test(String expected, String actual) {
if (!expected.equals(actual)) {
StringBuilder sb = new StringBuilder();
sb.append("Expected = ");
sb.append(expected);
sb.append(", actual = ");
sb.append(actual);
throw new IllegalStateException(sb.toString());
}
}
}

View File

@ -0,0 +1,206 @@
/*
* Copyright (c) 2015, 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 the boundary values for concatenation arguments.
*
* @compile ImplicitStringConcatBoundaries.java
* @run main/othervm ImplicitStringConcatBoundaries
*
* @compile -XDstringConcat=inline ImplicitStringConcatBoundaries.java
* @run main/othervm ImplicitStringConcatBoundaries
*
* @compile -XDstringConcat=indy -source 1.9 -target 1.9 ImplicitStringConcatBoundaries.java
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT ImplicitStringConcatBoundaries
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatBoundaries
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
*
* @compile -XDstringConcat=indyWithConstants -source 1.9 -target 1.9 ImplicitStringConcatBoundaries.java
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT ImplicitStringConcatBoundaries
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatBoundaries
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatBoundaries
*/
public class ImplicitStringConcatBoundaries {
public static final boolean BOOL_TRUE_1 = true;
public static boolean BOOL_TRUE_2 = true;
public static final boolean BOOL_FALSE_1 = false;
public static boolean BOOL_FALSE_2 = false;
public static final byte BYTE_MIN_1 = Byte.MIN_VALUE;
public static byte BYTE_MIN_2 = Byte.MIN_VALUE;
public static final byte BYTE_MAX_1 = Byte.MAX_VALUE;
public static byte BYTE_MAX_2 = Byte.MAX_VALUE;
public static final short SHORT_MIN_1 = Short.MIN_VALUE;
public static short SHORT_MIN_2 = Short.MIN_VALUE;
public static final short SHORT_MAX_1 = Short.MAX_VALUE;
public static short SHORT_MAX_2 = Short.MAX_VALUE;
public static final char CHAR_MIN_1 = Character.MIN_VALUE;
public static char CHAR_MIN_2 = Character.MIN_VALUE;
public static final char CHAR_MAX_1 = Character.MAX_VALUE;
public static char CHAR_MAX_2 = Character.MAX_VALUE;
public static final int INT_MIN_1 = Integer.MIN_VALUE;
public static int INT_MIN_2 = Integer.MIN_VALUE;
public static final int INT_MAX_1 = Integer.MAX_VALUE;
public static int INT_MAX_2 = Integer.MAX_VALUE;
public static final float FLOAT_MIN_EXP_1 = Float.MIN_EXPONENT;
public static float FLOAT_MIN_EXP_2 = Float.MIN_EXPONENT;
public static final float FLOAT_MIN_NORM_1 = Float.MIN_NORMAL;
public static float FLOAT_MIN_NORM_2 = Float.MIN_NORMAL;
public static final float FLOAT_MIN_1 = Float.MIN_VALUE;
public static float FLOAT_MIN_2 = Float.MIN_VALUE;
public static final float FLOAT_MAX_1 = Float.MAX_VALUE;
public static float FLOAT_MAX_2 = Float.MAX_VALUE;
public static final long LONG_MIN_1 = Long.MIN_VALUE;
public static long LONG_MIN_2 = Long.MIN_VALUE;
public static final long LONG_MAX_1 = Long.MAX_VALUE;
public static long LONG_MAX_2 = Long.MAX_VALUE;
public static final double DOUBLE_MIN_EXP_1 = Double.MIN_EXPONENT;
public static double DOUBLE_MIN_EXP_2 = Double.MIN_EXPONENT;
public static final double DOUBLE_MIN_NORM_1 = Double.MIN_NORMAL;
public static double DOUBLE_MIN_NORM_2 = Double.MIN_NORMAL;
public static final double DOUBLE_MIN_1 = Double.MIN_VALUE;
public static double DOUBLE_MIN_2 = Double.MIN_VALUE;
public static final double DOUBLE_MAX_1 = Double.MAX_VALUE;
public static double DOUBLE_MAX_2 = Double.MAX_VALUE;
public static void main(String[] args) throws Exception {
test("foofalse", "foo" + BOOL_FALSE_1);
test("foofalse", "foo" + BOOL_FALSE_2);
test("footrue", "foo" + BOOL_TRUE_1);
test("footrue", "foo" + BOOL_TRUE_2);
test("foo127", "foo" + BYTE_MAX_1);
test("foo127", "foo" + BYTE_MAX_2);
test("foo-128", "foo" + BYTE_MIN_1);
test("foo-128", "foo" + BYTE_MIN_2);
test("foo32767", "foo" + SHORT_MAX_1);
test("foo32767", "foo" + SHORT_MAX_2);
test("foo-32768", "foo" + SHORT_MIN_1);
test("foo-32768", "foo" + SHORT_MIN_2);
test("foo\u0000", "foo" + CHAR_MIN_1);
test("foo\u0000", "foo" + CHAR_MIN_2);
test("foo\uFFFF", "foo" + CHAR_MAX_1);
test("foo\uFFFF", "foo" + CHAR_MAX_2);
test("foo2147483647", "foo" + INT_MAX_1);
test("foo2147483647", "foo" + INT_MAX_2);
test("foo-2147483648", "foo" + INT_MIN_1);
test("foo-2147483648", "foo" + INT_MIN_2);
test("foo1.17549435E-38", "foo" + FLOAT_MIN_NORM_1);
test("foo1.17549435E-38", "foo" + FLOAT_MIN_NORM_2);
test("foo-126.0", "foo" + FLOAT_MIN_EXP_1);
test("foo-126.0", "foo" + FLOAT_MIN_EXP_2);
test("foo1.4E-45", "foo" + FLOAT_MIN_1);
test("foo1.4E-45", "foo" + FLOAT_MIN_2);
test("foo3.4028235E38", "foo" + FLOAT_MAX_1);
test("foo3.4028235E38", "foo" + FLOAT_MAX_2);
test("foo-9223372036854775808", "foo" + LONG_MIN_1);
test("foo-9223372036854775808", "foo" + LONG_MIN_2);
test("foo9223372036854775807", "foo" + LONG_MAX_1);
test("foo9223372036854775807", "foo" + LONG_MAX_2);
test("foo2.2250738585072014E-308", "foo" + DOUBLE_MIN_NORM_1);
test("foo2.2250738585072014E-308", "foo" + DOUBLE_MIN_NORM_2);
test("foo-1022.0", "foo" + DOUBLE_MIN_EXP_1);
test("foo-1022.0", "foo" + DOUBLE_MIN_EXP_2);
test("foo4.9E-324", "foo" + DOUBLE_MIN_1);
test("foo4.9E-324", "foo" + DOUBLE_MIN_2);
test("foo1.7976931348623157E308", "foo" + DOUBLE_MAX_1);
test("foo1.7976931348623157E308", "foo" + DOUBLE_MAX_2);
}
public static void test(String expected, String actual) {
if (!expected.equals(actual)) {
StringBuilder sb = new StringBuilder();
sb.append("Expected = ");
sb.append(expected);
sb.append(", actual = ");
sb.append(actual);
throw new IllegalStateException(sb.toString());
}
}
}

View File

@ -0,0 +1,195 @@
/*
* Copyright (c) 2015, 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 implicit String concatenations with lots of arguments.
*
* @compile ImplicitStringConcatMany.java
* @run main/othervm ImplicitStringConcatMany
*
* @compile -XDstringConcat=inline ImplicitStringConcatMany.java
* @run main/othervm ImplicitStringConcatMany
*
* @compile -XDstringConcat=indy -source 1.9 -target 1.9 ImplicitStringConcatMany.java
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT ImplicitStringConcatMany
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatMany
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
*
* @compile -XDstringConcat=indyWithConstants -source 1.9 -target 1.9 ImplicitStringConcatMany.java
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT ImplicitStringConcatMany
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatMany
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatMany
*/
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class ImplicitStringConcatMany {
static String s000, s001, s002, s003, s004, s005, s006, s007, s008, s009;
static String s010, s011, s012, s013, s014, s015, s016, s017, s018, s019;
static String s020, s021, s022, s023, s024, s025, s026, s027, s028, s029;
static String s030, s031, s032, s033, s034, s035, s036, s037, s038, s039;
static String s040, s041, s042, s043, s044, s045, s046, s047, s048, s049;
static String s050, s051, s052, s053, s054, s055, s056, s057, s058, s059;
static String s060, s061, s062, s063, s064, s065, s066, s067, s068, s069;
static String s070, s071, s072, s073, s074, s075, s076, s077, s078, s079;
static String s080, s081, s082, s083, s084, s085, s086, s087, s088, s089;
static String s090, s091, s092, s093, s094, s095, s096, s097, s098, s099;
static String s100, s101, s102, s103, s104, s105, s106, s107, s108, s109;
static String s110, s111, s112, s113, s114, s115, s116, s117, s118, s119;
static String s120, s121, s122, s123, s124, s125, s126, s127, s128, s129;
static String s130, s131, s132, s133, s134, s135, s136, s137, s138, s139;
static String s140, s141, s142, s143, s144, s145, s146, s147, s148, s149;
static String s150, s151, s152, s153, s154, s155, s156, s157, s158, s159;
static String s160, s161, s162, s163, s164, s165, s166, s167, s168, s169;
static String s170, s171, s172, s173, s174, s175, s176, s177, s178, s179;
static String s180, s181, s182, s183, s184, s185, s186, s187, s188, s189;
static String s190, s191, s192, s193, s194, s195, s196, s197, s198, s199;
static String s200, s201, s202, s203, s204, s205, s206, s207, s208, s209;
static String s210, s211, s212, s213, s214, s215, s216, s217, s218, s219;
static String s220, s221, s222, s223, s224, s225, s226, s227, s228, s229;
static String s230, s231, s232, s233, s234, s235, s236, s237, s238, s239;
static String s240, s241, s242, s243, s244, s245, s246, s247, s248, s249;
static String s250, s251, s252, s253, s254, s255, s256, s257, s258, s259;
static String s260, s261, s262, s263, s264, s265, s266, s267, s268, s269;
static String s270, s271, s272, s273, s274, s275, s276, s277, s278, s279;
static String s280, s281, s282, s283, s284, s285, s286, s287, s288, s289;
static String s290, s291, s292, s293, s294, s295, s296, s297, s298, s299;
static {
for (Field f : ImplicitStringConcatMany.class.getDeclaredFields()) {
if (Modifier.isStatic(f.getModifiers())) {
String name = f.getName();
try {
f.set(null, name);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
}
public static void main(String[] args) throws Exception {
String res =
s000 + s001 + s002 + s003 + s004 + s005 + s006 + s007 + s008 + s009 +
s010 + s011 + s012 + s013 + s014 + s015 + s016 + s017 + s018 + s019 +
s020 + s021 + s022 + s023 + s024 + s025 + s026 + s027 + s028 + s029 +
s030 + s031 + s032 + s033 + s034 + s035 + s036 + s037 + s038 + s039 +
s040 + s041 + s042 + s043 + s044 + s045 + s046 + s047 + s048 + s049 +
s050 + s051 + s052 + s053 + s054 + s055 + s056 + s057 + s058 + s059 +
s060 + s061 + s062 + s063 + s064 + s065 + s066 + s067 + s068 + s069 +
s070 + s071 + s072 + s073 + s074 + s075 + s076 + s077 + s078 + s079 +
s080 + s081 + s082 + s083 + s084 + s085 + s086 + s087 + s088 + s089 +
s090 + s091 + s092 + s093 + s094 + s095 + s096 + s097 + s098 + s099 +
s100 + s101 + s102 + s103 + s104 + s105 + s106 + s107 + s108 + s109 +
s110 + s111 + s112 + s113 + s114 + s115 + s116 + s117 + s118 + s119 +
s120 + s121 + s122 + s123 + s124 + s125 + s126 + s127 + s128 + s129 +
s130 + s131 + s132 + s133 + s134 + s135 + s136 + s137 + s138 + s139 +
s140 + s141 + s142 + s143 + s144 + s145 + s146 + s147 + s148 + s149 +
s150 + s151 + s152 + s153 + s154 + s155 + s156 + s157 + s158 + s159 +
s160 + s161 + s162 + s163 + s164 + s165 + s166 + s167 + s168 + s169 +
s170 + s171 + s172 + s173 + s174 + s175 + s176 + s177 + s178 + s179 +
s180 + s181 + s182 + s183 + s184 + s185 + s186 + s187 + s188 + s189 +
s190 + s191 + s192 + s193 + s194 + s195 + s196 + s197 + s198 + s199 +
s200 + s201 + s202 + s203 + s204 + s205 + s206 + s207 + s208 + s209 +
s210 + s211 + s212 + s213 + s214 + s215 + s216 + s217 + s218 + s219 +
s220 + s221 + s222 + s223 + s224 + s225 + s226 + s227 + s228 + s229 +
s230 + s231 + s232 + s233 + s234 + s235 + s236 + s237 + s238 + s239 +
s240 + s241 + s242 + s243 + s244 + s245 + s246 + s247 + s248 + s249 +
s250 + s251 + s252 + s253 + s254 + s255 + s256 + s257 + s258 + s259 +
s260 + s261 + s262 + s263 + s264 + s265 + s266 + s267 + s268 + s269 +
s270 + s271 + s272 + s273 + s274 + s275 + s276 + s277 + s278 + s279 +
s280 + s281 + s282 + s283 + s284 + s285 + s286 + s287 + s288 + s289 +
s290 + s291 + s292 + s293 + s294 + s295 + s296 + s297 + s298 + s299;
StringBuilder sb = new StringBuilder();
for (int c = 0; c < 300; c++) {
sb.append(String.format("s%03d", c));
}
test(sb.toString(), res);
}
public static void test(String expected, String actual) {
// Fingers crossed: String concat should work.
if (!expected.equals(actual)) {
throw new IllegalStateException("Expected = " + expected + ", actual = " + actual);
}
}
}

View File

@ -0,0 +1,195 @@
/*
* Copyright (c) 2015, 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 implicit String concatenations with lots of arguments (two-slot version)
*
* @compile ImplicitStringConcatManyLongs.java
* @run main/othervm ImplicitStringConcatManyLongs
*
* @compile -XDstringConcat=inline ImplicitStringConcatManyLongs.java
* @run main/othervm ImplicitStringConcatManyLongs
*
* @compile -XDstringConcat=indy -source 1.9 -target 1.9 ImplicitStringConcatManyLongs.java
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT ImplicitStringConcatManyLongs
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatManyLongs
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
*
* @compile -XDstringConcat=indyWithConstants -source 1.9 -target 1.9 ImplicitStringConcatManyLongs.java
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT ImplicitStringConcatManyLongs
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatManyLongs
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatManyLongs
*/
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class ImplicitStringConcatManyLongs {
static long s000, s001, s002, s003, s004, s005, s006, s007, s008, s009;
static long s010, s011, s012, s013, s014, s015, s016, s017, s018, s019;
static long s020, s021, s022, s023, s024, s025, s026, s027, s028, s029;
static long s030, s031, s032, s033, s034, s035, s036, s037, s038, s039;
static long s040, s041, s042, s043, s044, s045, s046, s047, s048, s049;
static long s050, s051, s052, s053, s054, s055, s056, s057, s058, s059;
static long s060, s061, s062, s063, s064, s065, s066, s067, s068, s069;
static long s070, s071, s072, s073, s074, s075, s076, s077, s078, s079;
static long s080, s081, s082, s083, s084, s085, s086, s087, s088, s089;
static long s090, s091, s092, s093, s094, s095, s096, s097, s098, s099;
static long s100, s101, s102, s103, s104, s105, s106, s107, s108, s109;
static long s110, s111, s112, s113, s114, s115, s116, s117, s118, s119;
static long s120, s121, s122, s123, s124, s125, s126, s127, s128, s129;
static long s130, s131, s132, s133, s134, s135, s136, s137, s138, s139;
static long s140, s141, s142, s143, s144, s145, s146, s147, s148, s149;
static long s150, s151, s152, s153, s154, s155, s156, s157, s158, s159;
static long s160, s161, s162, s163, s164, s165, s166, s167, s168, s169;
static long s170, s171, s172, s173, s174, s175, s176, s177, s178, s179;
static long s180, s181, s182, s183, s184, s185, s186, s187, s188, s189;
static long s190, s191, s192, s193, s194, s195, s196, s197, s198, s199;
static long s200, s201, s202, s203, s204, s205, s206, s207, s208, s209;
static long s210, s211, s212, s213, s214, s215, s216, s217, s218, s219;
static long s220, s221, s222, s223, s224, s225, s226, s227, s228, s229;
static long s230, s231, s232, s233, s234, s235, s236, s237, s238, s239;
static long s240, s241, s242, s243, s244, s245, s246, s247, s248, s249;
static long s250, s251, s252, s253, s254, s255, s256, s257, s258, s259;
static long s260, s261, s262, s263, s264, s265, s266, s267, s268, s269;
static long s270, s271, s272, s273, s274, s275, s276, s277, s278, s279;
static long s280, s281, s282, s283, s284, s285, s286, s287, s288, s289;
static long s290, s291, s292, s293, s294, s295, s296, s297, s298, s299;
static {
for (Field f : ImplicitStringConcatManyLongs.class.getDeclaredFields()) {
if (Modifier.isStatic(f.getModifiers())) {
String name = f.getName();
try {
f.set(null, Long.valueOf(name.substring(1)));
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
}
public static void main(String[] args) throws Exception {
String res = "" +
s000 + s001 + s002 + s003 + s004 + s005 + s006 + s007 + s008 + s009 +
s010 + s011 + s012 + s013 + s014 + s015 + s016 + s017 + s018 + s019 +
s020 + s021 + s022 + s023 + s024 + s025 + s026 + s027 + s028 + s029 +
s030 + s031 + s032 + s033 + s034 + s035 + s036 + s037 + s038 + s039 +
s040 + s041 + s042 + s043 + s044 + s045 + s046 + s047 + s048 + s049 +
s050 + s051 + s052 + s053 + s054 + s055 + s056 + s057 + s058 + s059 +
s060 + s061 + s062 + s063 + s064 + s065 + s066 + s067 + s068 + s069 +
s070 + s071 + s072 + s073 + s074 + s075 + s076 + s077 + s078 + s079 +
s080 + s081 + s082 + s083 + s084 + s085 + s086 + s087 + s088 + s089 +
s090 + s091 + s092 + s093 + s094 + s095 + s096 + s097 + s098 + s099 +
s100 + s101 + s102 + s103 + s104 + s105 + s106 + s107 + s108 + s109 +
s110 + s111 + s112 + s113 + s114 + s115 + s116 + s117 + s118 + s119 +
s120 + s121 + s122 + s123 + s124 + s125 + s126 + s127 + s128 + s129 +
s130 + s131 + s132 + s133 + s134 + s135 + s136 + s137 + s138 + s139 +
s140 + s141 + s142 + s143 + s144 + s145 + s146 + s147 + s148 + s149 +
s150 + s151 + s152 + s153 + s154 + s155 + s156 + s157 + s158 + s159 +
s160 + s161 + s162 + s163 + s164 + s165 + s166 + s167 + s168 + s169 +
s170 + s171 + s172 + s173 + s174 + s175 + s176 + s177 + s178 + s179 +
s180 + s181 + s182 + s183 + s184 + s185 + s186 + s187 + s188 + s189 +
s190 + s191 + s192 + s193 + s194 + s195 + s196 + s197 + s198 + s199 +
s200 + s201 + s202 + s203 + s204 + s205 + s206 + s207 + s208 + s209 +
s210 + s211 + s212 + s213 + s214 + s215 + s216 + s217 + s218 + s219 +
s220 + s221 + s222 + s223 + s224 + s225 + s226 + s227 + s228 + s229 +
s230 + s231 + s232 + s233 + s234 + s235 + s236 + s237 + s238 + s239 +
s240 + s241 + s242 + s243 + s244 + s245 + s246 + s247 + s248 + s249 +
s250 + s251 + s252 + s253 + s254 + s255 + s256 + s257 + s258 + s259 +
s260 + s261 + s262 + s263 + s264 + s265 + s266 + s267 + s268 + s269 +
s270 + s271 + s272 + s273 + s274 + s275 + s276 + s277 + s278 + s279 +
s280 + s281 + s282 + s283 + s284 + s285 + s286 + s287 + s288 + s289 +
s290 + s291 + s292 + s293 + s294 + s295 + s296 + s297 + s298 + s299;
StringBuilder sb = new StringBuilder();
for (int c = 0; c < 300; c++) {
sb.append(c);
}
test(sb.toString(), res);
}
public static void test(String expected, String actual) {
// Fingers crossed: String concat should work.
if (!expected.equals(actual)) {
throw new IllegalStateException("Expected = " + expected + ", actual = " + actual);
}
}
}

View File

@ -0,0 +1,127 @@
/*
* Copyright (c) 2015, 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 implicit String concatenations, multiple shapes.
*
* @compile ImplicitStringConcatShapes.java
* @run main/othervm ImplicitStringConcatShapes
*
* @compile -XDstringConcat=inline ImplicitStringConcatShapes.java
* @run main/othervm ImplicitStringConcatShapes
*
* @compile -XDstringConcat=indy -source 1.9 -target 1.9 ImplicitStringConcatShapes.java
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT ImplicitStringConcatShapes
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatShapes
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
*
* @compile -XDstringConcat=indyWithConstants -source 1.9 -target 1.9 ImplicitStringConcatShapes.java
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT ImplicitStringConcatShapes
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true ImplicitStringConcatShapes
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true ImplicitStringConcatShapes
*/
public class ImplicitStringConcatShapes {
public static void test(String expected, String actual) {
// Fingers crossed: String concat should work.
if (!expected.equals(actual)) {
StringBuilder sb = new StringBuilder();
sb.append("Expected = ");
sb.append(expected);
sb.append(", actual = ");
sb.append(actual);
throw new IllegalStateException(sb.toString());
}
}
static class MyClass {
private final int i;
public MyClass(int i) {
this.i = i;
}
public String toString() {
return new StringBuilder("C(").append(i).append(")").toString();
}
}
static class MyClassNullToString {
public String toString() {
return null;
}
}
public static void main(String[] args) throws Exception {
new ImplicitStringConcatShapes().run();
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,313 @@
/*
* Copyright (c) 2015, 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.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
public class ImplicitStringConcatShapesTestGen {
public static String escapeToUnicode(String str) {
StringBuilder b = new StringBuilder();
for (char c : str.toCharArray()) {
if (c < 128) {
b.append(c);
} else {
b.append("\\u").append(String.format("%04X", (int) c));
}
}
return b.toString();
}
public static void main(String... args) throws IOException {
PrintWriter pw = new PrintWriter(System.out);
String[] types = {
"boolean",
"byte",
"byteMinus",
"char",
"short",
"shortMinus",
"int",
"intMinus",
"integer",
"integerNull",
"float",
"floatMinus",
"long",
"longMinus",
"double",
"doubleMinus",
"object",
"objectNull",
"objectNullToString",
"String",
"StringUTF16",
"StringU1",
"StringU2",
"intArrayNull",
"objectArrayNull",
};
for (String t : Files.readAllLines(Paths.get("ImplicitStringConcatShapes-head.template"))) {
pw.println(t);
}
Map<String, String> values = new HashMap<>();
Random current = new Random(12345);
for (int mode = 0; mode <= 2; mode++) {
for (String type : types) {
int i = current.nextInt(100);
boolean isStatic = (mode | 1) == 1;
boolean isFinal = (mode | 2) == 2;
String fieldName = (isStatic ? "s" : "") + (isFinal ? "f" : "") + "_" + typeSig(type);
String value = initValue(type, i);
String stringValue = stringValue(type, i);
values.put(fieldName, stringValue);
pw.printf(" %s %s %s %s = %s;%n", isStatic ? "static" : "", isFinal ? "final" : "", typeValue(type, i), fieldName, value);
}
}
pw.println();
List<String> lines = new ArrayList<>();
List<String> l = new ArrayList<>(values.keySet());
for (String l1 : l) {
lines.add(String.format("test(\"%s\", \"\" + %s);",
escapeToUnicode(values.get(l1)),
l1
));
}
for (String l1 : l) {
for (String l2 : l) {
lines.add(String.format("test(\"%s\", \"\" + %s + %s);",
escapeToUnicode(values.get(l1) + values.get(l2)),
l1, l2
));
}
}
final int STRIDE = 1000;
int strides = lines.size() / STRIDE + 1;
pw.println(" public void run() {");
for (int c = 0; c < strides; c++) {
pw.println(" run" + c + "();");
}
pw.println(" }");
pw.println();
for (int c = 0; c < strides; c++) {
pw.println(" public void run" + c + "() {");
for (String line : lines.subList(c * STRIDE, Math.min(lines.size(), (c+1) * STRIDE))) {
pw.println(" " + line);
}
pw.println(" }");
pw.println();
}
pw.println("}");
pw.flush();
pw.close();
}
private static String typeSig(String type) {
switch (type) {
case "boolean": return "bl";
case "byte": return "b";
case "byteMinus": return "bM";
case "short": return "s";
case "shortMinus": return "sM";
case "char": return "c";
case "int": return "i";
case "intMinus": return "iM";
case "integer": return "I";
case "integerNull": return "IN";
case "float": return "f";
case "floatMinus": return "fM";
case "long": return "l";
case "longMinus": return "lM";
case "double": return "d";
case "doubleMinus": return "dM";
case "String": return "str";
case "StringUTF16": return "strU";
case "StringU1": return "strU1";
case "StringU2": return "strU2";
case "object": return "o";
case "objectNull": return "oN";
case "objectNullToString": return "oNtS";
case "intArrayNull": return "iAN";
case "objectArrayNull": return "oAN";
default:
throw new IllegalStateException();
}
}
private static String typeValue(String type, int i) {
switch (type) {
case "boolean":
case "byte":
case "byteMinus":
case "char":
case "short":
case "shortMinus":
case "int":
case "intMinus":
case "float":
case "floatMinus":
case "long":
case "longMinus":
case "double":
case "doubleMinus":
return type.replace("Minus", "");
case "String":
case "StringUTF16":
case "StringU1":
case "StringU2":
return "String";
case "object":
case "objectNull":
case "objectNullToString":
return "Object";
case "integer":
case "integerNull":
return "Integer";
case "intArrayNull":
return "int[]";
case "objectArrayNull":
return "Object[]";
default:
throw new IllegalStateException();
}
}
private static String initValue(String type, int i) {
switch (type) {
case "boolean":
return String.valueOf((i & 1) == 1);
case "byte":
return String.valueOf(i);
case "byteMinus":
return String.valueOf(-i);
case "short":
return String.valueOf(i*100);
case "shortMinus":
return String.valueOf(-i*100);
case "intMinus":
return String.valueOf(-i*1_000_000);
case "int":
case "integer":
return String.valueOf(i*1_000_000);
case "long":
return String.valueOf(i*1_000_000_000) + "L";
case "longMinus":
return String.valueOf(-i*1_000_000_000) + "L";
case "char":
return "'" + (char)(i % 26 + 65) + "'";
case "double":
return String.valueOf(i) + ".0d";
case "doubleMinus":
return "-" + String.valueOf(i) + ".0d";
case "float":
return String.valueOf(i) + ".0f";
case "floatMinus":
return "-" + String.valueOf(i) + ".0f";
case "object":
return "new MyClass(" + i + ")";
case "objectNullToString":
return "new MyClassNullToString()";
case "integerNull":
case "objectNull":
case "intArrayNull":
case "objectArrayNull":
return "null";
case "String":
return "\"" + i + "\"";
case "StringUTF16":
return "\"\\u0451" + i + "\"";
case "StringU1":
return "\"\\u0001" + i + "\"";
case "StringU2":
return "\"\\u0002" + i + "\"";
default:
throw new IllegalStateException();
}
}
private static String stringValue(String type, int i) {
switch (type) {
case "boolean":
return String.valueOf((i & 1) == 1);
case "byte":
return String.valueOf(i);
case "byteMinus":
return String.valueOf(-i);
case "short":
return String.valueOf(i*100);
case "shortMinus":
return String.valueOf(-i*100);
case "intMinus":
return String.valueOf(-i*1_000_000);
case "int":
case "integer":
return String.valueOf(i*1_000_000);
case "long":
return String.valueOf(i*1_000_000_000);
case "longMinus":
return String.valueOf(-i*1_000_000_000);
case "char":
return String.valueOf((char) (i % 26 + 65));
case "double":
case "float":
return String.valueOf(i) + ".0";
case "doubleMinus":
case "floatMinus":
return "-" + String.valueOf(i) + ".0";
case "object":
return "C(" + i + ")";
case "integerNull":
case "objectNull":
case "objectNullToString":
case "intArrayNull":
case "objectArrayNull":
return "null";
case "String":
return "" + i;
case "StringUTF16":
return "\u0451" + i;
case "StringU1":
return "\u0001" + i;
case "StringU2":
return "\u0002" + i;
default:
throw new IllegalStateException();
}
}
}

View File

@ -0,0 +1,293 @@
/*
* Copyright (c) 2015, 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.
*/
import java.io.Serializable;
import java.lang.invoke.*;
import java.util.concurrent.Callable;
/**
* @test
* @summary Test input invariants for StringConcatFactory
*
* @compile StringConcatFactoryInvariants.java
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT StringConcatFactoryInvariants
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true StringConcatFactoryInvariants
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.cache=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.cache=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.cache=true StringConcatFactoryInvariants
*
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=BC_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_SB_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true StringConcatFactoryInvariants
* @run main/othervm -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT -Djava.lang.invoke.stringConcat.debug=true -Djava.lang.invoke.stringConcat.cache=true StringConcatFactoryInvariants
*
*/
public class StringConcatFactoryInvariants {
private static final char TAG_ARG = '\u0001';
private static final char TAG_CONST = '\u0002';
public static void main(String[] args) throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.publicLookup();
String methodName = "foo";
MethodType mt = MethodType.methodType(String.class, String.class, int.class);
String recipe = "" + TAG_ARG + TAG_ARG + TAG_CONST;
String[] constants = new String[]{"bar"};
final int LIMIT = 200;
// Simple factory: check for dynamic arguments overflow
Class<?>[] underThreshold = new Class<?>[LIMIT - 1];
Class<?>[] threshold = new Class<?>[LIMIT];
Class<?>[] overThreshold = new Class<?>[LIMIT + 1];
StringBuilder sbUnderThreshold = new StringBuilder();
sbUnderThreshold.append(TAG_CONST);
for (int c = 0; c < LIMIT - 1; c++) {
underThreshold[c] = int.class;
threshold[c] = int.class;
overThreshold[c] = int.class;
sbUnderThreshold.append(TAG_ARG);
}
threshold[LIMIT - 1] = int.class;
overThreshold[LIMIT - 1] = int.class;
overThreshold[LIMIT] = int.class;
String recipeEmpty = "";
String recipeUnderThreshold = sbUnderThreshold.toString();
String recipeThreshold = sbUnderThreshold.append(TAG_ARG).toString();
String recipeOverThreshold = sbUnderThreshold.append(TAG_ARG).toString();
MethodType mtEmpty = MethodType.methodType(String.class);
MethodType mtUnderThreshold = MethodType.methodType(String.class, underThreshold);
MethodType mtThreshold = MethodType.methodType(String.class, threshold);
MethodType mtOverThreshold = MethodType.methodType(String.class, overThreshold);
// Check the basic functionality is working
{
CallSite cs = StringConcatFactory.makeConcat(lookup, methodName, mt);
test("foo42", (String) cs.getTarget().invokeExact("foo", 42));
}
{
CallSite cs = StringConcatFactory.makeConcatWithConstants(lookup, methodName, mt, recipe, constants);
test("foo42bar", (String) cs.getTarget().invokeExact("foo", 42));
}
// Simple factory, check for nulls:
failNPE("Lookup is null",
() -> StringConcatFactory.makeConcat(null, methodName, mt));
failNPE("Method name is null",
() -> StringConcatFactory.makeConcat(lookup, null, mt));
failNPE("MethodType is null",
() -> StringConcatFactory.makeConcat(lookup, methodName, null));
// Advanced factory, check for nulls:
failNPE("Lookup is null",
() -> StringConcatFactory.makeConcatWithConstants(null, methodName, mt, recipe, constants));
failNPE("Method name is null",
() -> StringConcatFactory.makeConcatWithConstants(lookup, null, mt, recipe, constants));
failNPE("MethodType is null",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, null, recipe, constants));
failNPE("Recipe is null",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, mt, null, constants));
failNPE("Constants vararg is null",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, mt, recipe, null));
// Simple factory, check for return type
fail("Return type: void",
() -> StringConcatFactory.makeConcat(lookup, methodName, MethodType.methodType(void.class, String.class, int.class)));
fail("Return type: int",
() -> StringConcatFactory.makeConcat(lookup, methodName, MethodType.methodType(int.class, String.class, int.class)));
fail("Return type: StringBuilder",
() -> StringConcatFactory.makeConcat(lookup, methodName, MethodType.methodType(StringBuilder.class, String.class, int.class)));
ok("Return type: Object",
() -> StringConcatFactory.makeConcat(lookup, methodName, MethodType.methodType(Object.class, String.class, int.class)));
ok("Return type: CharSequence",
() -> StringConcatFactory.makeConcat(lookup, methodName, MethodType.methodType(CharSequence.class, String.class, int.class)));
ok("Return type: Serializable",
() -> StringConcatFactory.makeConcat(lookup, methodName, MethodType.methodType(Serializable.class, String.class, int.class)));
// Advanced factory, check for return types
fail("Return type: void",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, MethodType.methodType(void.class, String.class, int.class), recipe, constants));
fail("Return type: int",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, MethodType.methodType(int.class, String.class, int.class), recipe, constants));
fail("Return type: StringBuilder",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, MethodType.methodType(StringBuilder.class, String.class, int.class), recipe, constants));
ok("Return type: Object",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, MethodType.methodType(Object.class, String.class, int.class), recipe, constants));
ok("Return type: CharSequence",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, MethodType.methodType(CharSequence.class, String.class, int.class), recipe, constants));
ok("Return type: Serializable",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, MethodType.methodType(Serializable.class, String.class, int.class), recipe, constants));
// Simple factory: check for dynamic arguments overflow
ok("Dynamic arguments is under limit",
() -> StringConcatFactory.makeConcat(lookup, methodName, mtUnderThreshold));
ok("Dynamic arguments is at the limit",
() -> StringConcatFactory.makeConcat(lookup, methodName, mtThreshold));
fail("Dynamic arguments is over the limit",
() -> StringConcatFactory.makeConcat(lookup, methodName, mtOverThreshold));
// Advanced factory: check for dynamic arguments overflow
ok("Dynamic arguments is under limit",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, mtUnderThreshold, recipeUnderThreshold, constants));
ok("Dynamic arguments is at the limit",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, mtThreshold, recipeThreshold, constants));
fail("Dynamic arguments is over the limit",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, mtOverThreshold, recipeOverThreshold, constants));
// Advanced factory: check for mismatched recipe and Constants
ok("Static arguments and recipe match",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, mtThreshold, recipeThreshold, "bar"));
fail("Static arguments and recipe mismatch",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, mtThreshold, recipeThreshold, "bar", "baz"));
// Advanced factory: check for mismatched recipe and dynamic arguments
fail("Dynamic arguments and recipe mismatch",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, mtThreshold, recipeUnderThreshold, constants));
ok("Dynamic arguments and recipe match",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, mtThreshold, recipeThreshold, constants));
fail("Dynamic arguments and recipe mismatch",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, mtThreshold, recipeOverThreshold, constants));
// Test passing array as constant
{
String[] arg = {"boo", "bar"};
CallSite cs1 = StringConcatFactory.makeConcatWithConstants(lookup, methodName, MethodType.methodType(String.class, int.class), "" + TAG_ARG + TAG_CONST + TAG_CONST, arg);
test("42boobar", (String) cs1.getTarget().invokeExact(42));
}
// Test passing null constant
ok("Can pass regular constants",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, MethodType.methodType(String.class, int.class), "" + TAG_ARG + TAG_CONST, "foo"));
failNPE("Cannot pass null constants",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, MethodType.methodType(String.class, int.class), "" + TAG_ARG + TAG_CONST, new String[]{null}));
// Simple factory: test empty arguments
ok("Ok to pass empty arguments",
() -> StringConcatFactory.makeConcat(lookup, methodName, mtEmpty));
// Advanced factory: test empty arguments
ok("Ok to pass empty arguments",
() -> StringConcatFactory.makeConcatWithConstants(lookup, methodName, mtEmpty, recipeEmpty));
}
public static void ok(String msg, Callable runnable) {
try {
runnable.call();
} catch (Throwable e) {
e.printStackTrace();
throw new IllegalStateException(msg + ", should have passed", e);
}
}
public static void fail(String msg, Callable runnable) {
boolean expected = false;
try {
runnable.call();
} catch (StringConcatException e) {
expected = true;
} catch (Throwable e) {
e.printStackTrace();
}
if (!expected) {
throw new IllegalStateException(msg + ", should have failed with StringConcatException");
}
}
public static void failNPE(String msg, Callable runnable) {
boolean expected = false;
try {
runnable.call();
} catch (NullPointerException e) {
expected = true;
} catch (Throwable e) {
e.printStackTrace();
}
if (!expected) {
throw new IllegalStateException(msg + ", should have failed with NullPointerException");
}
}
public static void test(String expected, String actual) {
// Fingers crossed: String concat should work.
if (!expected.equals(actual)) {
StringBuilder sb = new StringBuilder();
sb.append("Expected = ");
sb.append(expected);
sb.append(", actual = ");
sb.append(actual);
throw new IllegalStateException(sb.toString());
}
}
}

View File

@ -0,0 +1,26 @@
# Copyright (c) 2015, 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.
#!/bin/bash
javac ImplicitStringConcatShapesTestGen.java
java ImplicitStringConcatShapesTestGen > ImplicitStringConcatShapes.java
rm ImplicitStringConcatShapesTestGen.class

View File

@ -28,7 +28,7 @@
* @compile InvokeDynamicPrintArgs.java
* @run main/othervm
* indify.Indify
* --verify-specifier-count=3
* --verify-specifier-count=8
* --expand-properties --classpath ${test.classes}
* --java test.java.lang.invoke.InvokeDynamicPrintArgs --check-output
* @run main/othervm

View File

@ -28,7 +28,7 @@
* @compile MethodHandleConstants.java
* @run main/othervm
* indify.Indify
* --verify-specifier-count=0
* --verify-specifier-count=4
* --expand-properties --classpath ${test.classes}
* --java test.java.lang.invoke.MethodHandleConstants --check-output
* @run main/othervm

View File

@ -25,8 +25,7 @@
* @test
* @bug 8047031
* @summary SocketPermission tests for legacy socket types
* @library ../../../lib/testlibrary
* @run testng/othervm/policy=policy SocketPermissionTest
* @run testng/othervm SocketPermissionTest
* @key intermittent
*/
import java.io.IOException;
@ -39,186 +38,279 @@ import java.net.Socket;
import java.net.SocketPermission;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.Policy;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.util.Arrays;
import java.util.function.Function;
import java.util.function.IntConsumer;
import static jdk.testlibrary.Utils.getFreePort;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import static java.nio.charset.StandardCharsets.UTF_8;
public class SocketPermissionTest {
private int freePort = -1;
//positive tests
@Test(dataProvider = "positiveProvider")
public void testPositive(Function<String, AccessControlContext> genAcc, IntConsumer func) {
String addr = "localhost:" + freePort;
AccessControlContext acc = genAcc.apply(addr);
AccessController.doPrivileged((PrivilegedAction) () -> {
func.accept(freePort);
return null;
}, acc);
}
//negative tests
@Test(dataProvider = "negativeProvider", expectedExceptions = SecurityException.class)
public void testNegative(AccessControlContext acc, IntConsumer func) {
AccessController.doPrivileged((PrivilegedAction) () -> {
func.accept(freePort);
return null;
}, acc);
}
@BeforeMethod
public void setFreePort() throws Exception {
freePort = getFreePort();
public void setupSecurityManager() throws Exception {
// All permissions, a specific ACC will be used to when testing
// with a reduced permission set.
Policy.setPolicy(new Policy() {
final PermissionCollection perms = new Permissions();
{ perms.add(new java.security.AllPermission()); }
public PermissionCollection getPermissions(ProtectionDomain domain) {
return perms;
}
public PermissionCollection getPermissions(CodeSource codesource) {
return perms;
}
public boolean implies(ProtectionDomain domain, Permission perm) {
return perms.implies(perm);
}
} );
System.setSecurityManager(new SecurityManager());
}
@DataProvider
public Object[][] positiveProvider() {
//test for SocketPermission "host:port","connect,resolve";
Function<String, AccessControlContext> generateAcc1 = (addr) -> getAccessControlContext(
new SocketPermission(addr, "listen, connect,resolve"));
IntConsumer func1 = (i) -> connectSocketTest(i);
IntConsumer func2 = (i) -> connectDatagramSocketTest(i);
static final AccessControlContext RESTRICTED_ACC = getAccessControlContext();
//test for SocketPermission "localhost:1024-","accept";
Function<String, AccessControlContext> generateAcc2 = (addr) -> getAccessControlContext(
new SocketPermission(addr, "listen,connect,resolve"),
new SocketPermission("localhost:1024-", "accept"));
IntConsumer func3 = (i) -> acceptServerSocketTest(i);
@Test
public void connectSocketTest() throws Exception {
try (ServerSocket ss = new ServerSocket(0)) {
int port = ss.getLocalPort();
//test for SocketPermission "229.227.226.221", "connect,accept"
Function<String, AccessControlContext> generateAcc3 = (addr) -> getAccessControlContext(
new SocketPermission(addr, "listen,resolve"),
new SocketPermission("229.227.226.221", "connect,accept"));
IntConsumer func4 = (i) -> sendDatagramPacketTest(i);
IntConsumer func5 = (i) -> joinGroupMulticastTest(i);
//test for SocketPermission "host:port", "listen"
Function<String, AccessControlContext> generateAcc4 = (addr) -> getAccessControlContext(
new SocketPermission(addr, "listen"));
IntConsumer func6 = (i) -> listenDatagramSocketTest(i);
IntConsumer func7 = (i) -> listenMulticastSocketTest(i);
IntConsumer func8 = (i) -> listenServerSocketTest(i);
return new Object[][]{
{generateAcc1, func1},
{generateAcc1, func2},
{generateAcc2, func3},
{generateAcc3, func4},
{generateAcc3, func5},
{generateAcc4, func6},
{generateAcc4, func7},
{generateAcc4, func8}
};
}
@DataProvider
public Object[][] negativeProvider() {
IntConsumer[] funcs = {i -> connectSocketTest(i),
i -> connectDatagramSocketTest(i), i -> acceptServerSocketTest(i),
i -> sendDatagramPacketTest(i), i -> joinGroupMulticastTest(i),
i -> listenDatagramSocketTest(i), i -> listenMulticastSocketTest(i),
i -> listenServerSocketTest(i)};
return Arrays.stream(funcs).map(f -> {
//Construct an AccessControlContext without SocketPermission
String addr = "localhost:" + port;
AccessControlContext acc = getAccessControlContext(
new java.io.FilePermission("<<ALL FILES>>", "read,write,execute,delete"),
new java.net.NetPermission("*"),
new java.util.PropertyPermission("*", "read,write"),
new java.lang.reflect.ReflectPermission("*"),
new java.lang.RuntimePermission("*"),
new java.security.SecurityPermission("*"),
new java.io.SerializablePermission("*"));
return new Object[]{acc, f};
}).toArray(Object[][]::new);
}
new SocketPermission(addr, "listen,connect,resolve"));
public void connectSocketTest(int port) {
try (ServerSocket server = new ServerSocket(port);
Socket client = new Socket(InetAddress.getLocalHost(), port);) {
} catch (IOException ex) {
throw new RuntimeException(ex);
// Positive
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
try (Socket client = new Socket(InetAddress.getLocalHost(), port)) {
}
return null;
}, acc);
//Negative
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
Socket client = new Socket(InetAddress.getLocalHost(), port);
fail("Expected SecurityException");
return null;
}, RESTRICTED_ACC);
} catch (SecurityException expected) { }
}
}
public void connectDatagramSocketTest(int port) {
String msg = "Hello";
try {
InetAddress me = InetAddress.getLocalHost();
try (DatagramSocket ds = new DatagramSocket(port, me)) {
DatagramPacket dp = new DatagramPacket(msg.getBytes(),
msg.length(), me, port);
@Test
public void connectDatagramSocketTest() throws Exception {
byte[] msg = "Hello".getBytes(UTF_8);
InetAddress lh = InetAddress.getLocalHost();
try (DatagramSocket ds = new DatagramSocket(0)) {
int port = ds.getLocalPort();
String addr = lh.getHostAddress() + ":" + port;
AccessControlContext acc = getAccessControlContext(
new SocketPermission(addr, "connect,resolve"));
// Positive
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
DatagramPacket dp = new DatagramPacket(msg, msg.length, lh, port);
ds.send(dp);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
return null;
}, acc);
// Negative
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
DatagramPacket dp = new DatagramPacket(msg, msg.length, lh, port);
ds.send(dp);
fail("Expected SecurityException");
return null;
}, RESTRICTED_ACC);
} catch (SecurityException expected) { }
}
}
public void acceptServerSocketTest(int port) {
try {
InetAddress me = InetAddress.getLocalHost();
try (ServerSocket server = new ServerSocket(port)) {
Socket client = new Socket(me, port);
server.accept();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
@Test
public void acceptServerSocketTest() throws Exception {
try (ServerSocket ss = new ServerSocket(0)) {
int port = ss.getLocalPort();
String addr = "localhost:" + port;
AccessControlContext acc = getAccessControlContext(
new SocketPermission(addr, "listen,connect,resolve"),
new SocketPermission("localhost:1024-", "accept"));
// Positive
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
InetAddress me = InetAddress.getLocalHost();
try (Socket client = new Socket(me, port)) {
ss.accept();
}
return null;
}, acc);
// Negative
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
InetAddress me = InetAddress.getLocalHost();
try (Socket client = new Socket(me, port)) {
ss.accept();
}
fail("Expected SecurityException");
return null;
}, RESTRICTED_ACC);
} catch (SecurityException expected) { }
}
}
public static void sendDatagramPacketTest(int port) {
String msg = "Hello";
try {
InetAddress group = InetAddress.getByName("229.227.226.221");
try (DatagramSocket s = new DatagramSocket(port)) {
DatagramPacket hi = new DatagramPacket(msg.getBytes(),
msg.length(), group, port);
s.send(hi);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
@Test
public void sendDatagramPacketTest() throws Exception {
byte[] msg = "Hello".getBytes(UTF_8);
InetAddress group = InetAddress.getByName("229.227.226.221");
try (DatagramSocket ds = new DatagramSocket(0)) {
int port = ds.getLocalPort();
String addr = "localhost:" + port;
//test for SocketPermission "229.227.226.221", "connect,accept"
AccessControlContext acc = getAccessControlContext(
new SocketPermission(addr, "listen,resolve"),
new SocketPermission("229.227.226.221", "connect,accept"));
// Positive
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
DatagramPacket hi = new DatagramPacket(msg, msg.length, group, port);
ds.send(hi);
return null;
}, acc);
// Negative
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
DatagramPacket hi = new DatagramPacket(msg, msg.length, group, port);
ds.send(hi);
fail("Expected SecurityException");
return null;
}, RESTRICTED_ACC);
} catch (SecurityException expected) { }
}
}
public void joinGroupMulticastTest(int port) {
try {
InetAddress group = InetAddress.getByName("229.227.226.221");
try (MulticastSocket s = new MulticastSocket(port)) {
@Test
public void joinGroupMulticastTest() throws Exception {
InetAddress group = InetAddress.getByName("229.227.226.221");
try (MulticastSocket s = new MulticastSocket(0)) {
int port = s.getLocalPort();
String addr = "localhost:" + port;
AccessControlContext acc = getAccessControlContext(
new SocketPermission(addr, "listen,resolve"),
new SocketPermission("229.227.226.221", "connect,accept"));
// Positive
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
s.joinGroup(group);
s.leaveGroup(group);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
return null;
}, acc);
// Negative
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
s.joinGroup(group);
s.leaveGroup(group);
fail("Expected SecurityException");
return null;
}, RESTRICTED_ACC);
} catch (SecurityException expected) { }
}
}
public void listenDatagramSocketTest(int port) {
try (DatagramSocket ds = new DatagramSocket(port)) {
} catch (IOException ex) {
throw new RuntimeException(ex);
}
@Test
public void listenDatagramSocketTest() throws Exception {
// the hardcoded port number doesn't really matter since we expect the
// security permission to be checked before the underlying operation.
int port = 8899;
String addr = "localhost:" + port;
AccessControlContext acc = getAccessControlContext(
new SocketPermission(addr, "listen"));
// Positive
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
try (DatagramSocket ds = new DatagramSocket(port)) { }
catch (IOException intermittentlyExpected) { /* ignore */ }
return null;
}, acc);
// Negative
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
try (DatagramSocket ds = new DatagramSocket(port)) { }
catch (IOException intermittentlyExpected) { /* ignore */ }
fail("Expected SecurityException");
return null;
}, RESTRICTED_ACC);
} catch (SecurityException expected) { }
}
public void listenMulticastSocketTest(int port) {
try (MulticastSocket ms = new MulticastSocket(port)) {
} catch (IOException ex) {
throw new RuntimeException(ex);
}
@Test
public void listenMulticastSocketTest() throws Exception {
// the hardcoded port number doesn't really matter since we expect the
// security permission to be checked before the underlying operation.
int port = 8899;
String addr = "localhost:" + port;
AccessControlContext acc = getAccessControlContext(
new SocketPermission(addr, "listen"));
// Positive
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
try (MulticastSocket ms = new MulticastSocket(port)) { }
catch (IOException intermittentlyExpected) { /* ignore */ }
return null;
}, acc);
// Negative
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
try (MulticastSocket ms = new MulticastSocket(port)) { }
catch (IOException intermittentlyExpected) { /* ignore */ }
fail("Expected SecurityException");
return null;
}, RESTRICTED_ACC);
} catch (SecurityException expected) { }
}
public void listenServerSocketTest(int port) {
try (ServerSocket ms = new ServerSocket(port)) {
} catch (IOException ex) {
throw new RuntimeException(ex);
}
@Test
public void listenServerSocketTest() throws Exception {
// the hardcoded port number doesn't really matter since we expect the
// security permission to be checked before the underlying operation.
int port = 8899;
String addr = "localhost:" + port;
AccessControlContext acc = getAccessControlContext(
new SocketPermission(addr, "listen"));
// Positive
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
try (ServerSocket ss = new ServerSocket(port)) { }
catch (IOException intermittentlyExpected) { /* ignore */ }
return null;
}, acc);
// Negative
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
try (ServerSocket ss = new ServerSocket(port)) { }
catch (IOException intermittentlyExpected) { /* ignore */ }
fail("Expected SecurityException");
return null;
}, RESTRICTED_ACC);
} catch (SecurityException expected) { }
}
private static AccessControlContext getAccessControlContext(Permission... ps) {
@ -234,4 +326,15 @@ public class SocketPermissionTest {
return new AccessControlContext(new ProtectionDomain[]{pd});
}
// Standalone entry point for running with, possibly older, JDKs.
public static void main(String[] args) throws Throwable {
SocketPermissionTest test = new SocketPermissionTest();
test.setupSecurityManager();
for (java.lang.reflect.Method m : SocketPermissionTest.class.getDeclaredMethods()) {
if (m.getAnnotation(Test.class) != null) {
System.out.println("Invoking " + m.getName());
m.invoke(test);
}
}
}
}

View File

@ -1,3 +0,0 @@
grant {
permission java.security.AllPermission;
};

View File

@ -23,13 +23,16 @@
/**
* @test
* @bug 4768755 4677045
* @summary URL.equal(URL) is inconsistant for opaque URI.toURL()
* and new URL(URI.toString)
* @bug 4768755 4677045 8147462
* @summary URL.equal(URL) is inconsistent for opaque URI.toURL()
* and new URL(URI.toString)
* URI.toURL() does not always work as specified
* Ensure URIs representing invalid/malformed URLs throw similar
* exception with new URL(URI.toString()) and URI.toURL()
*/
import java.net.*;
import java.util.Objects;
public class URItoURLTest {
@ -39,19 +42,43 @@ public class URItoURLTest {
URL classUrl = testClass.getClass().
getResource("/java/lang/Object.class");
String[] uris = { "mailto:xyz@abc.de",
String[] uris = {
"mailto:xyz@abc.de",
"file:xyz#ab",
"http:abc/xyz/pqr",
"http:abc/xyz/pqr?id=x%0a&ca=true",
"file:/C:/v700/dev/unitTesting/tests/apiUtil/uri",
"http:///p",
"file:/C:/v700/dev/unitTesting/tests/apiUtil/uri",
"file:/C:/v700/dev%20src/unitTesting/tests/apiUtil/uri",
"file:/C:/v700/dev%20src/./unitTesting/./tests/apiUtil/uri",
"http://localhost:80/abc/./xyz/../pqr?id=x%0a&ca=true",
"file:./test/./x",
"file:./././%20#i=3",
"file:?hmm",
"file:.#hmm",
classUrl.toExternalForm(),
};
// Strings that represent valid URIs but invalid URLs that should throw
// MalformedURLException both when calling toURL and new URL(String)
String[] malformedUrls = {
"test:/test",
"fiel:test",
};
// Non-absolute URIs should throw IAE when calling toURL but will throw
// MalformedURLException when calling new URL
String[] illegalUris = {
"./test",
"/test",
};
boolean isTestFailed = false;
boolean isURLFailed = false;
for (int i = 0; i < uris.length; i++) {
URI uri = URI.create(uris[i]);
for (String uriString : uris) {
URI uri = URI.create(uriString);
URL url1 = new URL(uri.toString());
URL url2 = uri.toURL();
@ -107,6 +134,42 @@ public class URItoURLTest {
System.out.println();
isURLFailed = false;
}
for (String malformedUrl : malformedUrls) {
Exception toURLEx = null;
Exception newURLEx = null;
try {
new URI(malformedUrl).toURL();
} catch (Exception e) {
// expected
toURLEx = e;
}
try {
new URL(new URI(malformedUrl).toString());
} catch (Exception e) {
// expected
newURLEx = e;
}
if (!(toURLEx instanceof MalformedURLException) ||
!(newURLEx instanceof MalformedURLException) ||
!toURLEx.getMessage().equals(newURLEx.getMessage())) {
isTestFailed = true;
System.out.println("Expected the same MalformedURLException: " +
newURLEx + " vs " + toURLEx);
}
}
for (String illegalUri : illegalUris) {
try {
new URI(illegalUri).toURL();
} catch (IllegalArgumentException e) {
// pass
}
try {
new URL(illegalUri);
} catch (MalformedURLException e) {
// pass
}
}
if (isTestFailed) {
throw new Exception("URI.toURL() test failed");
}

View File

@ -0,0 +1,41 @@
/*
* 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 8147962
* @summary Verify URLs with upper-case protocols parse correctly in any
* locale
* @run main/othervm LocaleDependentURLTest
*/
import java.net.*;
import java.util.Locale;
public class LocaleDependentURLTest {
public static void main(String args[]) throws MalformedURLException {
for (Locale locale : Locale.getAvailableLocales()) {
Locale.setDefault(locale);
new URL("FILE:///TMP/X");
}
}
}

View File

@ -0,0 +1,124 @@
/*
* 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 8148192
* @summary Invoking close asynchronously can cause register to fail with
* an IOException rather than a ClosedWatchServiceException
* @run main LotsOfCloses
*/
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchService;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class LotsOfCloses {
private static final Random RAND = new Random();
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("tmp");
ExecutorService pool = Executors.newCachedThreadPool();
try {
// run the test repeatedly
long start = System.currentTimeMillis();
while ((System.currentTimeMillis() - start) < 5000) {
test(dir, pool);
}
} finally {
pool.shutdown();
}
}
/**
* Create a WatchService to watch for changes in the given directory
* and then attempt to close the WatchService and change a registration
* at the same time.
*/
static void test(Path dir, ExecutorService pool) throws Exception {
WatchService watcher = FileSystems.getDefault().newWatchService();
// initial registration
dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
// submit tasks to close the WatchService and update the registration
Future<Void> closeResult;
Future<Boolean> registerResult;
if (RAND.nextBoolean()) {
closeResult = pool.submit(newCloserTask(watcher));
registerResult = pool.submit(newRegisterTask(watcher, dir));
} else {
registerResult = pool.submit(newRegisterTask(watcher, dir));
closeResult = pool.submit(newCloserTask(watcher));
}
closeResult.get();
registerResult.get();
}
/**
* Returns a task that closes the given WatchService.
*/
static Callable<Void> newCloserTask(WatchService watcher) {
return () -> {
try {
watcher.close();
return null;
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
};
}
/**
* Returns a task that updates the registration of a directory with
* a WatchService.
*/
static Callable<Boolean> newRegisterTask(WatchService watcher, Path dir) {
return () -> {
try {
dir.register(watcher, StandardWatchEventKinds.ENTRY_DELETE);
return true;
} catch (ClosedWatchServiceException e) {
return false;
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
};
}
}

View File

@ -83,6 +83,7 @@ public class ArrayManagement {
int oldCapacity = capacity(list);
int oldModCount = modCount(list);
list.ensureCapacity(capacity);
assertTrue(capacity(list) >= capacity || capacity(list) == 0);
assertEquals(modCount(list),
(capacity(list) == oldCapacity)
? oldModCount

View File

@ -48,11 +48,14 @@ import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import static java.util.Objects.requireNonNull;
import static org.testng.Assert.fail;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
@ -533,6 +536,191 @@ public class Defaults {
"Should throw NPE");
}
/** A function that flipflops between running two other functions. */
static <T,U,V> BiFunction<T,U,V> twoStep(AtomicBoolean b,
BiFunction<T,U,V> first,
BiFunction<T,U,V> second) {
return (t, u) -> {
boolean bb = b.get();
try {
return (b.get() ? first : second).apply(t, u);
} finally {
b.set(!bb);
}};
}
/**
* Simulates races by modifying the map within the mapping function.
*/
@Test
public void testConcurrentMap_computeIfAbsent_racy() {
final ConcurrentMap<Long,Long> map = new ImplementsConcurrentMap<>();
final Long two = 2L;
Function<Long,Long> f, g;
// race not detected if function returns null
f = (k) -> { map.put(two, 42L); return null; };
assertNull(map.computeIfAbsent(two, f));
assertEquals(42L, (long)map.get(two));
map.clear();
f = (k) -> { map.put(two, 42L); return 86L; };
assertEquals(42L, (long)map.computeIfAbsent(two, f));
assertEquals(42L, (long)map.get(two));
// mapping function ignored if value already exists
map.put(two, 99L);
assertEquals(99L, (long)map.computeIfAbsent(two, f));
assertEquals(99L, (long)map.get(two));
}
/**
* Simulates races by modifying the map within the remapping function.
*/
@Test
public void testConcurrentMap_computeIfPresent_racy() {
final AtomicBoolean b = new AtomicBoolean(true);
final ConcurrentMap<Long,Long> map = new ImplementsConcurrentMap<>();
final Long two = 2L;
BiFunction<Long,Long,Long> f, g;
for (Long val : new Long[] { null, 86L }) {
map.clear();
// Function not invoked if no mapping exists
f = (k, v) -> { map.put(two, 42L); return val; };
assertNull(map.computeIfPresent(two, f));
assertNull(map.get(two));
map.put(two, 42L);
f = (k, v) -> { map.put(two, 86L); return val; };
g = (k, v) -> {
assertSame(two, k);
assertEquals(86L, (long)v);
return null;
};
assertNull(map.computeIfPresent(two, twoStep(b, f, g)));
assertFalse(map.containsKey(two));
assertTrue(b.get());
map.put(two, 42L);
f = (k, v) -> { map.put(two, 86L); return val; };
g = (k, v) -> {
assertSame(two, k);
assertEquals(86L, (long)v);
return 99L;
};
assertEquals(99L, (long)map.computeIfPresent(two, twoStep(b, f, g)));
assertTrue(map.containsKey(two));
assertTrue(b.get());
}
}
@Test
public void testConcurrentMap_compute_simple() {
final ConcurrentMap<Long,Long> map = new ImplementsConcurrentMap<>();
BiFunction<Long,Long,Long> fun = (k, v) -> ((v == null) ? 0L : k + v);
assertEquals(Long.valueOf(0L), map.compute(3L, fun));
assertEquals(Long.valueOf(3L), map.compute(3L, fun));
assertEquals(Long.valueOf(6L), map.compute(3L, fun));
assertNull(map.compute(3L, (k, v) -> null));
assertTrue(map.isEmpty());
assertEquals(Long.valueOf(0L), map.compute(new Long(3L), fun));
assertEquals(Long.valueOf(3L), map.compute(new Long(3L), fun));
assertEquals(Long.valueOf(6L), map.compute(new Long(3L), fun));
assertNull(map.compute(3L, (k, v) -> null));
assertTrue(map.isEmpty());
}
/**
* Simulates races by modifying the map within the remapping function.
*/
@Test
public void testConcurrentMap_compute_racy() {
final AtomicBoolean b = new AtomicBoolean(true);
final ConcurrentMap<Long,Long> map = new ImplementsConcurrentMap<>();
final Long two = 2L;
BiFunction<Long,Long,Long> f, g;
// null -> null is a no-op; race not detected
f = (k, v) -> { map.put(two, 42L); return null; };
assertNull(map.compute(two, f));
assertEquals(42L, (long)map.get(two));
for (Long val : new Long[] { null, 86L }) {
map.clear();
f = (k, v) -> { map.put(two, 42L); return 86L; };
g = (k, v) -> {
assertSame(two, k);
assertEquals(42L, (long)v);
return k + v;
};
assertEquals(44L, (long)map.compute(two, twoStep(b, f, g)));
assertEquals(44L, (long)map.get(two));
assertTrue(b.get());
f = (k, v) -> { map.remove(two); return val; };
g = (k, v) -> {
assertSame(two, k);
assertNull(v);
return 44L;
};
assertEquals(44L, (long)map.compute(two, twoStep(b, f, g)));
assertEquals(44L, (long)map.get(two));
assertTrue(map.containsKey(two));
assertTrue(b.get());
f = (k, v) -> { map.remove(two); return val; };
g = (k, v) -> {
assertSame(two, k);
assertNull(v);
return null;
};
assertNull(map.compute(two, twoStep(b, f, g)));
assertNull(map.get(two));
assertFalse(map.containsKey(two));
assertTrue(b.get());
}
}
/**
* Simulates races by modifying the map within the remapping function.
*/
@Test
public void testConcurrentMap_merge_racy() {
final AtomicBoolean b = new AtomicBoolean(true);
final ConcurrentMap<Long,Long> map = new ImplementsConcurrentMap<>();
final Long two = 2L;
BiFunction<Long,Long,Long> f, g;
for (Long val : new Long[] { null, 86L }) {
map.clear();
f = (v, w) -> { throw new AssertionError(); };
assertEquals(99L, (long)map.merge(two, 99L, f));
assertEquals(99L, (long)map.get(two));
f = (v, w) -> { map.put(two, 42L); return val; };
g = (v, w) -> {
assertEquals(42L, (long)v);
assertEquals(3L, (long)w);
return v + w;
};
assertEquals(45L, (long)map.merge(two, 3L, twoStep(b, f, g)));
assertEquals(45L, (long)map.get(two));
assertTrue(b.get());
f = (v, w) -> { map.remove(two); return val; };
g = (k, v) -> { throw new AssertionError(); };
assertEquals(55L, (long)map.merge(two, 55L, twoStep(b, f, g)));
assertEquals(55L, (long)map.get(two));
assertTrue(map.containsKey(two));
assertFalse(b.get()); b.set(true);
}
}
public enum IntegerEnum {
e0, e1, e2, e3, e4, e5, e6, e7, e8, e9,
@ -838,13 +1026,13 @@ public class Defaults {
protected ExtendsAbstractMap(M map) { this.map = map; }
public Set<Map.Entry<K,V>> entrySet() {
@Override public Set<Map.Entry<K,V>> entrySet() {
return new AbstractSet<Map.Entry<K,V>>() {
public int size() {
@Override public int size() {
return map.size();
}
public Iterator<Map.Entry<K,V>> iterator() {
@Override public Iterator<Map.Entry<K,V>> iterator() {
final Iterator<Map.Entry<K,V>> source = map.entrySet().iterator();
return new Iterator<Map.Entry<K,V>>() {
public boolean hasNext() { return source.hasNext(); }
@ -853,20 +1041,20 @@ public class Defaults {
};
}
public boolean add(Map.Entry<K,V> e) {
@Override public boolean add(Map.Entry<K,V> e) {
return map.entrySet().add(e);
}
};
}
public V put(K key, V value) {
@Override public V put(K key, V value) {
return map.put(key, value);
}
}
/**
* A simple mutable concurrent map implementation that provides only default
* implementations of all methods. ie. none of the ConcurrentMap interface
* implementations of all methods, i.e. none of the ConcurrentMap interface
* default methods have overridden implementations.
*
* @param <K> Type of keys
@ -875,14 +1063,26 @@ public class Defaults {
public static class ImplementsConcurrentMap<K,V> extends ExtendsAbstractMap<ConcurrentMap<K,V>, K, V> implements ConcurrentMap<K,V> {
public ImplementsConcurrentMap() { super(new ConcurrentHashMap<K,V>()); }
// ConcurrentMap reabstracts these methods
// ConcurrentMap reabstracts these methods.
//
// Unlike ConcurrentHashMap, we have zero tolerance for null values.
public V replace(K k, V v) { return map.replace(k, v); };
@Override public V replace(K k, V v) {
return map.replace(requireNonNull(k), requireNonNull(v));
}
public boolean replace(K k, V v, V vv) { return map.replace(k, v, vv); };
@Override public boolean replace(K k, V v, V vv) {
return map.replace(requireNonNull(k),
requireNonNull(v),
requireNonNull(vv));
}
public boolean remove(Object k, Object v) { return map.remove(k, v); }
@Override public boolean remove(Object k, Object v) {
return map.remove(requireNonNull(k), requireNonNull(v));
}
public V putIfAbsent(K k, V v) { return map.putIfAbsent(k, v); }
@Override public V putIfAbsent(K k, V v) {
return map.putIfAbsent(requireNonNull(k), requireNonNull(v));
}
}
}

View File

@ -0,0 +1,218 @@
/*
* Copyright 2016 Google, Inc. All Rights Reserved.
* 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 8148174
* @summary brittle white box test of internal array management
* @run testng ArrayManagement
*/
import java.lang.reflect.Field;
import java.util.AbstractList;
import java.util.Vector;
import java.util.Collections;
import java.util.List;
import java.util.SplittableRandom;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class ArrayManagement {
/**
* A Vector that exposes all protected elements, and checks class
* invariants.
*/
static class PublicVector<E> extends Vector<E> {
public PublicVector() { super(); }
public PublicVector(int capacity) { super(capacity); }
public PublicVector(int capacity, int capacityIncrement) {
super(capacity, capacityIncrement);
}
public Object[] elementData() { return elementData; }
public int modCount() { return modCount; }
public int capacityIncrement() { return capacityIncrement; }
public int capacity() { return elementData.length; }
public void ensureCapacity(int minCapacity) {
int oldCapacity = capacity();
int oldModCount = modCount();
super.ensureCapacity(minCapacity);
assertTrue(capacity() >= minCapacity);
if (minCapacity <= oldCapacity)
assertEquals(capacity(), oldCapacity);
if (minCapacity > 0)
assertEquals(modCount(), oldModCount + 1);
}
}
static final int DEFAULT_CAPACITY = 10;
static final SplittableRandom rnd = new SplittableRandom();
static int newCapacity(int oldCapacity) {
return 2 * oldCapacity;
}
static List<Object> singletonList() {
return Collections.singletonList(Boolean.TRUE);
}
/** Opportunistically randomly test various add operations. */
static void addOneElement(PublicVector<Object> list) {
int size = list.size();
int modCount = list.modCount();
switch (rnd.nextInt(4)) {
case 0: assertTrue(list.add(Boolean.TRUE)); break;
case 1: list.add(size, Boolean.TRUE); break;
case 2: assertTrue(list.addAll(singletonList())); break;
case 3: assertTrue(list.addAll(size, singletonList())); break;
default: throw new AssertionError();
}
assertEquals(list.modCount(), modCount + 1);
assertEquals(list.size(), size + 1);
}
@Test public void defaultCapacity() {
PublicVector<Object> list = new PublicVector<>();
assertEquals(new PublicVector<Object>().capacity(), DEFAULT_CAPACITY);
for (int i = 0; i < DEFAULT_CAPACITY; i++) {
addOneElement(list);
assertEquals(list.capacity(), DEFAULT_CAPACITY);
}
addOneElement(list);
assertEquals(list.capacity(), newCapacity(DEFAULT_CAPACITY));
}
@Test public void defaultCapacityEnsureCapacity() {
PublicVector<Object> list = new PublicVector<>();
for (int i = 0; i <= DEFAULT_CAPACITY; i++) {
list.ensureCapacity(i); // no-op!
assertEquals(list.capacity(), DEFAULT_CAPACITY);
}
for (int i = 0; i < DEFAULT_CAPACITY; i++) {
addOneElement(list);
assertEquals(list.capacity(), DEFAULT_CAPACITY);
}
addOneElement(list);
assertEquals(list.capacity(), newCapacity(DEFAULT_CAPACITY));
{
int capacity = list.capacity();
list.ensureCapacity(capacity + 1);
assertEquals(list.capacity(), newCapacity(capacity));
}
{
int capacity = list.capacity();
list.ensureCapacity(3 * capacity);
assertEquals(list.capacity(), 3 * capacity);
}
}
@Test public void ensureCapacityBeyondDefaultCapacity() {
PublicVector<Object> list = new PublicVector<>();
list.ensureCapacity(DEFAULT_CAPACITY + 1);
assertEquals(list.capacity(), newCapacity(DEFAULT_CAPACITY));
}
@Test public void explicitZeroCapacity() {
PublicVector<Object> list = new PublicVector<>(0);
assertEquals(list.capacity(), 0);
addOneElement(list);
assertEquals(list.capacity(), 1);
addOneElement(list);
assertEquals(list.capacity(), 2);
addOneElement(list);
assertEquals(list.capacity(), 4);
addOneElement(list);
assertEquals(list.capacity(), 4);
addOneElement(list);
assertEquals(list.capacity(), 8);
addOneElement(list);
assertEquals(list.capacity(), 8);
addOneElement(list);
assertEquals(list.capacity(), 8);
list.clear();
assertEquals(list.capacity(), 8);
}
@Test public void explicitZeroCapacityWithCapacityIncrement() {
PublicVector<Object> list = new PublicVector<>(0, 2);
assertEquals(list.capacity(), 0);
addOneElement(list);
assertEquals(list.capacity(), 2);
addOneElement(list);
assertEquals(list.capacity(), 2);
addOneElement(list);
assertEquals(list.capacity(), 4);
addOneElement(list);
assertEquals(list.capacity(), 4);
addOneElement(list);
assertEquals(list.capacity(), 6);
addOneElement(list);
assertEquals(list.capacity(), 6);
addOneElement(list);
assertEquals(list.capacity(), 8);
list.clear();
assertEquals(list.capacity(), 8);
}
@Test public void explicitLargeCapacity() {
int n = DEFAULT_CAPACITY * 3;
PublicVector<Object> list = new PublicVector<>(n);
assertEquals(list.capacity(), n);
list.ensureCapacity(0);
list.ensureCapacity(n);
for (int i = 0; i < n; i++) addOneElement(list);
assertEquals(list.capacity(), n);
addOneElement(list);
assertEquals(list.capacity(), newCapacity(n));
}
@Test public void explicitLargeCapacityWithCapacityIncrement() {
int n = DEFAULT_CAPACITY * 3;
PublicVector<Object> list = new PublicVector<>(n, 2);
assertEquals(list.capacity(), n);
list.ensureCapacity(0);
list.ensureCapacity(n);
for (int i = 0; i < n; i++) addOneElement(list);
assertEquals(list.capacity(), n);
addOneElement(list);
assertEquals(list.capacity(), n + 2);
}
@Test public void emptyArraysAreNotShared() {
assertNotSame(new PublicVector<Object>(0).elementData(),
new PublicVector<Object>(0).elementData());
}
@Test public void negativeCapacity() {
for (int capacity : new int[] { -1, Integer.MIN_VALUE }) {
try {
new Vector<Object>(capacity);
fail("should throw");
} catch (IllegalArgumentException success) {}
}
}
}

View File

@ -0,0 +1,43 @@
/*
* Copyright 2016 Google, Inc. All Rights Reserved.
* 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 8148174
* @summary repro for: NegativeArraySizeException in Vector.grow(int)
* @run main/othervm -Xmx17g Bug8148174
* @ignore This test has huge memory requirements
*/
public class Bug8148174 {
public static void main(String[] args) {
int size = Integer.MAX_VALUE - 2;
java.util.Vector<Object> huge = new java.util.Vector<>(size);
for (int i = 0; i < size; i++)
huge.add(null);
try {
huge.addAll(huge);
throw new Error("expected OutOfMemoryError not thrown");
} catch (OutOfMemoryError success) {}
}
}

View File

@ -36,17 +36,17 @@
* @author Doug Lea
* @bug 8004138
* @summary Check if ForkJoinPool table leaks thrown exceptions.
* @run main/othervm -Xmx2200k FJExceptionTableLeak
* @key intermittent
* @run main/othervm -Xmx8m -Djava.util.concurrent.ForkJoinPool.common.parallelism=4 FJExceptionTableLeak
*/
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class FJExceptionTableLeak {
// This test was observed to fail with jdk7 -Xmx2200k,
// This test was observed to fail with pre-bug-fix jdk7 -Xmx8m,
// using STEPS = 220 and TASKS_PER_STEP = 100
static final int STEPS = 500;
static final int PRE_BUG_FIX_FAILURE_STEPS = 220;
static final int STEPS = 10 * PRE_BUG_FIX_FAILURE_STEPS;
static final int TASKS_PER_STEP = 100;
static class FailingTaskException extends RuntimeException {}

View File

@ -0,0 +1,635 @@
/*
* 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.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import junit.framework.Test;
import junit.framework.TestSuite;
public class AbstractExecutorServiceTest extends JSR166TestCase {
public static void main(String[] args) {
main(suite(), args);
}
public static Test suite() {
return new TestSuite(AbstractExecutorServiceTest.class);
}
/**
* A no-frills implementation of AbstractExecutorService, designed
* to test the submit methods only.
*/
static class DirectExecutorService extends AbstractExecutorService {
public void execute(Runnable r) { r.run(); }
public void shutdown() { shutdown = true; }
public List<Runnable> shutdownNow() {
shutdown = true;
return Collections.EMPTY_LIST;
}
public boolean isShutdown() { return shutdown; }
public boolean isTerminated() { return isShutdown(); }
public boolean awaitTermination(long timeout, TimeUnit unit) {
return isShutdown();
}
private volatile boolean shutdown = false;
}
/**
* execute(runnable) runs it to completion
*/
public void testExecuteRunnable() throws Exception {
ExecutorService e = new DirectExecutorService();
final AtomicBoolean done = new AtomicBoolean(false);
Future<?> future = e.submit(new CheckedRunnable() {
public void realRun() {
done.set(true);
}});
assertNull(future.get());
assertNull(future.get(0, MILLISECONDS));
assertTrue(done.get());
assertTrue(future.isDone());
assertFalse(future.isCancelled());
}
/**
* Completed submit(callable) returns result
*/
public void testSubmitCallable() throws Exception {
ExecutorService e = new DirectExecutorService();
Future<String> future = e.submit(new StringTask());
String result = future.get();
assertSame(TEST_STRING, result);
}
/**
* Completed submit(runnable) returns successfully
*/
public void testSubmitRunnable() throws Exception {
ExecutorService e = new DirectExecutorService();
Future<?> future = e.submit(new NoOpRunnable());
future.get();
assertTrue(future.isDone());
}
/**
* Completed submit(runnable, result) returns result
*/
public void testSubmitRunnable2() throws Exception {
ExecutorService e = new DirectExecutorService();
Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
String result = future.get();
assertSame(TEST_STRING, result);
}
/**
* A submitted privileged action runs to completion
*/
public void testSubmitPrivilegedAction() throws Exception {
Runnable r = new CheckedRunnable() {
public void realRun() throws Exception {
ExecutorService e = new DirectExecutorService();
Future future = e.submit(Executors.callable(new PrivilegedAction() {
public Object run() {
return TEST_STRING;
}}));
assertSame(TEST_STRING, future.get());
}};
runWithPermissions(r,
new RuntimePermission("getClassLoader"),
new RuntimePermission("setContextClassLoader"),
new RuntimePermission("modifyThread"));
}
/**
* A submitted privileged exception action runs to completion
*/
public void testSubmitPrivilegedExceptionAction() throws Exception {
Runnable r = new CheckedRunnable() {
public void realRun() throws Exception {
ExecutorService e = new DirectExecutorService();
Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
public Object run() {
return TEST_STRING;
}}));
assertSame(TEST_STRING, future.get());
}};
runWithPermissions(r);
}
/**
* A submitted failed privileged exception action reports exception
*/
public void testSubmitFailedPrivilegedExceptionAction() throws Exception {
Runnable r = new CheckedRunnable() {
public void realRun() throws Exception {
ExecutorService e = new DirectExecutorService();
Future future = e.submit(Executors.callable(new PrivilegedExceptionAction() {
public Object run() throws Exception {
throw new IndexOutOfBoundsException();
}}));
try {
future.get();
shouldThrow();
} catch (ExecutionException success) {
assertTrue(success.getCause() instanceof IndexOutOfBoundsException);
}}};
runWithPermissions(r);
}
/**
* execute(null runnable) throws NPE
*/
public void testExecuteNullRunnable() {
ExecutorService e = new DirectExecutorService();
try {
e.submit((Runnable) null);
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* submit(null callable) throws NPE
*/
public void testSubmitNullCallable() {
ExecutorService e = new DirectExecutorService();
try {
e.submit((Callable) null);
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* submit(callable).get() throws InterruptedException if interrupted
*/
public void testInterruptedSubmit() throws InterruptedException {
final CountDownLatch submitted = new CountDownLatch(1);
final CountDownLatch quittingTime = new CountDownLatch(1);
final Callable<Void> awaiter = new CheckedCallable<Void>() {
public Void realCall() throws InterruptedException {
assertTrue(quittingTime.await(2*LONG_DELAY_MS, MILLISECONDS));
return null;
}};
final ExecutorService p
= new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(p, quittingTime)) {
Thread t = newStartedThread(new CheckedInterruptedRunnable() {
public void realRun() throws Exception {
Future<Void> future = p.submit(awaiter);
submitted.countDown();
future.get();
}});
await(submitted);
t.interrupt();
awaitTermination(t);
}
}
/**
* get of submit(callable) throws ExecutionException if callable
* throws exception
*/
public void testSubmitEE() throws InterruptedException {
final ThreadPoolExecutor p =
new ThreadPoolExecutor(1, 1,
60, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10));
try (PoolCleaner cleaner = cleaner(p)) {
Callable c = new Callable() {
public Object call() { throw new ArithmeticException(); }};
try {
p.submit(c).get();
shouldThrow();
} catch (ExecutionException success) {
assertTrue(success.getCause() instanceof ArithmeticException);
}
}
}
/**
* invokeAny(null) throws NPE
*/
public void testInvokeAny1() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
try {
e.invokeAny(null);
shouldThrow();
} catch (NullPointerException success) {}
}
}
/**
* invokeAny(empty collection) throws IAE
*/
public void testInvokeAny2() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
try {
e.invokeAny(new ArrayList<Callable<String>>());
shouldThrow();
} catch (IllegalArgumentException success) {}
}
}
/**
* invokeAny(c) throws NPE if c has null elements
*/
public void testInvokeAny3() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<Long>> l = new ArrayList<Callable<Long>>();
l.add(new Callable<Long>() {
public Long call() { throw new ArithmeticException(); }});
l.add(null);
try {
e.invokeAny(l);
shouldThrow();
} catch (NullPointerException success) {}
}
}
/**
* invokeAny(c) throws ExecutionException if no task in c completes
*/
public void testInvokeAny4() throws InterruptedException {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<Callable<String>>();
l.add(new NPETask());
try {
e.invokeAny(l);
shouldThrow();
} catch (ExecutionException success) {
assertTrue(success.getCause() instanceof NullPointerException);
}
}
}
/**
* invokeAny(c) returns result of some task in c if at least one completes
*/
public void testInvokeAny5() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<Callable<String>>();
l.add(new StringTask());
l.add(new StringTask());
String result = e.invokeAny(l);
assertSame(TEST_STRING, result);
}
}
/**
* invokeAll(null) throws NPE
*/
public void testInvokeAll1() throws InterruptedException {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
try {
e.invokeAll(null);
shouldThrow();
} catch (NullPointerException success) {}
}
}
/**
* invokeAll(empty collection) returns empty collection
*/
public void testInvokeAll2() throws InterruptedException {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
assertTrue(r.isEmpty());
}
}
/**
* invokeAll(c) throws NPE if c has null elements
*/
public void testInvokeAll3() throws InterruptedException {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<Callable<String>>();
l.add(new StringTask());
l.add(null);
try {
e.invokeAll(l);
shouldThrow();
} catch (NullPointerException success) {}
}
}
/**
* get of returned element of invokeAll(c) throws exception on failed task
*/
public void testInvokeAll4() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<Callable<String>>();
l.add(new NPETask());
List<Future<String>> futures = e.invokeAll(l);
assertEquals(1, futures.size());
try {
futures.get(0).get();
shouldThrow();
} catch (ExecutionException success) {
assertTrue(success.getCause() instanceof NullPointerException);
}
}
}
/**
* invokeAll(c) returns results of all completed tasks in c
*/
public void testInvokeAll5() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<Callable<String>>();
l.add(new StringTask());
l.add(new StringTask());
List<Future<String>> futures = e.invokeAll(l);
assertEquals(2, futures.size());
for (Future<String> future : futures)
assertSame(TEST_STRING, future.get());
}
}
/**
* timed invokeAny(null) throws NPE
*/
public void testTimedInvokeAny1() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
try {
e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
shouldThrow();
} catch (NullPointerException success) {}
}
}
/**
* timed invokeAny(null time unit) throws NPE
*/
public void testTimedInvokeAnyNullTimeUnit() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<Callable<String>>();
l.add(new StringTask());
try {
e.invokeAny(l, MEDIUM_DELAY_MS, null);
shouldThrow();
} catch (NullPointerException success) {}
}
}
/**
* timed invokeAny(empty collection) throws IAE
*/
public void testTimedInvokeAny2() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
try {
e.invokeAny(new ArrayList<Callable<String>>(),
MEDIUM_DELAY_MS, MILLISECONDS);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
}
/**
* timed invokeAny(c) throws NPE if c has null elements
*/
public void testTimedInvokeAny3() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<Long>> l = new ArrayList<Callable<Long>>();
l.add(new Callable<Long>() {
public Long call() { throw new ArithmeticException(); }});
l.add(null);
try {
e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
shouldThrow();
} catch (NullPointerException success) {}
}
}
/**
* timed invokeAny(c) throws ExecutionException if no task completes
*/
public void testTimedInvokeAny4() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
long startTime = System.nanoTime();
List<Callable<String>> l = new ArrayList<Callable<String>>();
l.add(new NPETask());
try {
e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
shouldThrow();
} catch (ExecutionException success) {
assertTrue(success.getCause() instanceof NullPointerException);
}
assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
}
}
/**
* timed invokeAny(c) returns result of some task in c
*/
public void testTimedInvokeAny5() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
long startTime = System.nanoTime();
List<Callable<String>> l = new ArrayList<Callable<String>>();
l.add(new StringTask());
l.add(new StringTask());
String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
assertSame(TEST_STRING, result);
assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
}
}
/**
* timed invokeAll(null) throws NPE
*/
public void testTimedInvokeAll1() throws InterruptedException {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
try {
e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
shouldThrow();
} catch (NullPointerException success) {}
}
}
/**
* timed invokeAll(null time unit) throws NPE
*/
public void testTimedInvokeAllNullTimeUnit() throws InterruptedException {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<Callable<String>>();
l.add(new StringTask());
try {
e.invokeAll(l, MEDIUM_DELAY_MS, null);
shouldThrow();
} catch (NullPointerException success) {}
}
}
/**
* timed invokeAll(empty collection) returns empty collection
*/
public void testTimedInvokeAll2() throws InterruptedException {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
assertTrue(r.isEmpty());
}
}
/**
* timed invokeAll(c) throws NPE if c has null elements
*/
public void testTimedInvokeAll3() throws InterruptedException {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<Callable<String>>();
l.add(new StringTask());
l.add(null);
try {
e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
shouldThrow();
} catch (NullPointerException success) {}
}
}
/**
* get of returned element of invokeAll(c) throws exception on failed task
*/
public void testTimedInvokeAll4() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<Callable<String>>();
l.add(new NPETask());
List<Future<String>> futures =
e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
assertEquals(1, futures.size());
try {
futures.get(0).get();
shouldThrow();
} catch (ExecutionException success) {
assertTrue(success.getCause() instanceof NullPointerException);
}
}
}
/**
* timed invokeAll(c) returns results of all completed tasks in c
*/
public void testTimedInvokeAll5() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
List<Callable<String>> l = new ArrayList<Callable<String>>();
l.add(new StringTask());
l.add(new StringTask());
List<Future<String>> futures =
e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
assertEquals(2, futures.size());
for (Future<String> future : futures)
assertSame(TEST_STRING, future.get());
}
}
/**
* timed invokeAll cancels tasks not completed by timeout
*/
public void testTimedInvokeAll6() throws Exception {
final ExecutorService e = new DirectExecutorService();
try (PoolCleaner cleaner = cleaner(e)) {
for (long timeout = timeoutMillis();;) {
List<Callable<String>> tasks = new ArrayList<>();
tasks.add(new StringTask("0"));
tasks.add(Executors.callable(possiblyInterruptedRunnable(timeout),
TEST_STRING));
tasks.add(new StringTask("2"));
long startTime = System.nanoTime();
List<Future<String>> futures =
e.invokeAll(tasks, timeout, MILLISECONDS);
assertEquals(tasks.size(), futures.size());
assertTrue(millisElapsedSince(startTime) >= timeout);
for (Future future : futures)
assertTrue(future.isDone());
try {
assertEquals("0", futures.get(0).get());
assertEquals(TEST_STRING, futures.get(1).get());
} catch (CancellationException retryWithLongerTimeout) {
// unusual delay before starting second task
timeout *= 2;
if (timeout >= LONG_DELAY_MS / 2)
fail("expected exactly one task to be cancelled");
continue;
}
assertTrue(futures.get(2).isCancelled());
break;
}
}
}
}

View File

@ -0,0 +1,205 @@
/*
* 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.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
import java.util.AbstractQueue;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import junit.framework.Test;
import junit.framework.TestSuite;
public class AbstractQueueTest extends JSR166TestCase {
public static void main(String[] args) {
main(suite(), args);
}
public static Test suite() {
return new TestSuite(AbstractQueueTest.class);
}
static class Succeed extends AbstractQueue<Integer> {
public boolean offer(Integer x) {
if (x == null) throw new NullPointerException();
return true;
}
public Integer peek() { return one; }
public Integer poll() { return one; }
public int size() { return 0; }
public Iterator iterator() { return null; } // not needed
}
static class Fail extends AbstractQueue<Integer> {
public boolean offer(Integer x) {
if (x == null) throw new NullPointerException();
return false;
}
public Integer peek() { return null; }
public Integer poll() { return null; }
public int size() { return 0; }
public Iterator iterator() { return null; } // not needed
}
/**
* add returns true if offer succeeds
*/
public void testAddS() {
Succeed q = new Succeed();
assertTrue(q.add(two));
}
/**
* add throws ISE true if offer fails
*/
public void testAddF() {
Fail q = new Fail();
try {
q.add(one);
shouldThrow();
} catch (IllegalStateException success) {}
}
/**
* add throws NPE if offer does
*/
public void testAddNPE() {
Succeed q = new Succeed();
try {
q.add(null);
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* remove returns normally if poll succeeds
*/
public void testRemoveS() {
Succeed q = new Succeed();
q.remove();
}
/**
* remove throws NSEE if poll returns null
*/
public void testRemoveF() {
Fail q = new Fail();
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success) {}
}
/**
* element returns normally if peek succeeds
*/
public void testElementS() {
Succeed q = new Succeed();
q.element();
}
/**
* element throws NSEE if peek returns null
*/
public void testElementF() {
Fail q = new Fail();
try {
q.element();
shouldThrow();
} catch (NoSuchElementException success) {}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
Succeed q = new Succeed();
try {
q.addAll(null);
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* addAll(this) throws IAE
*/
public void testAddAllSelf() {
Succeed q = new Succeed();
try {
q.addAll(q);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
Succeed q = new Succeed();
Integer[] ints = new Integer[SIZE];
try {
q.addAll(Arrays.asList(ints));
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
Succeed q = new Succeed();
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE - 1; ++i)
ints[i] = new Integer(i);
try {
q.addAll(Arrays.asList(ints));
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* addAll throws ISE if an add fails
*/
public void testAddAll4() {
Fail q = new Fail();
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
try {
q.addAll(Arrays.asList(ints));
shouldThrow();
} catch (IllegalStateException success) {}
}
}

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