提交 9d2d3c79 编写于 作者: L lana

Merge

...@@ -60,5 +60,10 @@ ifeq ($(PLATFORM), linux) ...@@ -60,5 +60,10 @@ ifeq ($(PLATFORM), linux)
endif endif
endif endif
# NIO Platform specific source file location
ifdef CROSS_COMPILE_ARCH
NIO_PLATFORM_CLASSES_ROOT_DIR = $(CLOSED_PLATFORM_SRC)/classes/
endif
endif # JAVASE_EMBEDDED endif # JAVASE_EMBEDDED
...@@ -195,8 +195,8 @@ ifndef JDK_MAJOR_VERSION ...@@ -195,8 +195,8 @@ ifndef JDK_MAJOR_VERSION
endif endif
ifndef JDK_MINOR_VERSION ifndef JDK_MINOR_VERSION
JDK_MINOR_VERSION = 7 JDK_MINOR_VERSION = 8
PREVIOUS_MINOR_VERSION = 6 PREVIOUS_MINOR_VERSION = 7
endif endif
ifndef JDK_MICRO_VERSION ifndef JDK_MICRO_VERSION
......
...@@ -223,6 +223,9 @@ endif ...@@ -223,6 +223,9 @@ endif
ifeq ($(JDK_MINOR_VERSION),6) ifeq ($(JDK_MINOR_VERSION),6)
JDK_IS_FCS = true JDK_IS_FCS = true
endif endif
ifeq ($(JDK_MINOR_VERSION),7)
JDK_IS_FCS = true
endif
ifeq ($(JDK_IS_FCS),false) ifeq ($(JDK_IS_FCS),false)
ifneq ($(MILESTONE), fcs) ifneq ($(MILESTONE), fcs)
DRAFT_HEADER = <br><strong>DRAFT&nbsp;$(MILESTONE)-$(BUILD_NUMBER)</strong> DRAFT_HEADER = <br><strong>DRAFT&nbsp;$(MILESTONE)-$(BUILD_NUMBER)</strong>
......
...@@ -255,7 +255,7 @@ FILES_export += \ ...@@ -255,7 +255,7 @@ FILES_export += \
sun/nio/fs/LinuxWatchService.java \ sun/nio/fs/LinuxWatchService.java \
sun/nio/fs/UnixCopyFile.java \ sun/nio/fs/UnixCopyFile.java \
sun/nio/fs/UnixNativeDispatcher.java sun/nio/fs/UnixNativeDispatcher.java
FILES_gen += \ FILES_gen += \
sun/nio/fs/UnixConstants.java sun/nio/fs/UnixConstants.java
endif # PLATFORM = linux endif # PLATFORM = linux
...@@ -771,7 +771,7 @@ $(CS_GEN)/CharsetEncoder.java: $(CHARSET_X_CODER_TEMPLATE) $(GEN_CODER_SH) ...@@ -771,7 +771,7 @@ $(CS_GEN)/CharsetEncoder.java: $(CHARSET_X_CODER_TEMPLATE) $(GEN_CODER_SH)
# #
GEN_EX_SH = genExceptions.sh GEN_EX_SH = genExceptions.sh
GEN_EX_CMD = NAWK="$(NAWK)" SH="$(SH)" $(SH) $(GEN_EX_SH) GEN_EX_CMD = NAWK="$(NAWK)" SH="$(SH)" $(SH) $(GEN_EX_SH)
$(CH_GEN)/%Exception.java: genExceptions.sh $(CH_SRC)/exceptions $(CH_GEN)/%Exception.java: genExceptions.sh $(CH_SRC)/exceptions
...@@ -820,14 +820,19 @@ $(TEMPDIR)/$(GENSOR_SRC) : $(GENSOR_SRC) ...@@ -820,14 +820,19 @@ $(TEMPDIR)/$(GENSOR_SRC) : $(GENSOR_SRC)
$(GENSOR_EXE) : $(TEMPDIR)/$(GENSOR_SRC) $(GENSOR_EXE) : $(TEMPDIR)/$(GENSOR_SRC)
$(prep-target) $(prep-target)
($(CD) $(TEMPDIR); $(HOST_CC) $(CPPFLAGS) $(LDDFLAGS) \ ($(CD) $(TEMPDIR); $(CC) $(CPPFLAGS) $(LDDFLAGS) \
-o genSocketOptionRegistry$(EXE_SUFFIX) $(GENSOR_SRC)) -o genSocketOptionRegistry$(EXE_SUFFIX) $(GENSOR_SRC))
ifdef NIO_PLATFORM_CLASSES_ROOT_DIR
$(SCH_GEN)/SocketOptionRegistry.java: $(NIO_PLATFORM_CLASSES_ROOT_DIR)/sun/nio/ch/SocketOptionRegistry-$(PLATFORM)-$(ARCH).java
$(prep-target)
$(CP) $< $@
else
$(SCH_GEN)/SocketOptionRegistry.java: $(GENSOR_EXE) $(SCH_GEN)/SocketOptionRegistry.java: $(GENSOR_EXE)
$(prep-target) $(prep-target)
NAWK="$(NAWK)" SH="$(SH)" $(SH) -e addNotices.sh "$(SOR_COPYRIGHT_YEARS)" > $@ NAWK="$(NAWK)" SH="$(SH)" $(SH) -e addNotices.sh "$(SOR_COPYRIGHT_YEARS)" > $@
$(GENSOR_EXE) >> $@ $(GENSOR_EXE) >> $@
endif
# #
# Generated sun.nio.cs SingleByte classes # Generated sun.nio.cs SingleByte classes
# #
...@@ -851,12 +856,18 @@ GENUC_COPYRIGHT_YEARS = $(shell $(CAT) $(GENUC_SRC) | \ ...@@ -851,12 +856,18 @@ GENUC_COPYRIGHT_YEARS = $(shell $(CAT) $(GENUC_SRC) | \
$(GENUC_EXE) : $(GENUC_SRC) $(GENUC_EXE) : $(GENUC_SRC)
$(prep-target) $(prep-target)
$(HOST_CC) $(CPPFLAGS) -o $@ $(GENUC_SRC) $(CC) $(CPPFLAGS) -o $@ $(GENUC_SRC)
ifdef NIO_PLATFORM_CLASSES_ROOT_DIR
$(SFS_GEN)/UnixConstants.java: $(NIO_PLATFORM_CLASSES_ROOT_DIR)/sun/nio/fs/UnixConstants-$(PLATFORM)-$(ARCH).java
$(prep-target)
$(CP) $< $@
else
$(SFS_GEN)/UnixConstants.java: $(GENUC_EXE) $(SFS_GEN)/UnixConstants.java: $(GENUC_EXE)
$(prep-target) $(prep-target)
NAWK="$(NAWK)" SH="$(SH)" $(SH) -e addNotices.sh "$(GENUC_COPYRIGHT_YEARS)" > $@ NAWK="$(NAWK)" SH="$(SH)" $(SH) -e addNotices.sh "$(GENUC_COPYRIGHT_YEARS)" > $@
$(GENUC_EXE) >> $@ $(GENUC_EXE) >> $@
endif
GENSC_SRC = $(PLATFORM_SRC)/native/sun/nio/fs/genSolarisConstants.c GENSC_SRC = $(PLATFORM_SRC)/native/sun/nio/fs/genSolarisConstants.c
...@@ -867,11 +878,17 @@ GENSC_COPYRIGHT_YEARS = $(shell $(CAT) $(GENSC_SRC) | \ ...@@ -867,11 +878,17 @@ GENSC_COPYRIGHT_YEARS = $(shell $(CAT) $(GENSC_SRC) | \
$(GENSC_EXE) : $(GENSC_SRC) $(GENSC_EXE) : $(GENSC_SRC)
$(prep-target) $(prep-target)
$(HOST_CC) $(CPPFLAGS) -o $@ $(GENSC_SRC) $(CC) $(CPPFLAGS) -o $@ $(GENSC_SRC)
ifdef NIO_PLATFORM_CLASSES_ROOT_DIR
$(SFS_GEN)/SolarisConstants.java: $(NIO_PLATFORM_CLASSES_ROOT_DIR)/sun/nio/fs/SolarisConstants-$(PLATFORM)-$(ARCH).java
$(prep-target)
$(CP) $< $@
else
$(SFS_GEN)/SolarisConstants.java: $(GENSC_EXE) $(SFS_GEN)/SolarisConstants.java: $(GENSC_EXE)
$(prep-target) $(prep-target)
NAWK="$(NAWK)" SH="$(SH)" $(SH) -e addNotices.sh "$(GENSC_COPYRIGHT_YEARS)" > $@ NAWK="$(NAWK)" SH="$(SH)" $(SH) -e addNotices.sh "$(GENSC_COPYRIGHT_YEARS)" > $@
$(GENSC_EXE) >> $@ $(GENSC_EXE) >> $@
endif
.PHONY: sources .PHONY: sources
/* /*
* Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -324,40 +324,45 @@ public final class Byte extends Number implements Comparable<Byte> { ...@@ -324,40 +324,45 @@ public final class Byte extends Number implements Comparable<Byte> {
} }
/** /**
* Returns the value of this {@code Byte} as a * Returns the value of this {@code Byte} as a {@code short} after
* {@code short}. * a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public short shortValue() { public short shortValue() {
return (short)value; return (short)value;
} }
/** /**
* Returns the value of this {@code Byte} as an * Returns the value of this {@code Byte} as an {@code int} after
* {@code int}. * a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public int intValue() { public int intValue() {
return (int)value; return (int)value;
} }
/** /**
* Returns the value of this {@code Byte} as a * Returns the value of this {@code Byte} as a {@code long} after
* {@code long}. * a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public long longValue() { public long longValue() {
return (long)value; return (long)value;
} }
/** /**
* Returns the value of this {@code Byte} as a * Returns the value of this {@code Byte} as a {@code float} after
* {@code float}. * a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public float floatValue() { public float floatValue() {
return (float)value; return (float)value;
} }
/** /**
* Returns the value of this {@code Byte} as a * Returns the value of this {@code Byte} as a {@code double}
* {@code double}. * after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public double doubleValue() { public double doubleValue() {
return (double)value; return (double)value;
......
/* /*
* Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -634,11 +634,12 @@ public final class Double extends Number implements Comparable<Double> { ...@@ -634,11 +634,12 @@ public final class Double extends Number implements Comparable<Double> {
} }
/** /**
* Returns the value of this {@code Double} as a {@code byte} (by * Returns the value of this {@code Double} as a {@code byte}
* casting to a {@code byte}). * after a narrowing primitive conversion.
* *
* @return the {@code double} value represented by this object * @return the {@code double} value represented by this object
* converted to type {@code byte} * converted to type {@code byte}
* @jls 5.1.3 Narrowing Primitive Conversions
* @since JDK1.1 * @since JDK1.1
*/ */
public byte byteValue() { public byte byteValue() {
...@@ -646,11 +647,12 @@ public final class Double extends Number implements Comparable<Double> { ...@@ -646,11 +647,12 @@ public final class Double extends Number implements Comparable<Double> {
} }
/** /**
* Returns the value of this {@code Double} as a * Returns the value of this {@code Double} as a {@code short}
* {@code short} (by casting to a {@code short}). * after a narrowing primitive conversion.
* *
* @return the {@code double} value represented by this object * @return the {@code double} value represented by this object
* converted to type {@code short} * converted to type {@code short}
* @jls 5.1.3 Narrowing Primitive Conversions
* @since JDK1.1 * @since JDK1.1
*/ */
public short shortValue() { public short shortValue() {
...@@ -658,8 +660,9 @@ public final class Double extends Number implements Comparable<Double> { ...@@ -658,8 +660,9 @@ public final class Double extends Number implements Comparable<Double> {
} }
/** /**
* Returns the value of this {@code Double} as an * Returns the value of this {@code Double} as an {@code int}
* {@code int} (by casting to type {@code int}). * after a narrowing primitive conversion.
* @jls 5.1.3 Narrowing Primitive Conversions
* *
* @return the {@code double} value represented by this object * @return the {@code double} value represented by this object
* converted to type {@code int} * converted to type {@code int}
...@@ -669,22 +672,24 @@ public final class Double extends Number implements Comparable<Double> { ...@@ -669,22 +672,24 @@ public final class Double extends Number implements Comparable<Double> {
} }
/** /**
* Returns the value of this {@code Double} as a * Returns the value of this {@code Double} as a {@code long}
* {@code long} (by casting to type {@code long}). * after a narrowing primitive conversion.
* *
* @return the {@code double} value represented by this object * @return the {@code double} value represented by this object
* converted to type {@code long} * converted to type {@code long}
* @jls 5.1.3 Narrowing Primitive Conversions
*/ */
public long longValue() { public long longValue() {
return (long)value; return (long)value;
} }
/** /**
* Returns the {@code float} value of this * Returns the value of this {@code Double} as a {@code float}
* {@code Double} object. * after a narrowing primitive conversion.
* *
* @return the {@code double} value represented by this object * @return the {@code double} value represented by this object
* converted to type {@code float} * converted to type {@code float}
* @jls 5.1.3 Narrowing Primitive Conversions
* @since JDK1.0 * @since JDK1.0
*/ */
public float floatValue() { public float floatValue() {
...@@ -692,8 +697,7 @@ public final class Double extends Number implements Comparable<Double> { ...@@ -692,8 +697,7 @@ public final class Double extends Number implements Comparable<Double> {
} }
/** /**
* Returns the {@code double} value of this * Returns the {@code double} value of this {@code Double} object.
* {@code Double} object.
* *
* @return the {@code double} value represented by this object * @return the {@code double} value represented by this object
*/ */
......
/* /*
* Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -556,22 +556,24 @@ public final class Float extends Number implements Comparable<Float> { ...@@ -556,22 +556,24 @@ public final class Float extends Number implements Comparable<Float> {
} }
/** /**
* Returns the value of this {@code Float} as a {@code byte} (by * Returns the value of this {@code Float} as a {@code byte} after
* casting to a {@code byte}). * a narrowing primitive conversion.
* *
* @return the {@code float} value represented by this object * @return the {@code float} value represented by this object
* converted to type {@code byte} * converted to type {@code byte}
* @jls 5.1.3 Narrowing Primitive Conversions
*/ */
public byte byteValue() { public byte byteValue() {
return (byte)value; return (byte)value;
} }
/** /**
* Returns the value of this {@code Float} as a {@code short} (by * Returns the value of this {@code Float} as a {@code short}
* casting to a {@code short}). * after a narrowing primitive conversion.
* *
* @return the {@code float} value represented by this object * @return the {@code float} value represented by this object
* converted to type {@code short} * converted to type {@code short}
* @jls 5.1.3 Narrowing Primitive Conversions
* @since JDK1.1 * @since JDK1.1
*/ */
public short shortValue() { public short shortValue() {
...@@ -579,22 +581,24 @@ public final class Float extends Number implements Comparable<Float> { ...@@ -579,22 +581,24 @@ public final class Float extends Number implements Comparable<Float> {
} }
/** /**
* Returns the value of this {@code Float} as an {@code int} (by * Returns the value of this {@code Float} as an {@code int} after
* casting to type {@code int}). * a narrowing primitive conversion.
* *
* @return the {@code float} value represented by this object * @return the {@code float} value represented by this object
* converted to type {@code int} * converted to type {@code int}
* @jls 5.1.3 Narrowing Primitive Conversions
*/ */
public int intValue() { public int intValue() {
return (int)value; return (int)value;
} }
/** /**
* Returns value of this {@code Float} as a {@code long} (by * Returns value of this {@code Float} as a {@code long} after a
* casting to type {@code long}). * narrowing primitive conversion.
* *
* @return the {@code float} value represented by this object * @return the {@code float} value represented by this object
* converted to type {@code long} * converted to type {@code long}
* @jls 5.1.3 Narrowing Primitive Conversions
*/ */
public long longValue() { public long longValue() {
return (long)value; return (long)value;
...@@ -610,11 +614,12 @@ public final class Float extends Number implements Comparable<Float> { ...@@ -610,11 +614,12 @@ public final class Float extends Number implements Comparable<Float> {
} }
/** /**
* Returns the {@code double} value of this {@code Float} object. * Returns the value of this {@code Float} as a {@code double}
* after a widening primitive conversion.
* *
* @return the {@code float} value represented by this * @return the {@code float} value represented by this
* object is converted to type {@code double} and the * object converted to type {@code double}
* result of the conversion is returned. * @jls 5.1.2 Widening Primitive Conversions
*/ */
public double doubleValue() { public double doubleValue() {
return (double)value; return (double)value;
......
/* /*
* Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -678,16 +678,18 @@ public final class Integer extends Number implements Comparable<Integer> { ...@@ -678,16 +678,18 @@ public final class Integer extends Number implements Comparable<Integer> {
} }
/** /**
* Returns the value of this {@code Integer} as a * Returns the value of this {@code Integer} as a {@code byte}
* {@code byte}. * after a narrowing primitive conversion.
* @jls 5.1.3 Narrowing Primitive Conversions
*/ */
public byte byteValue() { public byte byteValue() {
return (byte)value; return (byte)value;
} }
/** /**
* Returns the value of this {@code Integer} as a * Returns the value of this {@code Integer} as a {@code short}
* {@code short}. * after a narrowing primitive conversion.
* @jls 5.1.3 Narrowing Primitive Conversions
*/ */
public short shortValue() { public short shortValue() {
return (short)value; return (short)value;
...@@ -702,24 +704,27 @@ public final class Integer extends Number implements Comparable<Integer> { ...@@ -702,24 +704,27 @@ public final class Integer extends Number implements Comparable<Integer> {
} }
/** /**
* Returns the value of this {@code Integer} as a * Returns the value of this {@code Integer} as a {@code long}
* {@code long}. * after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public long longValue() { public long longValue() {
return (long)value; return (long)value;
} }
/** /**
* Returns the value of this {@code Integer} as a * Returns the value of this {@code Integer} as a {@code float}
* {@code float}. * after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public float floatValue() { public float floatValue() {
return (float)value; return (float)value;
} }
/** /**
* Returns the value of this {@code Integer} as a * Returns the value of this {@code Integer} as a {@code double}
* {@code double}. * after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public double doubleValue() { public double doubleValue() {
return (double)value; return (double)value;
......
/* /*
* Copyright (c) 1994, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -703,24 +703,27 @@ public final class Long extends Number implements Comparable<Long> { ...@@ -703,24 +703,27 @@ public final class Long extends Number implements Comparable<Long> {
} }
/** /**
* Returns the value of this {@code Long} as a * Returns the value of this {@code Long} as a {@code byte} after
* {@code byte}. * a narrowing primitive conversion.
* @jls 5.1.3 Narrowing Primitive Conversions
*/ */
public byte byteValue() { public byte byteValue() {
return (byte)value; return (byte)value;
} }
/** /**
* Returns the value of this {@code Long} as a * Returns the value of this {@code Long} as a {@code short} after
* {@code short}. * a narrowing primitive conversion.
* @jls 5.1.3 Narrowing Primitive Conversions
*/ */
public short shortValue() { public short shortValue() {
return (short)value; return (short)value;
} }
/** /**
* Returns the value of this {@code Long} as an * Returns the value of this {@code Long} as an {@code int} after
* {@code int}. * a narrowing primitive conversion.
* @jls 5.1.3 Narrowing Primitive Conversions
*/ */
public int intValue() { public int intValue() {
return (int)value; return (int)value;
...@@ -735,16 +738,18 @@ public final class Long extends Number implements Comparable<Long> { ...@@ -735,16 +738,18 @@ public final class Long extends Number implements Comparable<Long> {
} }
/** /**
* Returns the value of this {@code Long} as a * Returns the value of this {@code Long} as a {@code float} after
* {@code float}. * a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public float floatValue() { public float floatValue() {
return (float)value; return (float)value;
} }
/** /**
* Returns the value of this {@code Long} as a * Returns the value of this {@code Long} as a {@code double}
* {@code double}. * after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public double doubleValue() { public double doubleValue() {
return (double)value; return (double)value;
......
/* /*
* Copyright (c) 1994, 2001, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -26,69 +26,78 @@ ...@@ -26,69 +26,78 @@
package java.lang; package java.lang;
/** /**
* The abstract class <code>Number</code> is the superclass of classes * The abstract class {@code Number} is the superclass of platform
* <code>BigDecimal</code>, <code>BigInteger</code>, * classes representing numeric values that are convertible to the
* <code>Byte</code>, <code>Double</code>, <code>Float</code>, * primitive types {@code byte}, {@code double}, {@code float}, {@code
* <code>Integer</code>, <code>Long</code>, and <code>Short</code>. * int}, {@code long}, and {@code short}.
* <p> *
* Subclasses of <code>Number</code> must provide methods to convert * The specific semantics of the conversion from the numeric value of
* the represented numeric value to <code>byte</code>, <code>double</code>, * a particular {@code Number} implementation to a given primitive
* <code>float</code>, <code>int</code>, <code>long</code>, and * type is defined by the {@code Number} implementation in question.
* <code>short</code>. *
* For platform classes, the conversion is often analogous to a
* narrowing primitive conversion or a widening primitive conversion
* as defining in <cite>The Java&trade; Language Specification</cite>
* for converting between primitive types. Therefore, conversions may
* lose information about the overall magnitude of a numeric value, may
* lose precision, and may even return a result of a different sign
* than the input.
*
* See the documentation of a given {@code Number} implementation for
* conversion details.
* *
* @author Lee Boynton * @author Lee Boynton
* @author Arthur van Hoff * @author Arthur van Hoff
* @see java.lang.Byte * @jls 5.1.2 Widening Primitive Conversions
* @see java.lang.Double * @jls 5.1.3 Narrowing Primitive Conversions
* @see java.lang.Float
* @see java.lang.Integer
* @see java.lang.Long
* @see java.lang.Short
* @since JDK1.0 * @since JDK1.0
*/ */
public abstract class Number implements java.io.Serializable { public abstract class Number implements java.io.Serializable {
/** /**
* Returns the value of the specified number as an <code>int</code>. * Returns the value of the specified number as an {@code int},
* This may involve rounding or truncation. * which may involve rounding or truncation.
* *
* @return the numeric value represented by this object after conversion * @return the numeric value represented by this object after conversion
* to type <code>int</code>. * to type {@code int}.
*/ */
public abstract int intValue(); public abstract int intValue();
/** /**
* Returns the value of the specified number as a <code>long</code>. * Returns the value of the specified number as a {@code long},
* This may involve rounding or truncation. * which may involve rounding or truncation.
* *
* @return the numeric value represented by this object after conversion * @return the numeric value represented by this object after conversion
* to type <code>long</code>. * to type {@code long}.
*/ */
public abstract long longValue(); public abstract long longValue();
/** /**
* Returns the value of the specified number as a <code>float</code>. * Returns the value of the specified number as a {@code float},
* This may involve rounding. * which may involve rounding.
* *
* @return the numeric value represented by this object after conversion * @return the numeric value represented by this object after conversion
* to type <code>float</code>. * to type {@code float}.
*/ */
public abstract float floatValue(); public abstract float floatValue();
/** /**
* Returns the value of the specified number as a <code>double</code>. * Returns the value of the specified number as a {@code double},
* This may involve rounding. * which may involve rounding.
* *
* @return the numeric value represented by this object after conversion * @return the numeric value represented by this object after conversion
* to type <code>double</code>. * to type {@code double}.
*/ */
public abstract double doubleValue(); public abstract double doubleValue();
/** /**
* Returns the value of the specified number as a <code>byte</code>. * Returns the value of the specified number as a {@code byte},
* This may involve rounding or truncation. * which may involve rounding or truncation.
*
* <p>This implementation returns the result of {@link #intValue} cast
* to a {@code byte}.
* *
* @return the numeric value represented by this object after conversion * @return the numeric value represented by this object after conversion
* to type <code>byte</code>. * to type {@code byte}.
* @since JDK1.1 * @since JDK1.1
*/ */
public byte byteValue() { public byte byteValue() {
...@@ -96,11 +105,14 @@ public abstract class Number implements java.io.Serializable { ...@@ -96,11 +105,14 @@ public abstract class Number implements java.io.Serializable {
} }
/** /**
* Returns the value of the specified number as a <code>short</code>. * Returns the value of the specified number as a {@code short},
* This may involve rounding or truncation. * which may involve rounding or truncation.
*
* <p>This implementation returns the result of {@link #intValue} cast
* to a {@code short}.
* *
* @return the numeric value represented by this object after conversion * @return the numeric value represented by this object after conversion
* to type <code>short</code>. * to type {@code short}.
* @since JDK1.1 * @since JDK1.1
*/ */
public short shortValue() { public short shortValue() {
......
/* /*
* Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -321,8 +321,9 @@ public final class Short extends Number implements Comparable<Short> { ...@@ -321,8 +321,9 @@ public final class Short extends Number implements Comparable<Short> {
} }
/** /**
* Returns the value of this {@code Short} as a * Returns the value of this {@code Short} as a {@code byte} after
* {@code byte}. * a narrowing primitive conversion.
* @jls 5.1.3 Narrowing Primitive Conversions
*/ */
public byte byteValue() { public byte byteValue() {
return (byte)value; return (byte)value;
...@@ -337,32 +338,36 @@ public final class Short extends Number implements Comparable<Short> { ...@@ -337,32 +338,36 @@ public final class Short extends Number implements Comparable<Short> {
} }
/** /**
* Returns the value of this {@code Short} as an * Returns the value of this {@code Short} as an {@code int} after
* {@code int}. * a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public int intValue() { public int intValue() {
return (int)value; return (int)value;
} }
/** /**
* Returns the value of this {@code Short} as a * Returns the value of this {@code Short} as a {@code long} after
* {@code long}. * a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public long longValue() { public long longValue() {
return (long)value; return (long)value;
} }
/** /**
* Returns the value of this {@code Short} as a * Returns the value of this {@code Short} as a {@code float}
* {@code float}. * after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public float floatValue() { public float floatValue() {
return (float)value; return (float)value;
} }
/** /**
* Returns the value of this {@code Short} as a * Returns the value of this {@code Short} as a {@code double}
* {@code double}. * after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/ */
public double doubleValue() { public double doubleValue() {
return (double)value; return (double)value;
......
/* /*
* Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -41,21 +41,23 @@ package java.lang.annotation; ...@@ -41,21 +41,23 @@ package java.lang.annotation;
public class IncompleteAnnotationException extends RuntimeException { public class IncompleteAnnotationException extends RuntimeException {
private static final long serialVersionUID = 8445097402741811912L; private static final long serialVersionUID = 8445097402741811912L;
private Class annotationType; private Class<? extends Annotation> annotationType;
private String elementName; private String elementName;
/** /**
* Constructs an IncompleteAnnotationException to indicate that * Constructs an IncompleteAnnotationException to indicate that
* the named element was missing from the specified annotation type. * the named element was missing from the specified annotation type.
* *
* @param annotationType the Class object for the annotation type * @param annotationType the Class object for the annotation type
* @param elementName the name of the missing element * @param elementName the name of the missing element
* @throws NullPointerException if either parameter is {@code null}
*/ */
public IncompleteAnnotationException( public IncompleteAnnotationException(
Class<? extends Annotation> annotationType, Class<? extends Annotation> annotationType,
String elementName) { String elementName) {
super(annotationType.getName() + " missing element " + elementName); super(annotationType.getName().toString() +
" missing element " +
elementName.toString());
this.annotationType = annotationType; this.annotationType = annotationType;
this.elementName = elementName; this.elementName = elementName;
......
/* /*
* Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -35,4 +35,22 @@ package java.lang.reflect; ...@@ -35,4 +35,22 @@ package java.lang.reflect;
*/ */
public class GenericSignatureFormatError extends ClassFormatError { public class GenericSignatureFormatError extends ClassFormatError {
private static final long serialVersionUID = 6709919147137911034L; private static final long serialVersionUID = 6709919147137911034L;
/**
* Constructs a new {@code GenericSignatureFormatError}.
*
*/
public GenericSignatureFormatError() {
super();
}
/**
* Constructs a new {@code GenericSignatureFormatError} with the
* specified message.
*
* @param message the detail message, may be {@code null}
*/
public GenericSignatureFormatError(String message) {
super(message);
}
} }
/* /*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -118,15 +118,17 @@ public final class UID implements Serializable { ...@@ -118,15 +118,17 @@ public final class UID implements Serializable {
boolean done = false; boolean done = false;
while (!done) { while (!done) {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
if (now <= lastTime) { if (now == lastTime) {
// wait for time to change // wait for time to change
try { try {
Thread.currentThread().sleep(1); Thread.sleep(1);
} catch (InterruptedException e) { } catch (InterruptedException e) {
interrupted = true; interrupted = true;
} }
} else { } else {
lastTime = now; // If system time has gone backwards increase
// original by 1ms to maintain uniqueness
lastTime = (now < lastTime) ? lastTime+1 : now;
lastCount = Short.MIN_VALUE; lastCount = Short.MIN_VALUE;
done = true; done = true;
} }
......
...@@ -118,7 +118,13 @@ class Random implements java.io.Serializable { ...@@ -118,7 +118,13 @@ class Random implements java.io.Serializable {
* @see #setSeed(long) * @see #setSeed(long)
*/ */
public Random(long seed) { public Random(long seed) {
this.seed = new AtomicLong(initialScramble(seed)); if (getClass() == Random.class)
this.seed = new AtomicLong(initialScramble(seed));
else {
// subclass might have overriden setSeed
this.seed = new AtomicLong();
setSeed(seed);
}
} }
private static long initialScramble(long seed) { private static long initialScramble(long seed) {
......
...@@ -246,18 +246,37 @@ public class AtomicInteger extends Number implements java.io.Serializable { ...@@ -246,18 +246,37 @@ public class AtomicInteger extends Number implements java.io.Serializable {
} }
/**
* Returns the value of this {@code AtomicInteger} as an
* {@code int}.
*/
public int intValue() { public int intValue() {
return get(); return get();
} }
/**
* Returns the value of this {@code AtomicInteger} as a {@code long}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/
public long longValue() { public long longValue() {
return (long)get(); return (long)get();
} }
/**
* Returns the value of this {@code AtomicInteger} as a {@code float}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/
public float floatValue() { public float floatValue() {
return (float)get(); return (float)get();
} }
/**
* Returns the value of this {@code AtomicInteger} as a {@code double}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/
public double doubleValue() { public double doubleValue() {
return (double)get(); return (double)get();
} }
......
...@@ -260,18 +260,37 @@ public class AtomicLong extends Number implements java.io.Serializable { ...@@ -260,18 +260,37 @@ public class AtomicLong extends Number implements java.io.Serializable {
} }
/**
* Returns the value of this {@code AtomicLong} as an {@code int}
* after a narrowing primitive conversion.
* @jls 5.1.3 Narrowing Primitive Conversions
*/
public int intValue() { public int intValue() {
return (int)get(); return (int)get();
} }
/**
* Returns the value of this {@code AtomicLong} as a {@code long}
* value.
*/
public long longValue() { public long longValue() {
return get(); return get();
} }
/**
* Returns the value of this {@code AtomicLong} as a {@code float}
* after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/
public float floatValue() { public float floatValue() {
return (float)get(); return (float)get();
} }
/**
* Returns the value of this {@code AtomicLong} as a {@code
* double} after a widening primitive conversion.
* @jls 5.1.2 Widening Primitive Conversions
*/
public double doubleValue() { public double doubleValue() {
return (double)get(); return (double)get();
} }
......
...@@ -251,7 +251,10 @@ public class Logger { ...@@ -251,7 +251,10 @@ public class Logger {
protected Logger(String name, String resourceBundleName) { protected Logger(String name, String resourceBundleName) {
this.manager = LogManager.getLogManager(); this.manager = LogManager.getLogManager();
if (resourceBundleName != null) { if (resourceBundleName != null) {
// Note: we may get a MissingResourceException here. // MissingResourceException or IllegalArgumentException can
// be thrown by setupResourceInfo(). Since this is the Logger
// constructor, the resourceBundleName field is null so
// IllegalArgumentException cannot happen here.
setupResourceInfo(resourceBundleName); setupResourceInfo(resourceBundleName);
} }
this.name = name; this.name = name;
...@@ -374,13 +377,10 @@ public class Logger { ...@@ -374,13 +377,10 @@ public class Logger {
public static Logger getLogger(String name, String resourceBundleName) { public static Logger getLogger(String name, String resourceBundleName) {
LogManager manager = LogManager.getLogManager(); LogManager manager = LogManager.getLogManager();
Logger result = manager.demandLogger(name); Logger result = manager.demandLogger(name);
if (result.resourceBundleName == null) {
// Note: we may get a MissingResourceException here. // MissingResourceException or IllegalArgumentException can be
result.setupResourceInfo(resourceBundleName); // thrown by setupResourceInfo().
} else if (!result.resourceBundleName.equals(resourceBundleName)) { result.setupResourceInfo(resourceBundleName);
throw new IllegalArgumentException(result.resourceBundleName +
" != " + resourceBundleName);
}
return result; return result;
} }
...@@ -1353,14 +1353,29 @@ public class Logger { ...@@ -1353,14 +1353,29 @@ public class Logger {
} }
// Private utility method to initialize our one entry // Private utility method to initialize our one entry
// resource bundle cache. // resource bundle name cache.
// Note: for consistency reasons, we are careful to check // Note: for consistency reasons, we are careful to check
// that a suitable ResourceBundle exists before setting the // that a suitable ResourceBundle exists before setting the
// ResourceBundleName. // resourceBundleName field.
// Synchronized to prevent races in setting the field.
private synchronized void setupResourceInfo(String name) { private synchronized void setupResourceInfo(String name) {
if (name == null) { if (name == null) {
return; return;
} }
if (resourceBundleName != null) {
// this Logger already has a ResourceBundle
if (resourceBundleName.equals(name)) {
// the names match so there is nothing more to do
return;
}
// cannot change ResourceBundles once they are set
throw new IllegalArgumentException(
resourceBundleName + " != " + name);
}
ResourceBundle rb = findResourceBundle(name); ResourceBundle rb = findResourceBundle(name);
if (rb == null) { if (rb == null) {
// We've failed to find an expected ResourceBundle. // We've failed to find an expected ResourceBundle.
......
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
package javax.security.auth.kerberos; package javax.security.auth.kerberos;
import sun.misc.JavaxSecurityAuthKerberosAccess; import sun.security.krb5.JavaxSecurityAuthKerberosAccess;
import sun.security.krb5.EncryptionKey; import sun.security.krb5.EncryptionKey;
import sun.security.krb5.PrincipalName; import sun.security.krb5.PrincipalName;
......
...@@ -27,8 +27,8 @@ package javax.security.auth.kerberos; ...@@ -27,8 +27,8 @@ package javax.security.auth.kerberos;
import java.io.File; import java.io.File;
import java.util.Objects; import java.util.Objects;
import sun.misc.SharedSecrets;
import sun.security.krb5.EncryptionKey; import sun.security.krb5.EncryptionKey;
import sun.security.krb5.KerberosSecrets;
import sun.security.krb5.PrincipalName; import sun.security.krb5.PrincipalName;
import sun.security.krb5.RealmException; import sun.security.krb5.RealmException;
...@@ -74,9 +74,9 @@ public final class KeyTab { ...@@ -74,9 +74,9 @@ public final class KeyTab {
// is maintained in snapshot, this field is never "resolved". // is maintained in snapshot, this field is never "resolved".
private final File file; private final File file;
// Set up JavaxSecurityAuthKerberosAccess in SharedSecrets // Set up JavaxSecurityAuthKerberosAccess in KerberosSecrets
static { static {
SharedSecrets.setJavaxSecurityAuthKerberosAccess( KerberosSecrets.setJavaxSecurityAuthKerberosAccess(
new JavaxSecurityAuthKerberosAccessImpl()); new JavaxSecurityAuthKerberosAccessImpl());
} }
......
...@@ -43,7 +43,7 @@ java.launcher.opt.footer =\ -cp <class search path of directories and zip ...@@ -43,7 +43,7 @@ java.launcher.opt.footer =\ -cp <class search path of directories and zip
\ and ZIP archives to search for class files.\n\ \ and ZIP archives to search for class files.\n\
\ -D<name>=<value>\n\ \ -D<name>=<value>\n\
\ set a system property\n\ \ set a system property\n\
\ -verbose[:class|gc|jni]\n\ \ -verbose:[class|gc|jni]\n\
\ enable verbose output\n\ \ enable verbose output\n\
\ -version print product version and exit\n\ \ -version print product version and exit\n\
\ -version:<value>\n\ \ -version:<value>\n\
......
...@@ -29,7 +29,6 @@ import java.util.jar.JarFile; ...@@ -29,7 +29,6 @@ import java.util.jar.JarFile;
import java.io.Console; import java.io.Console;
import java.io.FileDescriptor; import java.io.FileDescriptor;
import java.security.ProtectionDomain; import java.security.ProtectionDomain;
import javax.security.auth.kerberos.KeyTab;
import java.security.AccessController; import java.security.AccessController;
...@@ -52,7 +51,6 @@ public class SharedSecrets { ...@@ -52,7 +51,6 @@ public class SharedSecrets {
private static JavaIOFileDescriptorAccess javaIOFileDescriptorAccess; private static JavaIOFileDescriptorAccess javaIOFileDescriptorAccess;
private static JavaSecurityProtectionDomainAccess javaSecurityProtectionDomainAccess; private static JavaSecurityProtectionDomainAccess javaSecurityProtectionDomainAccess;
private static JavaSecurityAccess javaSecurityAccess; private static JavaSecurityAccess javaSecurityAccess;
private static JavaxSecurityAuthKerberosAccess javaxSecurityAuthKerberosAccess;
public static JavaUtilJarAccess javaUtilJarAccess() { public static JavaUtilJarAccess javaUtilJarAccess() {
if (javaUtilJarAccess == null) { if (javaUtilJarAccess == null) {
...@@ -141,16 +139,4 @@ public class SharedSecrets { ...@@ -141,16 +139,4 @@ public class SharedSecrets {
} }
return javaSecurityAccess; return javaSecurityAccess;
} }
public static void setJavaxSecurityAuthKerberosAccess
(JavaxSecurityAuthKerberosAccess jsaka) {
javaxSecurityAuthKerberosAccess = jsaka;
}
public static JavaxSecurityAuthKerberosAccess
getJavaxSecurityAuthKerberosAccess() {
if (javaxSecurityAuthKerberosAccess == null)
unsafe.ensureClassInitialized(KeyTab.class);
return javaxSecurityAuthKerberosAccess;
}
} }
...@@ -44,7 +44,7 @@ import java.util.Iterator; ...@@ -44,7 +44,7 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import sun.misc.SharedSecrets; import sun.security.krb5.KerberosSecrets;
import sun.security.krb5.PrincipalName; import sun.security.krb5.PrincipalName;
/** /**
* Utilities for obtaining and converting Kerberos tickets. * Utilities for obtaining and converting Kerberos tickets.
...@@ -378,7 +378,7 @@ public class Krb5Util { ...@@ -378,7 +378,7 @@ public class Krb5Util {
*/ */
public static EncryptionKey[] keysFromJavaxKeyTab( public static EncryptionKey[] keysFromJavaxKeyTab(
KeyTab ktab, PrincipalName cname) { KeyTab ktab, PrincipalName cname) {
return SharedSecrets.getJavaxSecurityAuthKerberosAccess(). return KerberosSecrets.getJavaxSecurityAuthKerberosAccess().
keyTabGetEncryptionKeys(ktab, cname); keyTabGetEncryptionKeys(ktab, cname);
} }
......
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
* questions. * questions.
*/ */
package sun.misc; package sun.security.krb5;
import javax.security.auth.kerberos.KeyTab; import javax.security.auth.kerberos.KeyTab;
import sun.security.krb5.EncryptionKey; import sun.security.krb5.EncryptionKey;
......
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.krb5;
import javax.security.auth.kerberos.KeyTab;
import sun.misc.Unsafe;
public class KerberosSecrets {
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static JavaxSecurityAuthKerberosAccess javaxSecurityAuthKerberosAccess;
public static void setJavaxSecurityAuthKerberosAccess
(JavaxSecurityAuthKerberosAccess jsaka) {
javaxSecurityAuthKerberosAccess = jsaka;
}
public static JavaxSecurityAuthKerberosAccess
getJavaxSecurityAuthKerberosAccess() {
if (javaxSecurityAuthKerberosAccess == null)
unsafe.ensureClassInitialized(KeyTab.class);
return javaxSecurityAuthKerberosAccess;
}
}
...@@ -4193,15 +4193,11 @@ class Pair<A, B> { ...@@ -4193,15 +4193,11 @@ class Pair<A, B> {
return "Pair[" + fst + "," + snd + "]"; return "Pair[" + fst + "," + snd + "]";
} }
private static boolean equals(Object x, Object y) {
return (x == null && y == null) || (x != null && x.equals(y));
}
public boolean equals(Object other) { public boolean equals(Object other) {
return return
other instanceof Pair && other instanceof Pair &&
equals(fst, ((Pair)other).fst) && Objects.equals(fst, ((Pair)other).fst) &&
equals(snd, ((Pair)other).snd); Objects.equals(snd, ((Pair)other).snd);
} }
public int hashCode() { public int hashCode() {
......
/* /*
* Copyright (c) 2002, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -318,13 +318,6 @@ public class DistributionPoint { ...@@ -318,13 +318,6 @@ public class DistributionPoint {
out.write(DerValue.tag_Sequence, tagged); out.write(DerValue.tag_Sequence, tagged);
} }
/**
* Utility function for a.equals(b) where both a and b may be null.
*/
private static boolean equals(Object a, Object b) {
return (a == null) ? (b == null) : a.equals(b);
}
/** /**
* Compare an object to this DistributionPoint for equality. * Compare an object to this DistributionPoint for equality.
* *
...@@ -340,9 +333,9 @@ public class DistributionPoint { ...@@ -340,9 +333,9 @@ public class DistributionPoint {
} }
DistributionPoint other = (DistributionPoint)obj; DistributionPoint other = (DistributionPoint)obj;
boolean equal = equals(this.fullName, other.fullName) boolean equal = Objects.equals(this.fullName, other.fullName)
&& equals(this.relativeName, other.relativeName) && Objects.equals(this.relativeName, other.relativeName)
&& equals(this.crlIssuer, other.crlIssuer) && Objects.equals(this.crlIssuer, other.crlIssuer)
&& Arrays.equals(this.reasonFlags, other.reasonFlags); && Arrays.equals(this.reasonFlags, other.reasonFlags);
return equal; return equal;
} }
......
/* /*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -201,8 +201,8 @@ public class DistributionPointName { ...@@ -201,8 +201,8 @@ public class DistributionPointName {
} }
DistributionPointName other = (DistributionPointName)obj; DistributionPointName other = (DistributionPointName)obj;
return equals(this.fullName, other.fullName) && return Objects.equals(this.fullName, other.fullName) &&
equals(this.relativeName, other.relativeName); Objects.equals(this.relativeName, other.relativeName);
} }
/** /**
...@@ -239,11 +239,4 @@ public class DistributionPointName { ...@@ -239,11 +239,4 @@ public class DistributionPointName {
return sb.toString(); return sb.toString();
} }
/*
* Utility function for a.equals(b) where both a and b may be null.
*/
private static boolean equals(Object a, Object b) {
return (a == null) ? (b == null) : a.equals(b);
}
} }
...@@ -95,14 +95,17 @@ public class Klist { ...@@ -95,14 +95,17 @@ public class Klist {
} }
break; break;
case 'k': case 'k':
try { KeyTab ktab = KeyTab.getInstance(klist.name);
KeyTab ktab = KeyTab.getInstance(klist.name); if (ktab.isMissing()) {
klist.target = ktab; System.out.println("KeyTab " + klist.name + " not found.");
klist.name = ktab.tabName(); System.exit(-1);
} catch (Exception e) { } else if (!ktab.isValid()) {
klist.displayMessage("KeyTab"); System.out.println("KeyTab " + klist.name
+ " format not supported.");
System.exit(-1); System.exit(-1);
} }
klist.target = ktab;
klist.name = ktab.tabName();
klist.displayTab(); klist.displayTab();
break; break;
default: default:
......
...@@ -510,13 +510,17 @@ jdk_nio2: $(call TestDirs, java/nio/Buffer java/nio/ByteOrder \ ...@@ -510,13 +510,17 @@ jdk_nio2: $(call TestDirs, java/nio/Buffer java/nio/ByteOrder \
# Stable samevm testruns (minus items from PROBLEM_LIST) # Stable samevm testruns (minus items from PROBLEM_LIST)
JDK_ALL_TARGETS += jdk_nio3 JDK_ALL_TARGETS += jdk_nio3
jdk_nio3: $(call TestDirs, com/sun/nio sun/nio) jdk_nio3: $(call TestDirs, sun/nio)
$(call RunSamevmBatch) $(call RunSamevmBatch)
# All nio tests # All nio tests
jdk_nio: jdk_nio1 jdk_nio2 jdk_nio3 jdk_nio: jdk_nio1 jdk_nio2 jdk_nio3
@$(SummaryInfo) @$(SummaryInfo)
# Stable samevm testruns (minus items from PROBLEM_LIST)
jdk_sctp: $(call TestDirs, com/sun/nio/sctp)
$(call RunSamevmBatch)
# Stable othervm testruns (minus items from PROBLEM_LIST) # Stable othervm testruns (minus items from PROBLEM_LIST)
# Using samevm has serious problems with these tests # Using samevm has serious problems with these tests
JDK_ALL_TARGETS += jdk_rmi JDK_ALL_TARGETS += jdk_rmi
...@@ -532,7 +536,7 @@ jdk_security1: $(call TestDirs, java/security) ...@@ -532,7 +536,7 @@ jdk_security1: $(call TestDirs, java/security)
# Using samevm has serious problems with these tests # Using samevm has serious problems with these tests
JDK_ALL_TARGETS += jdk_security2 JDK_ALL_TARGETS += jdk_security2
jdk_security2: $(call TestDirs, javax/crypto com/sun/crypto) jdk_security2: $(call TestDirs, javax/crypto com/sun/crypto)
$(call RunOthervmBatch) $(call RunSamevmBatch)
# Stable othervm testruns (minus items from PROBLEM_LIST) # Stable othervm testruns (minus items from PROBLEM_LIST)
# Using samevm has serious problems with these tests # Using samevm has serious problems with these tests
......
...@@ -198,18 +198,6 @@ java/beans/XMLEncoder/6329581/Test6329581.java generic-all ...@@ -198,18 +198,6 @@ java/beans/XMLEncoder/6329581/Test6329581.java generic-all
# requires junit # requires junit
java/lang/invoke/InvokeDynamicPrintArgs.java generic-all java/lang/invoke/InvokeDynamicPrintArgs.java generic-all
# Times out on solaris 10 sparc
java/lang/ClassLoader/Assert.java generic-all
# Solaris sparc, samevm, java.lang.Exception: Read from closed pipe hangs
java/lang/Runtime/exec/SleepyCat.java generic-all
# Times out on solaris sparc -server
java/lang/ThreadLocal/MemoryLeak.java solaris-all
# Windows X64, RuntimeException: MyThread expected to have RUNNABLE but got WAITING
java/lang/Thread/ThreadStateTest.java generic-all
############################################################################ ############################################################################
# jdk_management # jdk_management
...@@ -296,7 +284,6 @@ javax/management/monitor/AttributeArbitraryDataTypeTest.java generic-all ...@@ -296,7 +284,6 @@ javax/management/monitor/AttributeArbitraryDataTypeTest.java generic-all
# jdk_misc # jdk_misc
# Need to be marked othervm, or changed to be samevm safe # Need to be marked othervm, or changed to be samevm safe
com/sun/jndi/ldap/ReadTimeoutTest.java generic-all
com/sun/jndi/rmi/registry/RegistryContext/UnbindIdempotent.java generic-all com/sun/jndi/rmi/registry/RegistryContext/UnbindIdempotent.java generic-all
# Need to be marked othervm, or changed to be samevm safe # Need to be marked othervm, or changed to be samevm safe
...@@ -380,30 +367,6 @@ java/io/File/MaxPathLength.java windows-all ...@@ -380,30 +367,6 @@ java/io/File/MaxPathLength.java windows-all
# 6963118 # 6963118
java/nio/channels/Selector/Wakeup.java windows-all java/nio/channels/Selector/Wakeup.java windows-all
# 6959891
com/sun/nio/sctp/SctpChannel/SocketOptionTests.java
# Fails with -ea -esa, Assertion error, but only on Solaris 10 machines?
com/sun/nio/sctp/SctpChannel/Send.java generic-all
com/sun/nio/sctp/SctpChannel/Shutdown.java generic-all
# Fails on OpenSolaris, IllegalStateException: Cannot add or remove addresses
# from a channel that is bound to the wildcard address
com/sun/nio/sctp/SctpChannel/Bind.java generic-all
# Failed on OpenSolaris, java.lang.AssertionError: Unknown event type
com/sun/nio/sctp/SctpChannel/Receive.java generic-all
# Solaris 11 gave assert error and "connection refused", samevm issues?
com/sun/nio/sctp/SctpServerChannel/NonBlockingAccept.java generic-all
# Fails with othervm on solaris 11 i586
com/sun/nio/sctp/SctpChannel/CommUp.java generic-all
com/sun/nio/sctp/SctpChannel/Connect.java generic-all
com/sun/nio/sctp/SctpMultiChannel/Branch.java generic-all
com/sun/nio/sctp/SctpMultiChannel/Send.java generic-all
com/sun/nio/sctp/SctpMultiChannel/SocketOptionTests.java generic-all
############################################################################ ############################################################################
# jdk_rmi # jdk_rmi
...@@ -503,10 +466,6 @@ sun/security/pkcs11/ec/TestECDSA.java solaris-i586 ...@@ -503,10 +466,6 @@ sun/security/pkcs11/ec/TestECDSA.java solaris-i586
sun/security/pkcs11/ec/TestECGenSpec.java solaris-i586 sun/security/pkcs11/ec/TestECGenSpec.java solaris-i586
sun/security/pkcs11/ec/TestKeyFactory.java solaris-i586 sun/security/pkcs11/ec/TestKeyFactory.java solaris-i586
# Unknown problem, could be a jtreg -samevm issue?
# Error while cleaning up threads after test
java/security/Security/SynchronizedAccess.java generic-all
# Failing on Solaris X64 (-d64 -server) with: # Failing on Solaris X64 (-d64 -server) with:
# GSSException: Failure unspecified at GSS-API level # GSSException: Failure unspecified at GSS-API level
# (Mechanism level: Specified version of key is not available (44)) # (Mechanism level: Specified version of key is not available (44))
...@@ -592,37 +551,9 @@ sun/security/tools/jarsigner/oldsig.sh generic-all ...@@ -592,37 +551,9 @@ sun/security/tools/jarsigner/oldsig.sh generic-all
# Various failures on Linux Fedora 9 X64, othervm mode # Various failures on Linux Fedora 9 X64, othervm mode
sun/security/ssl/sanity/interop/ClientJSSEServerJSSE.java generic-all sun/security/ssl/sanity/interop/ClientJSSEServerJSSE.java generic-all
# Linux i586 -server, buffer too short to hold shared secret?
com/sun/crypto/provider/KeyAgreement/DHKeyAgreement2.java generic-all
# Solaris sparcv9: Failed to parse input emptysubject.jks: No such file or directory # Solaris sparcv9: Failed to parse input emptysubject.jks: No such file or directory
sun/security/tools/keytool/emptysubject.sh generic-all sun/security/tools/keytool/emptysubject.sh generic-all
# Timeout on solaris-sparcv9 or exception thrown
com/sun/crypto/provider/Cipher/RSA/TestOAEP_KAT.java solaris-all
# Leaving file open: SerialVersion.current, windows samevm
java/security/BasicPermission/SerialVersion.java generic-all
# Solaris 11 i586, these all fail with samevm, need to be othervm???
java/security/BasicPermission/NullOrEmptyName.java generic-all
# Suspect missing close() on file PermClass.current, windows samevm cascade
java/security/BasicPermission/PermClass.java generic-all
# Solaris 11 i586, these all fail with samevm, need to be othervm???
java/security/KeyPairGenerator/Failover.java generic-all
java/security/Provider/DefaultPKCS11.java generic-all
java/security/SecureClassLoader/DefineClassByteBuffer.java generic-all
java/security/SecureRandom/GetAlgorithm.java generic-all
java/security/Security/removing/RemoveProviders.java generic-all
java/security/Signature/ByteBuffers.java generic-all
java/security/Signature/NONEwithRSA.java generic-all
java/security/Signature/SignWithOutputBuffer.java generic-all
java/security/Signature/TestInitSignWithMyOwnRandom.java generic-all
java/security/UnresolvedPermission/AccessorMethods.java generic-all
java/security/UnresolvedPermission/Equals.java generic-all
# Fails on OpenSolaris, missing classes, slow on Solaris sparc # Fails on OpenSolaris, missing classes, slow on Solaris sparc
sun/security/ec/TestEC.java generic-all sun/security/ec/TestEC.java generic-all
...@@ -643,9 +574,6 @@ sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java generic-all ...@@ -643,9 +574,6 @@ sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java generic-all
sun/security/rsa/TestKeyPairGeneratorLength.java solaris-all sun/security/rsa/TestKeyPairGeneratorLength.java solaris-all
sun/security/rsa/TestSignatures.java solaris-all sun/security/rsa/TestSignatures.java solaris-all
# Timeout on solaris-sparc and i586 and x64, -client and -server
sun/security/ssl/com/sun/net/ssl/internal/ssl/InputRecord/InterruptedIO.java solaris-all
# Do not seem to run on windows machines? dll missing? # Do not seem to run on windows machines? dll missing?
sun/security/tools/jarsigner/emptymanifest.sh windows-all sun/security/tools/jarsigner/emptymanifest.sh windows-all
......
/* /*
* Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
/* /*
* @test * @test
* @bug 0000000 * @bug 0000000 7055362
* @summary Sealtest * @summary Sealtest
* @author Jan Luehe * @author Jan Luehe
*/ */
...@@ -54,14 +54,16 @@ public class Sealtest { ...@@ -54,14 +54,16 @@ public class Sealtest {
SealedObject sealed = new SealedObject(kp.getPrivate(), c); SealedObject sealed = new SealedObject(kp.getPrivate(), c);
// serialize // serialize
FileOutputStream fos = new FileOutputStream("sealed"); try (FileOutputStream fos = new FileOutputStream("sealed");
ObjectOutputStream oos = new ObjectOutputStream(fos); ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(sealed); oos.writeObject(sealed);
}
// deserialize // deserialize
FileInputStream fis = new FileInputStream("sealed"); try (FileInputStream fis = new FileInputStream("sealed");
ObjectInputStream ois = new ObjectInputStream(fis); ObjectInputStream ois = new ObjectInputStream(fis)) {
sealed = (SealedObject)ois.readObject(); sealed = (SealedObject)ois.readObject();
}
System.out.println(sealed.getAlgorithm()); System.out.println(sealed.getAlgorithm());
......
/* /*
* Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
/* /*
* @test * @test
* @bug 4894151 * @bug 4894151 7055362
* @summary known answer test for OAEP encryption * @summary known answer test for OAEP encryption
* @author Andreas Sterbenz * @author Andreas Sterbenz
*/ */
...@@ -62,60 +62,62 @@ public class TestOAEP_KAT { ...@@ -62,60 +62,62 @@ public class TestOAEP_KAT {
System.out.println("Testing provider " + provider.getName() + "..."); System.out.println("Testing provider " + provider.getName() + "...");
Cipher c = Cipher.getInstance("RSA/ECB/OAEPwithSHA1andMGF1Padding", provider); Cipher c = Cipher.getInstance("RSA/ECB/OAEPwithSHA1andMGF1Padding", provider);
KeyFactory kf = KeyFactory.getInstance("RSA", kfProvider); KeyFactory kf = KeyFactory.getInstance("RSA", kfProvider);
InputStream in = new FileInputStream(new File(BASE, "oaep-vect.txt")); try (InputStream in = new FileInputStream(new File(BASE, "oaep-vect.txt"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF8")); BufferedReader reader =
while (true) { new BufferedReader(new InputStreamReader(in, "UTF8"))) {
String line = reader.readLine(); while (true) {
if (line == null) { String line = reader.readLine();
break; if (line == null) {
} break;
line = line.trim(); }
if (line.length() == 0) { line = line.trim();
continue; if (line.length() == 0) {
} continue;
if (line.equals("# RSA modulus n:")) {
n = parseNumber(reader);
} else if (line.equals("# RSA public exponent e:")) {
e = parseNumber(reader);
} else if (line.equals("# RSA private exponent d:")) {
d = parseNumber(reader);
} else if (line.equals("# Prime p:")) {
p = parseNumber(reader);
} else if (line.equals("# Prime q:")) {
q = parseNumber(reader);
} else if (line.equals("# p's CRT exponent dP:")) {
pe = parseNumber(reader);
} else if (line.equals("# q's CRT exponent dQ:")) {
qe = parseNumber(reader);
} else if (line.equals("# CRT coefficient qInv:")) {
coeff = parseNumber(reader);
} else if (line.equals("# Message to be encrypted:")) {
plainText = parseBytes(reader);
} else if (line.equals("# Seed:")) {
seed = parseBytes(reader);
} else if (line.equals("# Encryption:")) {
cipherText = parseBytes(reader);
// do encryption test first
KeySpec pubSpec = new RSAPublicKeySpec(n, e);
PublicKey pubKey = kf.generatePublic(pubSpec);
c.init(Cipher.ENCRYPT_MODE, pubKey, new MyRandom(seed));
cipherText2 = c.doFinal(plainText);
if (Arrays.equals(cipherText2, cipherText) == false) {
throw new Exception("Encryption mismatch");
} }
// followed by decryption test if (line.equals("# RSA modulus n:")) {
KeySpec privSpec = new RSAPrivateCrtKeySpec(n, e, d, p, q, pe, qe, coeff); n = parseNumber(reader);
PrivateKey privKey = kf.generatePrivate(privSpec); } else if (line.equals("# RSA public exponent e:")) {
c.init(Cipher.DECRYPT_MODE, privKey); e = parseNumber(reader);
byte[] dec = c.doFinal(cipherText); } else if (line.equals("# RSA private exponent d:")) {
if (Arrays.equals(plainText, dec) == false) { d = parseNumber(reader);
throw new Exception("Decryption mismatch"); } else if (line.equals("# Prime p:")) {
p = parseNumber(reader);
} else if (line.equals("# Prime q:")) {
q = parseNumber(reader);
} else if (line.equals("# p's CRT exponent dP:")) {
pe = parseNumber(reader);
} else if (line.equals("# q's CRT exponent dQ:")) {
qe = parseNumber(reader);
} else if (line.equals("# CRT coefficient qInv:")) {
coeff = parseNumber(reader);
} else if (line.equals("# Message to be encrypted:")) {
plainText = parseBytes(reader);
} else if (line.equals("# Seed:")) {
seed = parseBytes(reader);
} else if (line.equals("# Encryption:")) {
cipherText = parseBytes(reader);
// do encryption test first
KeySpec pubSpec = new RSAPublicKeySpec(n, e);
PublicKey pubKey = kf.generatePublic(pubSpec);
c.init(Cipher.ENCRYPT_MODE, pubKey, new MyRandom(seed));
cipherText2 = c.doFinal(plainText);
if (Arrays.equals(cipherText2, cipherText) == false) {
throw new Exception("Encryption mismatch");
}
// followed by decryption test
KeySpec privSpec = new RSAPrivateCrtKeySpec(n, e, d, p, q, pe, qe, coeff);
PrivateKey privKey = kf.generatePrivate(privSpec);
c.init(Cipher.DECRYPT_MODE, privKey);
byte[] dec = c.doFinal(cipherText);
if (Arrays.equals(plainText, dec) == false) {
throw new Exception("Decryption mismatch");
}
} else if (line.startsWith("# ------------------------------")) {
// ignore, do not print
} else {
// unknown line (comment), print
System.out.println(": " + line);
} }
} else if (line.startsWith("# ------------------------------")) {
// ignore, do not print
} else {
// unknown line (comment), print
System.out.println(": " + line);
} }
} }
long stop = System.currentTimeMillis(); long stop = System.currentTimeMillis();
......
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
/** /**
* @test * @test
* @bug 6176036 * @bug 6176036 7056489
* @summary Read-timeout specification for LDAP operations * @summary Read-timeout specification for LDAP operations
*/ */
...@@ -37,40 +37,37 @@ import java.util.Hashtable; ...@@ -37,40 +37,37 @@ import java.util.Hashtable;
public class ReadTimeoutTest { public class ReadTimeoutTest {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
boolean passed = false; boolean passed = false;
// Set up the environment for creating the initial context // create the server
Hashtable env = new Hashtable(11); try (Server server = Server.create()) {
env.put(Context.INITIAL_CONTEXT_FACTORY, // Set up the environment for creating the initial context
"com.sun.jndi.ldap.LdapCtxFactory"); Hashtable<String,Object> env = new Hashtable<>(11);
env.put("com.sun.jndi.ldap.read.timeout", "1000"); env.put(Context.INITIAL_CONTEXT_FACTORY,
env.put(Context.PROVIDER_URL, "ldap://localhost:2001"); "com.sun.jndi.ldap.LdapCtxFactory");
env.put("com.sun.jndi.ldap.read.timeout", "1000");
Server s = new Server(); env.put(Context.PROVIDER_URL, "ldap://localhost:" + server.port());
try {
// start the server
s.start();
// Create initial context // Create initial context
DirContext ctx = new InitialDirContext(env); DirContext ctx = new InitialDirContext(env);
System.out.println("LDAP Client: Connected to the Server"); try {
System.out.println("LDAP Client: Connected to the Server");
SearchControls scl = new SearchControls();
scl.setSearchScope(SearchControls.SUBTREE_SCOPE); SearchControls scl = new SearchControls();
System.out.println("Performing Search"); scl.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration answer = System.out.println("Performing Search");
ctx.search("ou=People,o=JNDITutorial", "(objectClass=*)", scl); NamingEnumeration<SearchResult> answer =
ctx.search("ou=People,o=JNDITutorial", "(objectClass=*)", scl);
// Close the context when we're done } finally {
ctx.close(); // Close the context when we're done
ctx.close();
}
} catch (NamingException e) { } catch (NamingException e) {
passed = true; passed = true;
e.printStackTrace(); e.printStackTrace();
} }
s.interrupt();
if (!passed) { if (!passed) {
throw new Exception("Read timeout test failed," + throw new Exception("Read timeout test failed," +
" read timeout exception not thrown"); " read timeout exception not thrown");
...@@ -78,27 +75,39 @@ public class ReadTimeoutTest { ...@@ -78,27 +75,39 @@ public class ReadTimeoutTest {
System.out.println("The test PASSED"); System.out.println("The test PASSED");
} }
static class Server extends Thread { static class Server implements Runnable, Closeable {
private final ServerSocket ss;
static int serverPort = 2001; private Server(ServerSocket ss) {
this.ss = ss;
}
Server() { static Server create() throws IOException {
Server server = new Server(new ServerSocket(0));
new Thread(server).start();
return server;
}
int port() {
return ss.getLocalPort();
} }
public void run() { public void run() {
try { try (Socket s = ss.accept()) {
ServerSocket serverSock = new ServerSocket(serverPort);
Socket socket = serverSock.accept();
System.out.println("Server: Connection accepted"); System.out.println("Server: Connection accepted");
BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
BufferedInputStream bin = new BufferedInputStream(socket. byte[] buf = new byte[100];
getInputStream()); int n;
while (true) { do {
bin.read(); n = bis.read(buf);
} } while (n > 0);
} catch (IOException e) { } catch (IOException e) {
// ignore // ignore
} }
}
public void close() throws IOException {
ss.close();
}
} }
} }
}
...@@ -43,14 +43,12 @@ public class B6373555 { ...@@ -43,14 +43,12 @@ public class B6373555 {
private static int port; private static int port;
private static volatile boolean error = false; private static volatile boolean error = false;
private static Object lock;
static HttpServer httpServer; static HttpServer httpServer;
static ExecutorService pool, execs; static ExecutorService pool, execs;
static int NUM = 1000; static int NUM = 1000;
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
try { try {
lock = new Object();
if (args.length > 0) { if (args.length > 0) {
NUM = Integer.parseInt (args[0]); NUM = Integer.parseInt (args[0]);
} }
...@@ -117,12 +115,6 @@ public class B6373555 { ...@@ -117,12 +115,6 @@ public class B6373555 {
System.out.println("Doesn't match"); System.out.println("Doesn't match");
error = true; error = true;
} }
synchronized(lock) {
++received;
if ((received % 1000) == 0) {
System.out.println("Received="+received);
}
}
} }
catch(Exception e) { catch(Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -150,18 +142,12 @@ public class B6373555 { ...@@ -150,18 +142,12 @@ public class B6373555 {
private static HttpServer createHttpServer(ExecutorService execs) private static HttpServer createHttpServer(ExecutorService execs)
throws Exception { throws Exception {
InetSocketAddress inetAddress = new InetSocketAddress(0); InetSocketAddress inetAddress = new InetSocketAddress(0);
HttpServer testServer = HttpServer.create(inetAddress, 5); HttpServer testServer = HttpServer.create(inetAddress, 15);
testServer.setExecutor(execs); testServer.setExecutor(execs);
HttpContext context = testServer.createContext("/test"); HttpContext context = testServer.createContext("/test");
context.setHandler(new HttpHandler() { context.setHandler(new HttpHandler() {
public void handle(HttpExchange msg) { public void handle(HttpExchange msg) {
try { try {
synchronized(lock) {
++s_received;
if ((s_received % 1000) == 0) {
System.out.println("Received="+s_received);
}
}
String method = msg.getRequestMethod(); String method = msg.getRequestMethod();
if (method.equals("POST")) { if (method.equals("POST")) {
InputStream is = msg.getRequestBody(); InputStream is = msg.getRequestBody();
...@@ -172,12 +158,6 @@ public class B6373555 { ...@@ -172,12 +158,6 @@ public class B6373555 {
System.out.println("****** METHOD not handled ***** "+method); System.out.println("****** METHOD not handled ***** "+method);
System.out.println("Received="+s_received); System.out.println("Received="+s_received);
} }
synchronized(lock) {
++sent;
if ((sent % 1000) == 0) {
System.out.println("sent="+sent);
}
}
} }
catch(Exception e) { catch(Exception e) {
e.printStackTrace(); e.printStackTrace();
......
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
# @summary (cl) ClassLoader.loadClass locks all instances in chain # @summary (cl) ClassLoader.loadClass locks all instances in chain
# when delegating # when delegating
# #
# @run shell/timeout=10 TestOneWayDelegate.sh # @run shell TestOneWayDelegate.sh
# if running by hand on windows, change TESTSRC and TESTCLASSES to "." # if running by hand on windows, change TESTSRC and TESTCLASSES to "."
if [ "${TESTSRC}" = "" ] ; then if [ "${TESTSRC}" = "" ] ; then
......
/* /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -34,21 +34,16 @@ ...@@ -34,21 +34,16 @@
*/ */
import java.util.concurrent.locks.LockSupport; import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.Semaphore; import java.util.concurrent.Phaser;
public class ThreadStateTest { public class ThreadStateTest {
// maximum number of retries when checking for thread state.
static final int MAX_RETRY = 500;
private static boolean testFailed = false; private static boolean testFailed = false;
static class Lock { // used to achieve waiting states
private String name; static final Object globalLock = new Object();
Lock(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
private static Lock globalLock = new Lock("my lock");
public static void main(String[] argv) { public static void main(String[] argv) {
// Call Thread.getState to force all initialization done // Call Thread.getState to force all initialization done
...@@ -102,13 +97,27 @@ public class ThreadStateTest { ...@@ -102,13 +97,27 @@ public class ThreadStateTest {
System.out.println("Unexpected exception."); System.out.println("Unexpected exception.");
testFailed = true; testFailed = true;
} }
if (testFailed) if (testFailed)
throw new RuntimeException("TEST FAILED."); throw new RuntimeException("TEST FAILED.");
System.out.println("Test passed."); System.out.println("Test passed.");
} }
private static void checkThreadState(Thread t, Thread.State expected) { private static void checkThreadState(Thread t, Thread.State expected) {
Thread.State state = t.getState(); // wait for the thread to transition to the expected state.
// There is a small window between the thread checking the state
// and the thread actual entering that state.
Thread.State state;
int retryCount=0;
while ((state = t.getState()) != expected && retryCount < MAX_RETRY) {
if (state != Thread.State.RUNNABLE) {
throw new RuntimeException("Thread not in expected state yet," +
" but it should at least be RUNNABLE");
}
goSleep(10);
retryCount++;
}
System.out.println("Checking thread state " + state); System.out.println("Checking thread state " + state);
if (state == null) { if (state == null) {
throw new RuntimeException(t.getName() + " expected to have " + throw new RuntimeException(t.getName() + " expected to have " +
...@@ -121,13 +130,6 @@ public class ThreadStateTest { ...@@ -121,13 +130,6 @@ public class ThreadStateTest {
} }
} }
private static String getLockName(Object lock) {
if (lock == null) return null;
return lock.getClass().getName() + '@' +
Integer.toHexString(System.identityHashCode(lock));
}
private static void goSleep(long ms) { private static void goSleep(long ms) {
try { try {
Thread.sleep(ms); Thread.sleep(ms);
...@@ -139,7 +141,9 @@ public class ThreadStateTest { ...@@ -139,7 +141,9 @@ public class ThreadStateTest {
} }
static class MyThread extends Thread { static class MyThread extends Thread {
private ThreadExecutionSynchronizer thrsync = new ThreadExecutionSynchronizer(); // Phaser to sync between the main thread putting
// this thread into various states
private Phaser phaser = new Phaser(2);
MyThread(String name) { MyThread(String name) {
super(name); super(name);
...@@ -153,12 +157,14 @@ public class ThreadStateTest { ...@@ -153,12 +157,14 @@ public class ThreadStateTest {
private final int TIMED_PARKED = 5; private final int TIMED_PARKED = 5;
private final int SLEEPING = 6; private final int SLEEPING = 6;
private final int TERMINATE = 7; private final int TERMINATE = 7;
private int state = RUNNABLE;
private volatile int state = RUNNABLE;
private boolean done = false; private boolean done = false;
public void run() { public void run() {
// Signal main thread to continue. // Signal main thread to continue.
thrsync.signal(); phaser.arriveAndAwaitAdvance();
while (!done) { while (!done) {
switch (state) { switch (state) {
case RUNNABLE: { case RUNNABLE: {
...@@ -172,7 +178,7 @@ public class ThreadStateTest { ...@@ -172,7 +178,7 @@ public class ThreadStateTest {
} }
case BLOCKED: { case BLOCKED: {
// signal main thread. // signal main thread.
thrsync.signal(); phaser.arrive();
System.out.println(" myThread is going to block."); System.out.println(" myThread is going to block.");
synchronized (globalLock) { synchronized (globalLock) {
// finish blocking // finish blocking
...@@ -183,7 +189,7 @@ public class ThreadStateTest { ...@@ -183,7 +189,7 @@ public class ThreadStateTest {
case WAITING: { case WAITING: {
synchronized (globalLock) { synchronized (globalLock) {
// signal main thread. // signal main thread.
thrsync.signal(); phaser.arrive();
System.out.println(" myThread is going to wait."); System.out.println(" myThread is going to wait.");
try { try {
globalLock.wait(); globalLock.wait();
...@@ -196,7 +202,7 @@ public class ThreadStateTest { ...@@ -196,7 +202,7 @@ public class ThreadStateTest {
case TIMED_WAITING: { case TIMED_WAITING: {
synchronized (globalLock) { synchronized (globalLock) {
// signal main thread. // signal main thread.
thrsync.signal(); phaser.arrive();
System.out.println(" myThread is going to timed wait."); System.out.println(" myThread is going to timed wait.");
try { try {
globalLock.wait(10000); globalLock.wait(10000);
...@@ -208,7 +214,7 @@ public class ThreadStateTest { ...@@ -208,7 +214,7 @@ public class ThreadStateTest {
} }
case PARKED: { case PARKED: {
// signal main thread. // signal main thread.
thrsync.signal(); phaser.arrive();
System.out.println(" myThread is going to park."); System.out.println(" myThread is going to park.");
LockSupport.park(); LockSupport.park();
// give a chance for the main thread to block // give a chance for the main thread to block
...@@ -217,7 +223,7 @@ public class ThreadStateTest { ...@@ -217,7 +223,7 @@ public class ThreadStateTest {
} }
case TIMED_PARKED: { case TIMED_PARKED: {
// signal main thread. // signal main thread.
thrsync.signal(); phaser.arrive();
System.out.println(" myThread is going to timed park."); System.out.println(" myThread is going to timed park.");
long deadline = System.currentTimeMillis() + 10000*1000; long deadline = System.currentTimeMillis() + 10000*1000;
LockSupport.parkUntil(deadline); LockSupport.parkUntil(deadline);
...@@ -228,20 +234,19 @@ public class ThreadStateTest { ...@@ -228,20 +234,19 @@ public class ThreadStateTest {
} }
case SLEEPING: { case SLEEPING: {
// signal main thread. // signal main thread.
thrsync.signal(); phaser.arrive();
System.out.println(" myThread is going to sleep."); System.out.println(" myThread is going to sleep.");
try { try {
Thread.sleep(1000000); Thread.sleep(1000000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// finish sleeping // finish sleeping
interrupted();
} }
break; break;
} }
case TERMINATE: { case TERMINATE: {
done = true; done = true;
// signal main thread. // signal main thread.
thrsync.signal(); phaser.arrive();
break; break;
} }
default: default:
...@@ -249,69 +254,66 @@ public class ThreadStateTest { ...@@ -249,69 +254,66 @@ public class ThreadStateTest {
} }
} }
} }
public void waitUntilStarted() { public void waitUntilStarted() {
// wait for MyThread. // wait for MyThread.
thrsync.waitForSignal(); phaser.arriveAndAwaitAdvance();
goSleep(10);
} }
public void goBlocked() { public void goBlocked() {
System.out.println("Waiting myThread to go blocked."); System.out.println("Waiting myThread to go blocked.");
setState(BLOCKED); setState(BLOCKED);
// wait for MyThread to get blocked // wait for MyThread to get to a point just before being blocked
thrsync.waitForSignal(); phaser.arriveAndAwaitAdvance();
goSleep(20);
} }
public void goWaiting() { public void goWaiting() {
System.out.println("Waiting myThread to go waiting."); System.out.println("Waiting myThread to go waiting.");
setState(WAITING); setState(WAITING);
// wait for MyThread to wait on object. // wait for MyThread to get to just before wait on object.
thrsync.waitForSignal(); phaser.arriveAndAwaitAdvance();
goSleep(20);
} }
public void goTimedWaiting() { public void goTimedWaiting() {
System.out.println("Waiting myThread to go timed waiting."); System.out.println("Waiting myThread to go timed waiting.");
setState(TIMED_WAITING); setState(TIMED_WAITING);
// wait for MyThread timed wait call. // wait for MyThread to get to just before timed wait call.
thrsync.waitForSignal(); phaser.arriveAndAwaitAdvance();
goSleep(20);
} }
public void goParked() { public void goParked() {
System.out.println("Waiting myThread to go parked."); System.out.println("Waiting myThread to go parked.");
setState(PARKED); setState(PARKED);
// wait for MyThread state change to PARKED. // wait for MyThread to get to just before parked.
thrsync.waitForSignal(); phaser.arriveAndAwaitAdvance();
goSleep(20);
} }
public void goTimedParked() { public void goTimedParked() {
System.out.println("Waiting myThread to go timed parked."); System.out.println("Waiting myThread to go timed parked.");
setState(TIMED_PARKED); setState(TIMED_PARKED);
// wait for MyThread. // wait for MyThread to get to just before timed park.
thrsync.waitForSignal(); phaser.arriveAndAwaitAdvance();
goSleep(20);
} }
public void goSleeping() { public void goSleeping() {
System.out.println("Waiting myThread to go sleeping."); System.out.println("Waiting myThread to go sleeping.");
setState(SLEEPING); setState(SLEEPING);
// wait for MyThread. // wait for MyThread to get to just before sleeping
thrsync.waitForSignal(); phaser.arriveAndAwaitAdvance();
goSleep(20);
} }
public void terminate() { public void terminate() {
System.out.println("Waiting myThread to terminate."); System.out.println("Waiting myThread to terminate.");
setState(TERMINATE); setState(TERMINATE);
// wait for MyThread. // wait for MyThread to get to just before terminate
thrsync.waitForSignal(); phaser.arriveAndAwaitAdvance();
goSleep(20);
} }
private void setState(int newState) { private void setState(int newState) {
switch (state) { switch (state) {
case BLOCKED: case BLOCKED:
while (state == BLOCKED) { while (state == BLOCKED) {
goSleep(20); goSleep(10);
} }
state = newState; state = newState;
break; break;
...@@ -337,50 +339,4 @@ public class ThreadStateTest { ...@@ -337,50 +339,4 @@ public class ThreadStateTest {
} }
} }
} }
static class ThreadExecutionSynchronizer {
private boolean waiting;
private Semaphore semaphore;
public ThreadExecutionSynchronizer() {
semaphore = new Semaphore(1);
waiting = false;
}
// Synchronizes two threads execution points.
// Basically any thread could get scheduled to run and
// it is not possible to know which thread reaches expected
// execution point. So whichever thread reaches a execution
// point first wait for the second thread. When the second thread
// reaches the expected execution point will wake up
// the thread which is waiting here.
void stopOrGo() {
semaphore.acquireUninterruptibly(); // Thread can get blocked.
if (!waiting) {
waiting = true;
// Wait for second thread to enter this method.
while(!semaphore.hasQueuedThreads()) {
try {
Thread.sleep(20);
} catch (InterruptedException xx) {}
}
semaphore.release();
} else {
waiting = false;
semaphore.release();
}
}
// Wrapper function just for code readability.
void waitForSignal() {
stopOrGo();
}
void signal() {
stopOrGo();
}
}
} }
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* 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 7021922
* @summary Test null handling of IncompleteAnnotationException constructor
* @author Joseph D. Darcy
*/
import java.lang.annotation.*;
public class TestIncompleteAnnotationExceptionNPE {
public static void main(String... args) {
int errors = 0;
Class<? extends Annotation> annotationType = Annotation.class;
String elementName = "name";
try {
Object o = new IncompleteAnnotationException(null, null);
errors++;
} catch(NullPointerException npe) {
; // Expected
}
try {
Object o = new IncompleteAnnotationException(annotationType, null);
errors++;
} catch(NullPointerException npe) {
; // Expected
}
try {
Object o = new IncompleteAnnotationException(null, elementName);
errors++;
} catch(NullPointerException npe) {
; // Expected
}
if (errors != 0)
throw new RuntimeException("Encountered " + errors +
" error(s) during construction.");
}
}
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
* @author Luis-Miguel Alventosa * @author Luis-Miguel Alventosa
* @run clean MBeanServerMXBeanUnsupportedTest * @run clean MBeanServerMXBeanUnsupportedTest
* @run build MBeanServerMXBeanUnsupportedTest * @run build MBeanServerMXBeanUnsupportedTest
* @run main MBeanServerMXBeanUnsupportedTest * @run main/othervm MBeanServerMXBeanUnsupportedTest
*/ */
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
......
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
/* @test /* @test
* @bug 4607272 6842687 6878369 6944810 7023403 * @bug 4607272 6842687 6878369 6944810 7023403
* @summary Unit test for AsynchronousSocketChannel * @summary Unit test for AsynchronousSocketChannel
* @run main/timeout=600 Basic * @run main Basic -skipSlowConnectTest
*/ */
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
...@@ -34,12 +34,25 @@ import java.net.*; ...@@ -34,12 +34,25 @@ import java.net.*;
import java.util.Random; import java.util.Random;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.atomic.*; import java.util.concurrent.atomic.*;
import java.io.Closeable;
import java.io.IOException; import java.io.IOException;
public class Basic { public class Basic {
static final Random rand = new Random(); static final Random rand = new Random();
static boolean skipSlowConnectTest = false;
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
for (String arg: args) {
switch (arg) {
case "-skipSlowConnectTest" :
skipSlowConnectTest = true;
break;
default:
throw new RuntimeException("Unrecognized argument: " + arg);
}
}
testBind(); testBind();
testSocketOptions(); testSocketOptions();
testConnect(); testConnect();
...@@ -54,7 +67,7 @@ public class Basic { ...@@ -54,7 +67,7 @@ public class Basic {
testShutdown(); testShutdown();
} }
static class Server { static class Server implements Closeable {
private final ServerSocketChannel ssc; private final ServerSocketChannel ssc;
private final InetSocketAddress address; private final InetSocketAddress address;
...@@ -74,10 +87,8 @@ public class Basic { ...@@ -74,10 +87,8 @@ public class Basic {
return ssc.accept(); return ssc.accept();
} }
void close() { public void close() throws IOException {
try { ssc.close();
ssc.close();
} catch (IOException ignore) { }
} }
} }
...@@ -85,28 +96,28 @@ public class Basic { ...@@ -85,28 +96,28 @@ public class Basic {
static void testBind() throws Exception { static void testBind() throws Exception {
System.out.println("-- bind --"); System.out.println("-- bind --");
AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(); try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {
if (ch.getLocalAddress() != null) if (ch.getLocalAddress() != null)
throw new RuntimeException("Local address should be 'null'"); throw new RuntimeException("Local address should be 'null'");
ch.bind(new InetSocketAddress(0));
// check local address after binding
InetSocketAddress local = (InetSocketAddress)ch.getLocalAddress();
if (local.getPort() == 0)
throw new RuntimeException("Unexpected port");
if (!local.getAddress().isAnyLocalAddress())
throw new RuntimeException("Not bound to a wildcard address");
// try to re-bind
try {
ch.bind(new InetSocketAddress(0)); ch.bind(new InetSocketAddress(0));
throw new RuntimeException("AlreadyBoundException expected");
} catch (AlreadyBoundException x) { // check local address after binding
InetSocketAddress local = (InetSocketAddress)ch.getLocalAddress();
if (local.getPort() == 0)
throw new RuntimeException("Unexpected port");
if (!local.getAddress().isAnyLocalAddress())
throw new RuntimeException("Not bound to a wildcard address");
// try to re-bind
try {
ch.bind(new InetSocketAddress(0));
throw new RuntimeException("AlreadyBoundException expected");
} catch (AlreadyBoundException x) {
}
} }
ch.close();
// check ClosedChannelException // check ClosedChannelException
ch = AsynchronousSocketChannel.open(); AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
ch.close(); ch.close();
try { try {
ch.bind(new InetSocketAddress(0)); ch.bind(new InetSocketAddress(0));
...@@ -118,109 +129,124 @@ public class Basic { ...@@ -118,109 +129,124 @@ public class Basic {
static void testSocketOptions() throws Exception { static void testSocketOptions() throws Exception {
System.out.println("-- socket options --"); System.out.println("-- socket options --");
AsynchronousSocketChannel ch = AsynchronousSocketChannel.open() try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {
.setOption(SO_RCVBUF, 128*1024) ch.setOption(SO_RCVBUF, 128*1024)
.setOption(SO_SNDBUF, 128*1024) .setOption(SO_SNDBUF, 128*1024)
.setOption(SO_REUSEADDR, true); .setOption(SO_REUSEADDR, true);
// check SO_SNDBUF/SO_RCVBUF limits // check SO_SNDBUF/SO_RCVBUF limits
int before, after; int before, after;
before = ch.getOption(SO_SNDBUF); before = ch.getOption(SO_SNDBUF);
after = ch.setOption(SO_SNDBUF, Integer.MAX_VALUE).getOption(SO_SNDBUF); after = ch.setOption(SO_SNDBUF, Integer.MAX_VALUE).getOption(SO_SNDBUF);
if (after < before) if (after < before)
throw new RuntimeException("setOption caused SO_SNDBUF to decrease"); throw new RuntimeException("setOption caused SO_SNDBUF to decrease");
before = ch.getOption(SO_RCVBUF); before = ch.getOption(SO_RCVBUF);
after = ch.setOption(SO_RCVBUF, Integer.MAX_VALUE).getOption(SO_RCVBUF); after = ch.setOption(SO_RCVBUF, Integer.MAX_VALUE).getOption(SO_RCVBUF);
if (after < before) if (after < before)
throw new RuntimeException("setOption caused SO_RCVBUF to decrease"); throw new RuntimeException("setOption caused SO_RCVBUF to decrease");
ch.bind(new InetSocketAddress(0));
// default values
if ((Boolean)ch.getOption(SO_KEEPALIVE))
throw new RuntimeException("Default of SO_KEEPALIVE should be 'false'");
if ((Boolean)ch.getOption(TCP_NODELAY))
throw new RuntimeException("Default of TCP_NODELAY should be 'false'");
// set and check
if (!(Boolean)ch.setOption(SO_KEEPALIVE, true).getOption(SO_KEEPALIVE))
throw new RuntimeException("SO_KEEPALIVE did not change");
if (!(Boolean)ch.setOption(TCP_NODELAY, true).getOption(TCP_NODELAY))
throw new RuntimeException("SO_KEEPALIVE did not change");
// read others (can't check as actual value is implementation dependent)
ch.getOption(SO_RCVBUF);
ch.getOption(SO_SNDBUF);
ch.close(); ch.bind(new InetSocketAddress(0));
// default values
if (ch.getOption(SO_KEEPALIVE))
throw new RuntimeException("Default of SO_KEEPALIVE should be 'false'");
if (ch.getOption(TCP_NODELAY))
throw new RuntimeException("Default of TCP_NODELAY should be 'false'");
// set and check
if (!ch.setOption(SO_KEEPALIVE, true).getOption(SO_KEEPALIVE))
throw new RuntimeException("SO_KEEPALIVE did not change");
if (!ch.setOption(TCP_NODELAY, true).getOption(TCP_NODELAY))
throw new RuntimeException("SO_KEEPALIVE did not change");
// read others (can't check as actual value is implementation dependent)
ch.getOption(SO_RCVBUF);
ch.getOption(SO_SNDBUF);
}
} }
static void testConnect() throws Exception { static void testConnect() throws Exception {
System.out.println("-- connect --"); System.out.println("-- connect --");
Server server = new Server(); SocketAddress address;
AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
ch.connect(server.address()).get(); try (Server server = new Server()) {
address = server.address();
// check local address
if (ch.getLocalAddress() == null) // connect to server and check local/remote addresses
throw new RuntimeException("Not bound to local address"); try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {
ch.connect(address).get();
// check remote address // check local address
InetSocketAddress remote = (InetSocketAddress)ch.getRemoteAddress(); if (ch.getLocalAddress() == null)
if (remote.getPort() != server.address().getPort()) throw new RuntimeException("Not bound to local address");
throw new RuntimeException("Connected to unexpected port");
if (!remote.getAddress().equals(server.address().getAddress())) // check remote address
throw new RuntimeException("Connected to unexpected address"); InetSocketAddress remote = (InetSocketAddress)ch.getRemoteAddress();
if (remote.getPort() != server.address().getPort())
throw new RuntimeException("Connected to unexpected port");
if (!remote.getAddress().equals(server.address().getAddress()))
throw new RuntimeException("Connected to unexpected address");
// try to connect again
try {
ch.connect(server.address()).get();
throw new RuntimeException("AlreadyConnectedException expected");
} catch (AlreadyConnectedException x) {
}
// try to connect again // clean-up
try { server.accept().close();
ch.connect(server.address()).get(); }
throw new RuntimeException("AlreadyConnectedException expected");
} catch (AlreadyConnectedException x) {
}
ch.close();
// check that connect fails with ClosedChannelException) // check that connect fails with ClosedChannelException
ch = AsynchronousSocketChannel.open(); AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
ch.close(); ch.close();
try { try {
ch.connect(server.address()).get(); ch.connect(server.address()).get();
throw new RuntimeException("ExecutionException expected"); throw new RuntimeException("ExecutionException expected");
} catch (ExecutionException x) { } catch (ExecutionException x) {
if (!(x.getCause() instanceof ClosedChannelException)) if (!(x.getCause() instanceof ClosedChannelException))
throw new RuntimeException("Cause of ClosedChannelException expected"); throw new RuntimeException("Cause of ClosedChannelException expected");
}
final AtomicReference<Throwable> connectException =
new AtomicReference<Throwable>();
ch.connect(server.address(), (Void)null, new CompletionHandler<Void,Void>() {
public void completed(Void result, Void att) {
} }
public void failed(Throwable exc, Void att) { final AtomicReference<Throwable> connectException = new AtomicReference<>();
connectException.set(exc); ch.connect(server.address(), (Void)null, new CompletionHandler<Void,Void>() {
public void completed(Void result, Void att) {
}
public void failed(Throwable exc, Void att) {
connectException.set(exc);
}
});
while (connectException.get() == null) {
Thread.sleep(100);
} }
}); if (!(connectException.get() instanceof ClosedChannelException))
while (connectException.get() == null) { throw new RuntimeException("ClosedChannelException expected");
Thread.sleep(100);
} }
if (!(connectException.get() instanceof ClosedChannelException))
throw new RuntimeException("ClosedChannelException expected");
System.out.println("-- connect to non-existent host --");
// test that failure to connect closes the channel // test that failure to connect closes the channel
ch = AsynchronousSocketChannel.open(); try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {
try { try {
ch.connect(genSocketAddress()).get(); ch.connect(address).get();
} catch (ExecutionException x) { } catch (ExecutionException x) {
// failed to establish connection // failed to establish connection
if (ch.isOpen()) if (ch.isOpen())
throw new RuntimeException("Channel should be closed"); throw new RuntimeException("Channel should be closed");
} finally { }
ch.close();
} }
server.close(); // repeat test by connecting to a (probably) non-existent host. This
// improves the chance that the connect will not fail immediately.
if (!skipSlowConnectTest) {
try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {
try {
ch.connect(genSocketAddress()).get();
} catch (ExecutionException x) {
// failed to establish connection
if (ch.isOpen())
throw new RuntimeException("Channel should be closed");
}
}
}
} }
static void testCloseWhenPending() throws Exception { static void testCloseWhenPending() throws Exception {
...@@ -249,466 +275,460 @@ public class Basic { ...@@ -249,466 +275,460 @@ public class Basic {
System.out.println("-- asynchronous close when reading --"); System.out.println("-- asynchronous close when reading --");
Server server = new Server(); try (Server server = new Server()) {
ch = AsynchronousSocketChannel.open(); ch = AsynchronousSocketChannel.open();
ch.connect(server.address()).get(); ch.connect(server.address()).get();
ByteBuffer dst = ByteBuffer.allocateDirect(100); ByteBuffer dst = ByteBuffer.allocateDirect(100);
Future<Integer> result = ch.read(dst); Future<Integer> result = ch.read(dst);
// attempt a second read - should fail with ReadPendingException // attempt a second read - should fail with ReadPendingException
ByteBuffer buf = ByteBuffer.allocateDirect(100); ByteBuffer buf = ByteBuffer.allocateDirect(100);
try { try {
ch.read(buf); ch.read(buf);
throw new RuntimeException("ReadPendingException expected"); throw new RuntimeException("ReadPendingException expected");
} catch (ReadPendingException x) { } catch (ReadPendingException x) {
} }
// close channel (should cause initial read to complete) // close channel (should cause initial read to complete)
ch.close(); ch.close();
server.accept().close();
// check that AsynchronousCloseException is thrown // check that AsynchronousCloseException is thrown
try { try {
result.get(); result.get();
throw new RuntimeException("Should not read"); throw new RuntimeException("Should not read");
} catch (ExecutionException x) { } catch (ExecutionException x) {
if (!(x.getCause() instanceof AsynchronousCloseException)) if (!(x.getCause() instanceof AsynchronousCloseException))
throw new RuntimeException(x); throw new RuntimeException(x);
} }
System.out.println("-- asynchronous close when writing --"); System.out.println("-- asynchronous close when writing --");
ch = AsynchronousSocketChannel.open(); ch = AsynchronousSocketChannel.open();
ch.connect(server.address()).get(); ch.connect(server.address()).get();
final AtomicReference<Throwable> writeException = final AtomicReference<Throwable> writeException =
new AtomicReference<Throwable>(); new AtomicReference<Throwable>();
// write bytes to fill socket buffer // write bytes to fill socket buffer
ch.write(genBuffer(), ch, new CompletionHandler<Integer,AsynchronousSocketChannel>() { ch.write(genBuffer(), ch, new CompletionHandler<Integer,AsynchronousSocketChannel>() {
public void completed(Integer result, AsynchronousSocketChannel ch) { public void completed(Integer result, AsynchronousSocketChannel ch) {
ch.write(genBuffer(), ch, this); ch.write(genBuffer(), ch, this);
} }
public void failed(Throwable x, AsynchronousSocketChannel ch) { public void failed(Throwable x, AsynchronousSocketChannel ch) {
writeException.set(x); writeException.set(x);
} }
}); });
// give time for socket buffer to fill up. // give time for socket buffer to fill up.
Thread.sleep(5*1000); Thread.sleep(5*1000);
// attempt a concurrent write - should fail with WritePendingException // attempt a concurrent write - should fail with WritePendingException
try { try {
ch.write(genBuffer()); ch.write(genBuffer());
throw new RuntimeException("WritePendingException expected"); throw new RuntimeException("WritePendingException expected");
} catch (WritePendingException x) { } catch (WritePendingException x) {
} }
// close channel - should cause initial write to complete // close channel - should cause initial write to complete
ch.close(); ch.close();
server.accept().close();
// wait for exception // wait for exception
while (writeException.get() == null) { while (writeException.get() == null) {
Thread.sleep(100); Thread.sleep(100);
}
if (!(writeException.get() instanceof AsynchronousCloseException))
throw new RuntimeException("AsynchronousCloseException expected");
} }
if (!(writeException.get() instanceof AsynchronousCloseException))
throw new RuntimeException("AsynchronousCloseException expected");
server.close();
} }
static void testCancel() throws Exception { static void testCancel() throws Exception {
System.out.println("-- cancel --"); System.out.println("-- cancel --");
Server server = new Server(); try (Server server = new Server()) {
for (int i=0; i<2; i++) {
for (int i=0; i<2; i++) { boolean mayInterruptIfRunning = (i == 0) ? false : true;
boolean mayInterruptIfRunning = (i == 0) ? false : true;
// establish loopback connection
// establish loopback connection AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(); ch.connect(server.address()).get();
ch.connect(server.address()).get(); SocketChannel peer = server.accept();
SocketChannel peer = server.accept();
// start read operation
// start read operation ByteBuffer buf = ByteBuffer.allocate(1);
ByteBuffer buf = ByteBuffer.allocate(1); Future<Integer> res = ch.read(buf);
Future<Integer> res = ch.read(buf);
// cancel operation
// cancel operation boolean cancelled = res.cancel(mayInterruptIfRunning);
boolean cancelled = res.cancel(mayInterruptIfRunning);
// check post-conditions
if (!res.isDone())
throw new RuntimeException("isDone should return true");
if (res.isCancelled() != cancelled)
throw new RuntimeException("isCancelled not consistent");
try {
res.get();
throw new RuntimeException("CancellationException expected");
} catch (CancellationException x) {
}
try {
res.get(1, TimeUnit.SECONDS);
throw new RuntimeException("CancellationException expected");
} catch (CancellationException x) {
}
// check post-conditions // check that the cancel doesn't impact writing to the channel
if (!res.isDone()) if (!mayInterruptIfRunning) {
throw new RuntimeException("isDone should return true"); buf = ByteBuffer.wrap("a".getBytes());
if (res.isCancelled() != cancelled) ch.write(buf).get();
throw new RuntimeException("isCancelled not consistent"); }
try {
res.get();
throw new RuntimeException("CancellationException expected");
} catch (CancellationException x) {
}
try {
res.get(1, TimeUnit.SECONDS);
throw new RuntimeException("CancellationException expected");
} catch (CancellationException x) {
}
// check that the cancel doesn't impact writing to the channel ch.close();
if (!mayInterruptIfRunning) { peer.close();
buf = ByteBuffer.wrap("a".getBytes());
ch.write(buf).get();
} }
ch.close();
peer.close();
} }
server.close();
} }
static void testRead1() throws Exception { static void testRead1() throws Exception {
System.out.println("-- read (1) --"); System.out.println("-- read (1) --");
Server server = new Server(); try (Server server = new Server()) {
final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(); final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
ch.connect(server.address()).get(); ch.connect(server.address()).get();
// read with 0 bytes remaining should complete immediately // read with 0 bytes remaining should complete immediately
ByteBuffer buf = ByteBuffer.allocate(1); ByteBuffer buf = ByteBuffer.allocate(1);
buf.put((byte)0); buf.put((byte)0);
int n = ch.read(buf).get(); int n = ch.read(buf).get();
if (n != 0) if (n != 0)
throw new RuntimeException("0 expected"); throw new RuntimeException("0 expected");
// write bytes and close connection // write bytes and close connection
SocketChannel sc = server.accept(); ByteBuffer src = genBuffer();
ByteBuffer src = genBuffer(); try (SocketChannel sc = server.accept()) {
sc.setOption(StandardSocketOptions.SO_SNDBUF, src.remaining()); sc.setOption(SO_SNDBUF, src.remaining());
while (src.hasRemaining()) while (src.hasRemaining())
sc.write(src); sc.write(src);
sc.close();
// reads should complete immediately
final ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity() + 100);
final CountDownLatch latch = new CountDownLatch(1);
ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer result, Void att) {
int n = result;
if (n > 0) {
ch.read(dst, (Void)null, this);
} else {
latch.countDown();
}
}
public void failed(Throwable exc, Void att) {
} }
});
latch.await(); // reads should complete immediately
final ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity() + 100);
final CountDownLatch latch = new CountDownLatch(1);
ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer result, Void att) {
int n = result;
if (n > 0) {
ch.read(dst, (Void)null, this);
} else {
latch.countDown();
}
}
public void failed(Throwable exc, Void att) {
}
});
// check buffers latch.await();
src.flip();
dst.flip();
if (!src.equals(dst)) {
throw new RuntimeException("Contents differ");
}
// close channel // check buffers
ch.close(); src.flip();
dst.flip();
if (!src.equals(dst)) {
throw new RuntimeException("Contents differ");
}
// check read fails with ClosedChannelException // close channel
try { ch.close();
ch.read(dst).get();
throw new RuntimeException("ExecutionException expected");
} catch (ExecutionException x) {
if (!(x.getCause() instanceof ClosedChannelException))
throw new RuntimeException("Cause of ClosedChannelException expected");
}
server.close(); // check read fails with ClosedChannelException
try {
ch.read(dst).get();
throw new RuntimeException("ExecutionException expected");
} catch (ExecutionException x) {
if (!(x.getCause() instanceof ClosedChannelException))
throw new RuntimeException("Cause of ClosedChannelException expected");
}
}
} }
static void testRead2() throws Exception { static void testRead2() throws Exception {
System.out.println("-- read (2) --"); System.out.println("-- read (2) --");
Server server = new Server(); try (Server server = new Server()) {
final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(); ch.connect(server.address()).get();
ch.connect(server.address()).get(); SocketChannel sc = server.accept();
SocketChannel sc = server.accept();
ByteBuffer src = genBuffer();
ByteBuffer src = genBuffer();
// read until the buffer is full
// read until the buffer is full final ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity());
final ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity()); final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch latch = new CountDownLatch(1); ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() {
ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() { public void completed(Integer result, Void att) {
public void completed(Integer result, Void att) { if (dst.hasRemaining()) {
if (dst.hasRemaining()) { ch.read(dst, (Void)null, this);
ch.read(dst, (Void)null, this); } else {
} else { latch.countDown();
latch.countDown(); }
} }
public void failed(Throwable exc, Void att) {
}
});
// trickle the writing
do {
int rem = src.remaining();
int size = (rem <= 100) ? rem : 50 + rand.nextInt(rem - 100);
ByteBuffer buf = ByteBuffer.allocate(size);
for (int i=0; i<size; i++)
buf.put(src.get());
buf.flip();
Thread.sleep(50 + rand.nextInt(1500));
while (buf.hasRemaining())
sc.write(buf);
} while (src.hasRemaining());
// wait until ascynrhonous reading has completed
latch.await();
// check buffers
src.flip();
dst.flip();
if (!src.equals(dst)) {
throw new RuntimeException("Contents differ");
} }
public void failed(Throwable exc, Void att) {
}
});
// trickle the writing
do {
int rem = src.remaining();
int size = (rem <= 100) ? rem : 50 + rand.nextInt(rem - 100);
ByteBuffer buf = ByteBuffer.allocate(size);
for (int i=0; i<size; i++)
buf.put(src.get());
buf.flip();
Thread.sleep(50 + rand.nextInt(1500));
while (buf.hasRemaining())
sc.write(buf);
} while (src.hasRemaining());
// wait until ascynrhonous reading has completed
latch.await();
// check buffers
src.flip();
dst.flip();
if (!src.equals(dst)) {
throw new RuntimeException("Contents differ");
}
sc.close(); sc.close();
ch.close(); ch.close();
server.close(); }
} }
// exercise scattering read // exercise scattering read
static void testRead3() throws Exception { static void testRead3() throws Exception {
System.out.println("-- read (3) --"); System.out.println("-- read (3) --");
Server server = new Server(); try (Server server = new Server()) {
final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(); final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
ch.connect(server.address()).get(); ch.connect(server.address()).get();
SocketChannel sc = server.accept(); SocketChannel sc = server.accept();
ByteBuffer[] dsts = new ByteBuffer[3]; ByteBuffer[] dsts = new ByteBuffer[3];
for (int i=0; i<dsts.length; i++) { for (int i=0; i<dsts.length; i++) {
dsts[i] = ByteBuffer.allocateDirect(100); dsts[i] = ByteBuffer.allocateDirect(100);
} }
// scattering read that completes ascynhronously // scattering read that completes ascynhronously
final CountDownLatch l1 = new CountDownLatch(1); final CountDownLatch l1 = new CountDownLatch(1);
ch.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, (Void)null, ch.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, (Void)null,
new CompletionHandler<Long,Void>() { new CompletionHandler<Long,Void>() {
public void completed(Long result, Void att) { public void completed(Long result, Void att) {
long n = result; long n = result;
if (n <= 0) if (n <= 0)
throw new RuntimeException("No bytes read"); throw new RuntimeException("No bytes read");
l1.countDown(); l1.countDown();
} }
public void failed(Throwable exc, Void att) { public void failed(Throwable exc, Void att) {
} }
}); });
// write some bytes // write some bytes
sc.write(genBuffer()); sc.write(genBuffer());
// read should now complete // read should now complete
l1.await(); l1.await();
// write more bytes // write more bytes
sc.write(genBuffer()); sc.write(genBuffer());
// read should complete immediately // read should complete immediately
for (int i=0; i<dsts.length; i++) { for (int i=0; i<dsts.length; i++) {
dsts[i].rewind(); dsts[i].rewind();
} }
final CountDownLatch l2 = new CountDownLatch(1); final CountDownLatch l2 = new CountDownLatch(1);
ch.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, (Void)null, ch.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, (Void)null,
new CompletionHandler<Long,Void>() { new CompletionHandler<Long,Void>() {
public void completed(Long result, Void att) { public void completed(Long result, Void att) {
long n = result; long n = result;
if (n <= 0) if (n <= 0)
throw new RuntimeException("No bytes read"); throw new RuntimeException("No bytes read");
l2.countDown(); l2.countDown();
} }
public void failed(Throwable exc, Void att) { public void failed(Throwable exc, Void att) {
} }
}); });
l2.await(); l2.await();
ch.close(); ch.close();
sc.close(); sc.close();
server.close(); }
} }
static void testWrite1() throws Exception { static void testWrite1() throws Exception {
System.out.println("-- write (1) --"); System.out.println("-- write (1) --");
Server server = new Server(); try (Server server = new Server()) {
final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(); final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
ch.connect(server.address()).get(); ch.connect(server.address()).get();
SocketChannel sc = server.accept(); SocketChannel sc = server.accept();
// write with 0 bytes remaining should complete immediately // write with 0 bytes remaining should complete immediately
ByteBuffer buf = ByteBuffer.allocate(1); ByteBuffer buf = ByteBuffer.allocate(1);
buf.put((byte)0); buf.put((byte)0);
int n = ch.write(buf).get(); int n = ch.write(buf).get();
if (n != 0) if (n != 0)
throw new RuntimeException("0 expected"); throw new RuntimeException("0 expected");
// write all bytes and close connection when done // write all bytes and close connection when done
final ByteBuffer src = genBuffer(); final ByteBuffer src = genBuffer();
ch.write(src, (Void)null, new CompletionHandler<Integer,Void>() { ch.write(src, (Void)null, new CompletionHandler<Integer,Void>() {
public void completed(Integer result, Void att) { public void completed(Integer result, Void att) {
if (src.hasRemaining()) { if (src.hasRemaining()) {
ch.write(src, (Void)null, this); ch.write(src, (Void)null, this);
} else { } else {
try { try {
ch.close(); ch.close();
} catch (IOException ignore) { } } catch (IOException ignore) { }
}
} }
public void failed(Throwable exc, Void att) {
}
});
// read to EOF or buffer full
ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity() + 100);
do {
n = sc.read(dst);
} while (n > 0);
sc.close();
// check buffers
src.flip();
dst.flip();
if (!src.equals(dst)) {
throw new RuntimeException("Contents differ");
} }
public void failed(Throwable exc, Void att) {
}
});
// read to EOF or buffer full
ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity() + 100);
do {
n = sc.read(dst);
} while (n > 0);
sc.close();
// check buffers
src.flip();
dst.flip();
if (!src.equals(dst)) {
throw new RuntimeException("Contents differ");
}
// check write fails with ClosedChannelException // check write fails with ClosedChannelException
try { try {
ch.read(dst).get(); ch.read(dst).get();
throw new RuntimeException("ExecutionException expected"); throw new RuntimeException("ExecutionException expected");
} catch (ExecutionException x) { } catch (ExecutionException x) {
if (!(x.getCause() instanceof ClosedChannelException)) if (!(x.getCause() instanceof ClosedChannelException))
throw new RuntimeException("Cause of ClosedChannelException expected"); throw new RuntimeException("Cause of ClosedChannelException expected");
}
} }
server.close();
} }
// exercise gathering write // exercise gathering write
static void testWrite2() throws Exception { static void testWrite2() throws Exception {
System.out.println("-- write (2) --"); System.out.println("-- write (2) --");
Server server = new Server(); try (Server server = new Server()) {
final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(); final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
ch.connect(server.address()).get(); ch.connect(server.address()).get();
SocketChannel sc = server.accept(); SocketChannel sc = server.accept();
// number of bytes written // number of bytes written
final AtomicLong bytesWritten = new AtomicLong(0); final AtomicLong bytesWritten = new AtomicLong(0);
// write buffers (should complete immediately) // write buffers (should complete immediately)
ByteBuffer[] srcs = genBuffers(1); ByteBuffer[] srcs = genBuffers(1);
final CountDownLatch l1 = new CountDownLatch(1); final CountDownLatch l1 = new CountDownLatch(1);
ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, (Void)null, ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, (Void)null,
new CompletionHandler<Long,Void>() { new CompletionHandler<Long,Void>() {
public void completed(Long result, Void att) { public void completed(Long result, Void att) {
long n = result; long n = result;
if (n <= 0) if (n <= 0)
throw new RuntimeException("No bytes read"); throw new RuntimeException("No bytes read");
bytesWritten.addAndGet(n); bytesWritten.addAndGet(n);
l1.countDown(); l1.countDown();
}
public void failed(Throwable exc, Void att) {
}
});
l1.await();
// set to true to signal that no more buffers should be written
final AtomicBoolean continueWriting = new AtomicBoolean(true);
// write until socket buffer is full so as to create the conditions
// for when a write does not complete immediately
srcs = genBuffers(1);
ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, (Void)null,
new CompletionHandler<Long,Void>() {
public void completed(Long result, Void att) {
long n = result;
if (n <= 0)
throw new RuntimeException("No bytes written");
bytesWritten.addAndGet(n);
if (continueWriting.get()) {
ByteBuffer[] srcs = genBuffers(8);
ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS,
(Void)null, this);
} }
} public void failed(Throwable exc, Void att) {
public void failed(Throwable exc, Void att) { }
} });
}); l1.await();
// set to true to signal that no more buffers should be written
final AtomicBoolean continueWriting = new AtomicBoolean(true);
// write until socket buffer is full so as to create the conditions
// for when a write does not complete immediately
srcs = genBuffers(1);
ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, (Void)null,
new CompletionHandler<Long,Void>() {
public void completed(Long result, Void att) {
long n = result;
if (n <= 0)
throw new RuntimeException("No bytes written");
bytesWritten.addAndGet(n);
if (continueWriting.get()) {
ByteBuffer[] srcs = genBuffers(8);
ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS,
(Void)null, this);
}
}
public void failed(Throwable exc, Void att) {
}
});
// give time for socket buffer to fill up. // give time for socket buffer to fill up.
Thread.sleep(5*1000); Thread.sleep(5*1000);
// signal handler to stop further writing // signal handler to stop further writing
continueWriting.set(false); continueWriting.set(false);
// read until done // read until done
ByteBuffer buf = ByteBuffer.allocateDirect(4096); ByteBuffer buf = ByteBuffer.allocateDirect(4096);
long total = 0L; long total = 0L;
do { do {
int n = sc.read(buf); int n = sc.read(buf);
if (n <= 0) if (n <= 0)
throw new RuntimeException("No bytes read"); throw new RuntimeException("No bytes read");
buf.rewind(); buf.rewind();
total += n; total += n;
} while (total < bytesWritten.get()); } while (total < bytesWritten.get());
ch.close(); ch.close();
sc.close(); sc.close();
server.close(); }
} }
static void testShutdown() throws Exception { static void testShutdown() throws Exception {
System.out.println("-- shutdown--"); System.out.println("-- shutdown--");
Server server = new Server(); try (Server server = new Server();
AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(); AsynchronousSocketChannel ch = AsynchronousSocketChannel.open())
ch.connect(server.address()).get(); {
SocketChannel sc = server.accept(); ch.connect(server.address()).get();
try (SocketChannel peer = server.accept()) {
ByteBuffer buf = ByteBuffer.allocateDirect(1000); ByteBuffer buf = ByteBuffer.allocateDirect(1000);
int n; int n;
// check read // check read
ch.shutdownInput(); ch.shutdownInput();
n = ch.read(buf).get(); n = ch.read(buf).get();
if (n != -1) if (n != -1)
throw new RuntimeException("-1 expected"); throw new RuntimeException("-1 expected");
// check full with full buffer // check full with full buffer
buf.put(new byte[100]); buf.put(new byte[100]);
n = ch.read(buf).get(); n = ch.read(buf).get();
if (n != -1) if (n != -1)
throw new RuntimeException("-1 expected"); throw new RuntimeException("-1 expected");
// check write // check write
ch.shutdownOutput(); ch.shutdownOutput();
try { try {
ch.write(buf).get(); ch.write(buf).get();
throw new RuntimeException("ClosedChannelException expected"); throw new RuntimeException("ClosedChannelException expected");
} catch (ExecutionException x) { } catch (ExecutionException x) {
if (!(x.getCause() instanceof ClosedChannelException)) if (!(x.getCause() instanceof ClosedChannelException))
throw new RuntimeException("ClosedChannelException expected"); throw new RuntimeException("ClosedChannelException expected");
}
}
} }
sc.close();
ch.close();
server.close();
} }
static void testTimeout() throws Exception { static void testTimeout() throws Exception {
...@@ -720,88 +740,88 @@ public class Basic { ...@@ -720,88 +740,88 @@ public class Basic {
} }
static void testTimeout(final long timeout, final TimeUnit unit) throws Exception { static void testTimeout(final long timeout, final TimeUnit unit) throws Exception {
Server server = new Server(); try (Server server = new Server()) {
AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(); AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
ch.connect(server.address()).get(); ch.connect(server.address()).get();
ByteBuffer dst = ByteBuffer.allocate(512);
final AtomicReference<Throwable> readException = new AtomicReference<Throwable>(); ByteBuffer dst = ByteBuffer.allocate(512);
// this read should timeout if value is > 0 final AtomicReference<Throwable> readException = new AtomicReference<Throwable>();
ch.read(dst, timeout, unit, null, new CompletionHandler<Integer,Void>() {
public void completed(Integer result, Void att) {
readException.set(new RuntimeException("Should not complete"));
}
public void failed(Throwable exc, Void att) {
readException.set(exc);
}
});
if (timeout > 0L) {
// wait for exception
while (readException.get() == null) {
Thread.sleep(100);
}
if (!(readException.get() instanceof InterruptedByTimeoutException))
throw new RuntimeException("InterruptedByTimeoutException expected");
// after a timeout then further reading should throw unspecified runtime exception // this read should timeout if value is > 0
boolean exceptionThrown = false; ch.read(dst, timeout, unit, null, new CompletionHandler<Integer,Void>() {
try { public void completed(Integer result, Void att) {
ch.read(dst); readException.set(new RuntimeException("Should not complete"));
} catch (RuntimeException x) { }
exceptionThrown = true; public void failed(Throwable exc, Void att) {
readException.set(exc);
}
});
if (timeout > 0L) {
// wait for exception
while (readException.get() == null) {
Thread.sleep(100);
}
if (!(readException.get() instanceof InterruptedByTimeoutException))
throw new RuntimeException("InterruptedByTimeoutException expected");
// after a timeout then further reading should throw unspecified runtime exception
boolean exceptionThrown = false;
try {
ch.read(dst);
} catch (RuntimeException x) {
exceptionThrown = true;
}
if (!exceptionThrown)
throw new RuntimeException("RuntimeException expected after timeout.");
} else {
Thread.sleep(1000);
Throwable exc = readException.get();
if (exc != null)
throw new RuntimeException(exc);
} }
if (!exceptionThrown)
throw new RuntimeException("RuntimeException expected after timeout.");
} else {
Thread.sleep(1000);
Throwable exc = readException.get();
if (exc != null)
throw new RuntimeException(exc);
}
final AtomicReference<Throwable> writeException = new AtomicReference<Throwable>(); final AtomicReference<Throwable> writeException = new AtomicReference<Throwable>();
// write bytes to fill socket buffer // write bytes to fill socket buffer
ch.write(genBuffer(), timeout, unit, ch, ch.write(genBuffer(), timeout, unit, ch,
new CompletionHandler<Integer,AsynchronousSocketChannel>() new CompletionHandler<Integer,AsynchronousSocketChannel>()
{ {
public void completed(Integer result, AsynchronousSocketChannel ch) { public void completed(Integer result, AsynchronousSocketChannel ch) {
ch.write(genBuffer(), timeout, unit, ch, this); ch.write(genBuffer(), timeout, unit, ch, this);
} }
public void failed(Throwable exc, AsynchronousSocketChannel ch) { public void failed(Throwable exc, AsynchronousSocketChannel ch) {
writeException.set(exc); writeException.set(exc);
} }
}); });
if (timeout > 0) { if (timeout > 0) {
// wait for exception // wait for exception
while (writeException.get() == null) { while (writeException.get() == null) {
Thread.sleep(100); Thread.sleep(100);
}
if (!(writeException.get() instanceof InterruptedByTimeoutException))
throw new RuntimeException("InterruptedByTimeoutException expected");
// after a timeout then further writing should throw unspecified runtime exception
boolean exceptionThrown = false;
try {
ch.write(genBuffer());
} catch (RuntimeException x) {
exceptionThrown = true;
}
if (!exceptionThrown)
throw new RuntimeException("RuntimeException expected after timeout.");
} else {
Thread.sleep(1000);
Throwable exc = writeException.get();
if (exc != null)
throw new RuntimeException(exc);
} }
if (!(writeException.get() instanceof InterruptedByTimeoutException))
throw new RuntimeException("InterruptedByTimeoutException expected");
// after a timeout then further writing should throw unspecified runtime exception // clean-up
boolean exceptionThrown = false; server.accept().close();
try { ch.close();
ch.write(genBuffer());
} catch (RuntimeException x) {
exceptionThrown = true;
}
if (!exceptionThrown)
throw new RuntimeException("RuntimeException expected after timeout.");
} else {
Thread.sleep(1000);
Throwable exc = writeException.get();
if (exc != null)
throw new RuntimeException(exc);
} }
// clean-up
server.accept().close();
ch.close();
server.close();
} }
// returns ByteBuffer with random bytes // returns ByteBuffer with random bytes
......
/* /*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
/* /*
* @test * @test
* @bug 4511601 * @bug 4511601 7054918
* @summary BasicPermissionCollection does not set permClass * @summary BasicPermissionCollection does not set permClass
* during deserialization * during deserialization
*/ */
...@@ -55,59 +55,66 @@ public class PermClass { ...@@ -55,59 +55,66 @@ public class PermClass {
// read in a 1.2.1 BasicPermissionCollection // read in a 1.2.1 BasicPermissionCollection
File sFile = new File(dir, "PermClass.1.2.1"); File sFile = new File(dir, "PermClass.1.2.1");
ObjectInputStream ois = new ObjectInputStream try (FileInputStream fis = new FileInputStream(sFile);
(new FileInputStream(sFile)); ObjectInputStream ois = new ObjectInputStream(fis)) {
PermissionCollection pc = (PermissionCollection)ois.readObject(); PermissionCollection pc = (PermissionCollection)ois.readObject();
System.out.println("1.2.1 collection = " + pc); System.out.println("1.2.1 collection = " + pc);
if (pc.implies(mp)) { if (pc.implies(mp)) {
System.out.println("JDK 1.2.1 test passed"); System.out.println("JDK 1.2.1 test passed");
} else { } else {
throw new Exception("JDK 1.2.1 test failed"); throw new Exception("JDK 1.2.1 test failed");
}
} }
// read in a 1.3.1 BasicPermissionCollection // read in a 1.3.1 BasicPermissionCollection
sFile = new File(dir, "PermClass.1.3.1"); sFile = new File(dir, "PermClass.1.3.1");
ois = new ObjectInputStream(new FileInputStream(sFile)); try (FileInputStream fis = new FileInputStream(sFile);
pc = (PermissionCollection)ois.readObject(); ObjectInputStream ois = new ObjectInputStream(fis)) {
System.out.println("1.3.1 collection = " + pc); PermissionCollection pc = (PermissionCollection)ois.readObject();
System.out.println("1.3.1 collection = " + pc);
if (pc.implies(mp)) {
System.out.println("JDK 1.3.1 test passed"); if (pc.implies(mp)) {
} else { System.out.println("JDK 1.3.1 test passed");
throw new Exception("JDK 1.3.1 test failed"); } else {
throw new Exception("JDK 1.3.1 test failed");
}
} }
// read in a 1.4 BasicPermissionCollection // read in a 1.4 BasicPermissionCollection
sFile = new File(dir, "PermClass.1.4"); sFile = new File(dir, "PermClass.1.4");
ois = new ObjectInputStream(new FileInputStream(sFile)); try (FileInputStream fis = new FileInputStream(sFile);
pc = (PermissionCollection)ois.readObject(); ObjectInputStream ois = new ObjectInputStream(fis)) {
System.out.println("1.4 collection = " + pc); PermissionCollection pc = (PermissionCollection)ois.readObject();
System.out.println("1.4 collection = " + pc);
if (pc.implies(mp)) {
System.out.println("JDK 1.4 test 1 passed"); if (pc.implies(mp)) {
} else { System.out.println("JDK 1.4 test 1 passed");
throw new Exception("JDK 1.4 test 1 failed"); } else {
throw new Exception("JDK 1.4 test 1 failed");
}
} }
// write out current BasicPermissionCollection // write out current BasicPermissionCollection
PermissionCollection bpc = mp.newPermissionCollection(); PermissionCollection bpc = mp.newPermissionCollection();
bpc.add(mp); bpc.add(mp);
sFile = new File(dir, "PermClass.current"); sFile = new File(dir, "PermClass.current");
ObjectOutputStream oos = new ObjectOutputStream try (FileOutputStream fos = new FileOutputStream("PermClass.current");
(new FileOutputStream("PermClass.current")); ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(bpc); oos.writeObject(bpc);
oos.close(); }
// read in current BasicPermissionCollection // read in current BasicPermissionCollection
ois = new ObjectInputStream(new FileInputStream("PermClass.current")); try (FileInputStream fis = new FileInputStream("PermClass.current");
pc = (PermissionCollection)ois.readObject(); ObjectInputStream ois = new ObjectInputStream(fis)) {
System.out.println("current collection = " + pc); PermissionCollection pc = (PermissionCollection)ois.readObject();
System.out.println("current collection = " + pc);
if (pc.implies(mp)) {
System.out.println("JDK 1.4 test 2 passed"); if (pc.implies(mp)) {
} else { System.out.println("JDK 1.4 test 2 passed");
throw new Exception("JDK 1.4 test 2 failed"); } else {
throw new Exception("JDK 1.4 test 2 failed");
}
} }
} }
} }
......
/* /*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
/* /*
* @test * @test
* @bug 4502729 * @bug 4502729 7054918
* @summary BasicPermissionCollection serial version UID incorrect * @summary BasicPermissionCollection serial version UID incorrect
*/ */
...@@ -36,40 +36,44 @@ public class SerialVersion { ...@@ -36,40 +36,44 @@ public class SerialVersion {
String dir = System.getProperty("test.src"); String dir = System.getProperty("test.src");
File sFile = new File (dir,"SerialVersion.1.2.1"); File sFile = new File (dir,"SerialVersion.1.2.1");
// read in a 1.2.1 BasicPermissionCollection // read in a 1.2.1 BasicPermissionCollection
ObjectInputStream ois = new ObjectInputStream try (FileInputStream fis = new FileInputStream(sFile);
(new FileInputStream(sFile)); ObjectInputStream ois = new ObjectInputStream(fis)) {
PermissionCollection pc = (PermissionCollection)ois.readObject(); PermissionCollection pc = (PermissionCollection)ois.readObject();
System.out.println("1.2.1 collection = " + pc); System.out.println("1.2.1 collection = " + pc);
}
// read in a 1.3.1 BasicPermissionCollection // read in a 1.3.1 BasicPermissionCollection
sFile = new File (dir,"SerialVersion.1.3.1"); sFile = new File (dir,"SerialVersion.1.3.1");
ois = new ObjectInputStream try (FileInputStream fis = new FileInputStream(sFile);
(new FileInputStream(sFile)); ObjectInputStream ois = new ObjectInputStream(fis)) {
pc = (PermissionCollection)ois.readObject(); PermissionCollection pc = (PermissionCollection)ois.readObject();
System.out.println("1.3.1 collection = " + pc); System.out.println("1.3.1 collection = " + pc);
}
// read in a 1.4 BasicPermissionCollection // read in a 1.4 BasicPermissionCollection
sFile = new File (dir,"SerialVersion.1.4"); sFile = new File (dir,"SerialVersion.1.4");
ois = new ObjectInputStream try (FileInputStream fis = new FileInputStream(sFile);
(new FileInputStream(sFile)); ObjectInputStream ois = new ObjectInputStream(fis)) {
pc = (PermissionCollection)ois.readObject(); PermissionCollection pc = (PermissionCollection)ois.readObject();
System.out.println("1.4 collection = " + pc); System.out.println("1.4 collection = " + pc);
}
// write out current BasicPermissionCollection // write out current BasicPermissionCollection
MyPermission mp = new MyPermission("SerialVersionTest"); MyPermission mp = new MyPermission("SerialVersionTest");
PermissionCollection bpc = mp.newPermissionCollection(); PermissionCollection bpc = mp.newPermissionCollection();
sFile = new File (dir,"SerialVersion.current"); sFile = new File (dir,"SerialVersion.current");
ObjectOutputStream oos = new ObjectOutputStream try (FileOutputStream fos = new FileOutputStream("SerialVersion.current");
(new FileOutputStream("SerialVersion.current")); ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(bpc); oos.writeObject(bpc);
oos.close(); }
// read in current BasicPermissionCollection // read in current BasicPermissionCollection
ois = new ObjectInputStream try (FileInputStream fis = new FileInputStream("SerialVersion.current");
(new FileInputStream("SerialVersion.current")); ObjectInputStream ois = new ObjectInputStream(fis)) {
pc = (PermissionCollection)ois.readObject(); PermissionCollection pc = (PermissionCollection)ois.readObject();
System.out.println("current collection = " + pc); System.out.println("current collection = " + pc);
}
} }
} }
......
/* /*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,8 @@ ...@@ -23,7 +23,8 @@
/** /**
* @test * @test
* @bug 4894125 * @bug 4894125 7054918
* @library ../testlibrary
* @summary test that failover for KeyFactory works * @summary test that failover for KeyFactory works
* @author Andreas Sterbenz * @author Andreas Sterbenz
*/ */
...@@ -37,6 +38,15 @@ import java.security.spec.*; ...@@ -37,6 +38,15 @@ import java.security.spec.*;
public class Failover { public class Failover {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ProvidersSnapshot snapshot = ProvidersSnapshot.create();
try {
main0(args);
} finally {
snapshot.restore();
}
}
public static void main0(String[] args) throws Exception {
Security.insertProviderAt(new ProviderFail(), 1); Security.insertProviderAt(new ProviderFail(), 1);
Security.addProvider(new ProviderPass()); Security.addProvider(new ProviderPass());
System.out.println(Arrays.asList(Security.getProviders())); System.out.println(Arrays.asList(Security.getProviders()));
......
/* /*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,8 @@ ...@@ -23,7 +23,8 @@
/** /**
* @test * @test
* @bug 4894125 * @bug 4894125 7054918
* @library ../testlibrary
* @summary test that failover for KeyPairGenerator works * @summary test that failover for KeyPairGenerator works
* @author Andreas Sterbenz * @author Andreas Sterbenz
*/ */
...@@ -37,6 +38,15 @@ import java.security.spec.*; ...@@ -37,6 +38,15 @@ import java.security.spec.*;
public class Failover { public class Failover {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ProvidersSnapshot snapshot = ProvidersSnapshot.create();
try {
main0(args);
} finally {
snapshot.restore();
}
}
public static void main0(String[] args) throws Exception {
Security.insertProviderAt(new ProviderFail(), 1); Security.insertProviderAt(new ProviderFail(), 1);
Security.addProvider(new ProviderPass()); Security.addProvider(new ProviderPass());
System.out.println(Arrays.asList(Security.getProviders())); System.out.println(Arrays.asList(Security.getProviders()));
......
/* /*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,8 @@ ...@@ -23,7 +23,8 @@
/* /*
* @test * @test
* @bug 4856968 * @bug 4856968 7054918
* @library ../testlibrary
* @summary make sure add/insert/removeProvider() work correctly * @summary make sure add/insert/removeProvider() work correctly
* @author Andreas Sterbenz * @author Andreas Sterbenz
*/ */
...@@ -43,6 +44,15 @@ public class ChangeProviders extends Provider { ...@@ -43,6 +44,15 @@ public class ChangeProviders extends Provider {
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ProvidersSnapshot snapshot = ProvidersSnapshot.create();
try {
main0(args);
} finally {
snapshot.restore();
}
}
public static void main0(String[] args) throws Exception {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
Provider p = new ChangeProviders(); Provider p = new ChangeProviders();
......
/* /*
* Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,8 @@ ...@@ -23,7 +23,8 @@
/* /*
* @test * @test
* @bug 4856968 * @bug 4856968 7054918
* @library ../testlibrary
* @summary make sure getInstance() works correctly, including failover * @summary make sure getInstance() works correctly, including failover
* and delayed provider selection for Signatures * and delayed provider selection for Signatures
* @author Andreas Sterbenz * @author Andreas Sterbenz
...@@ -43,6 +44,15 @@ public class GetInstance { ...@@ -43,6 +44,15 @@ public class GetInstance {
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ProvidersSnapshot snapshot = ProvidersSnapshot.create();
try {
main0(args);
} finally {
snapshot.restore();
}
}
public static void main0(String[] args) throws Exception {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
Provider foo = new FooProvider(); Provider foo = new FooProvider();
......
/* /*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,8 @@ ...@@ -23,7 +23,8 @@
/* /*
* @test * @test
* @bug 4190873 * @bug 4190873 7054918
* @library ../testlibrary
* @summary Make sure provider instance can be removed from list of registered * @summary Make sure provider instance can be removed from list of registered
* providers, and "entrySet", "keySet", and "values" methods don't loop * providers, and "entrySet", "keySet", and "values" methods don't loop
* indefinitely. * indefinitely.
...@@ -34,6 +35,15 @@ import java.util.*; ...@@ -34,6 +35,15 @@ import java.util.*;
public class RemoveProvider { public class RemoveProvider {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ProvidersSnapshot snapshot = ProvidersSnapshot.create();
try {
main0(args);
} finally {
snapshot.restore();
}
}
public static void main0(String[] args) throws Exception {
// Add provider 1 // Add provider 1
Provider p1 = new MyProvider("name1",1,""); Provider p1 = new MyProvider("name1",1,"");
......
/* /*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,9 +23,8 @@ ...@@ -23,9 +23,8 @@
/** /**
* @test * @test
* @bug 6220064 * @bug 6220064 7054918
* @summary make sure everything works ok in the Turkish local (dotted/dotless i problem) * @summary make sure everything works ok in the Turkish local (dotted/dotless i problem)
* @run main/othervm Turkish
* @author Andreas Sterbenz * @author Andreas Sterbenz
*/ */
...@@ -41,54 +40,59 @@ public class Turkish { ...@@ -41,54 +40,59 @@ public class Turkish {
Provider p1 = new TProvider("T1"); Provider p1 = new TProvider("T1");
System.out.println(p1.getServices()); // trigger service parsing System.out.println(p1.getServices()); // trigger service parsing
Locale.setDefault(new Locale("tr", "TR")); Locale loc = Locale.getDefault();
try {
Locale.setDefault(new Locale("tr", "TR"));
Provider p2 = new TProvider("T2"); Provider p2 = new TProvider("T2");
System.out.println(p2.getServices()); // trigger service parsing System.out.println(p2.getServices()); // trigger service parsing
System.out.println(Signature.getInstance("MD5withRSA")); System.out.println(Signature.getInstance("MD5withRSA"));
System.out.println(Signature.getInstance("md5withrsa")); System.out.println(Signature.getInstance("md5withrsa"));
System.out.println(Signature.getInstance("MD5WITHRSA")); System.out.println(Signature.getInstance("MD5WITHRSA"));
Service s1, s2; Service s1, s2;
s1 = p1.getService("Signature", "MD5withRSA"); s1 = p1.getService("Signature", "MD5withRSA");
check(s1, null); check(s1, null);
check(s1, p1.getService("Signature", "md5withrsa")); check(s1, p1.getService("Signature", "md5withrsa"));
check(s1, p1.getService("Signature", "MD5WITHRSA")); check(s1, p1.getService("Signature", "MD5WITHRSA"));
check(s1, p1.getService("Signature", "MD5RSA")); check(s1, p1.getService("Signature", "MD5RSA"));
check(s1, p1.getService("Signature", "md5rsa")); check(s1, p1.getService("Signature", "md5rsa"));
check(s1, p1.getService("Signature", "MD5rsa")); check(s1, p1.getService("Signature", "MD5rsa"));
s1 = p1.getService("Signature", "SHAwithRSA"); s1 = p1.getService("Signature", "SHAwithRSA");
check(s1, null); check(s1, null);
check(s1, p1.getService("Signature", "shawithrsa")); check(s1, p1.getService("Signature", "shawithrsa"));
check(s1, p1.getService("Signature", "SHAWITHRSA")); check(s1, p1.getService("Signature", "SHAWITHRSA"));
check(s1, p1.getService("Signature", "SHARSA")); check(s1, p1.getService("Signature", "SHARSA"));
check(s1, p1.getService("Signature", "sharsa")); check(s1, p1.getService("Signature", "sharsa"));
check(s1, p1.getService("Signature", "SHArsa")); check(s1, p1.getService("Signature", "SHArsa"));
check(s1, p1.getService("Signature", "SHA1RSA")); check(s1, p1.getService("Signature", "SHA1RSA"));
check(s1, p1.getService("Signature", "sha1rsa")); check(s1, p1.getService("Signature", "sha1rsa"));
check(s1, p1.getService("Signature", "SHA1rsa")); check(s1, p1.getService("Signature", "SHA1rsa"));
s1 = p2.getService("Signature", "MD5withRSA"); s1 = p2.getService("Signature", "MD5withRSA");
check(s1, null); check(s1, null);
check(s1, p2.getService("Signature", "md5withrsa")); check(s1, p2.getService("Signature", "md5withrsa"));
check(s1, p2.getService("Signature", "MD5WITHRSA")); check(s1, p2.getService("Signature", "MD5WITHRSA"));
check(s1, p2.getService("Signature", "MD5RSA")); check(s1, p2.getService("Signature", "MD5RSA"));
check(s1, p2.getService("Signature", "md5rsa")); check(s1, p2.getService("Signature", "md5rsa"));
check(s1, p2.getService("Signature", "MD5rsa")); check(s1, p2.getService("Signature", "MD5rsa"));
s1 = p2.getService("Signature", "SHAwithRSA"); s1 = p2.getService("Signature", "SHAwithRSA");
check(s1, null); check(s1, null);
check(s1, p2.getService("Signature", "shawithrsa")); check(s1, p2.getService("Signature", "shawithrsa"));
check(s1, p2.getService("Signature", "SHAWITHRSA")); check(s1, p2.getService("Signature", "SHAWITHRSA"));
check(s1, p2.getService("Signature", "SHARSA")); check(s1, p2.getService("Signature", "SHARSA"));
check(s1, p2.getService("Signature", "sharsa")); check(s1, p2.getService("Signature", "sharsa"));
check(s1, p2.getService("Signature", "SHArsa")); check(s1, p2.getService("Signature", "SHArsa"));
check(s1, p2.getService("Signature", "SHA1RSA")); check(s1, p2.getService("Signature", "SHA1RSA"));
check(s1, p2.getService("Signature", "sha1rsa")); check(s1, p2.getService("Signature", "sha1rsa"));
check(s1, p2.getService("Signature", "SHA1rsa")); check(s1, p2.getService("Signature", "SHA1rsa"));
System.out.println("OK"); System.out.println("OK");
} finally {
Locale.setDefault(loc);
}
} }
private static void check(Service s1, Service s2) throws Exception { private static void check(Service s1, Service s2) throws Exception {
......
/* /*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
/* /*
* @test * @test
* @bug 4894899 * @bug 4894899 7054428
* @summary Test various cases of passing java.nio.ByteBuffers * @summary Test various cases of passing java.nio.ByteBuffers
* to defineClass(). * to defineClass().
* *
...@@ -46,6 +46,17 @@ public class DefineClassByteBuffer { ...@@ -46,6 +46,17 @@ public class DefineClassByteBuffer {
} }
public static void main(String arg[]) throws Exception { public static void main(String arg[]) throws Exception {
// Rename the compiled TestClass.class file to something else,
// otherwise it would be loaded by the parent class loader and
// DummyClassLoader will never be used, especially in /othervm mode.
File oldFile = new File(System.getProperty("test.classes", "."),
"TestClass.class");
File newFile = new File(System.getProperty("test.classes", "."),
"CLAZZ");
oldFile.renameTo(newFile);
ClassLoader[] cls = new ClassLoader[DummyClassLoader.MAX_TYPE]; ClassLoader[] cls = new ClassLoader[DummyClassLoader.MAX_TYPE];
for (int i = 0; i < cls.length; i++) { for (int i = 0; i < cls.length; i++) {
cls[i] = new DummyClassLoader(i); cls[i] = new DummyClassLoader(i);
...@@ -54,7 +65,11 @@ public class DefineClassByteBuffer { ...@@ -54,7 +65,11 @@ public class DefineClassByteBuffer {
/* Create several instances of the class using different classloaders, /* Create several instances of the class using different classloaders,
which are using different types of ByteBuffer. */ which are using different types of ByteBuffer. */
for (int i = 0; i < cls.length; i++) { for (int i = 0; i < cls.length; i++) {
test(cls[i]); test(cls[i]);
}
if (DummyClassLoader.count != cls.length) {
throw new Exception("DummyClassLoader not always used");
} }
} }
...@@ -75,6 +90,8 @@ public class DefineClassByteBuffer { ...@@ -75,6 +90,8 @@ public class DefineClassByteBuffer {
int loaderType; int loaderType;
static int count = 0;
DummyClassLoader(int loaderType) { DummyClassLoader(int loaderType) {
this.loaderType = loaderType; this.loaderType = loaderType;
} }
...@@ -84,10 +101,11 @@ public class DefineClassByteBuffer { ...@@ -84,10 +101,11 @@ public class DefineClassByteBuffer {
static ByteBuffer readClassFile(String name) { static ByteBuffer readClassFile(String name) {
try { try {
File f = new File(System.getProperty("test.classes", "."), File f = new File(System.getProperty("test.classes", "."),
name); "CLAZZ");
FileInputStream fin = new FileInputStream(f); try (FileInputStream fin = new FileInputStream(f);
FileChannel fc = fin.getChannel(); FileChannel fc = fin.getChannel()) {
return fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); return fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
}
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
throw new RuntimeException("Can't open file: " + name, e); throw new RuntimeException("Can't open file: " + name, e);
} catch (IOException e) { } catch (IOException e) {
...@@ -101,12 +119,16 @@ public class DefineClassByteBuffer { ...@@ -101,12 +119,16 @@ public class DefineClassByteBuffer {
buffers. */ buffers. */
buffers[MAPPED_BUFFER] = readClassFile(CLASS_NAME + ".class"); buffers[MAPPED_BUFFER] = readClassFile(CLASS_NAME + ".class");
byte[] array = new byte[buffers[MAPPED_BUFFER].limit()]; byte[] array = new byte[buffers[MAPPED_BUFFER].limit()];
buffers[MAPPED_BUFFER].get(array);
buffers[MAPPED_BUFFER].flip();
buffers[DIRECT_BUFFER] = ByteBuffer.allocateDirect(array.length); buffers[DIRECT_BUFFER] = ByteBuffer.allocateDirect(array.length);
buffers[DIRECT_BUFFER].put(array); buffers[DIRECT_BUFFER].put(array);
buffers[DIRECT_BUFFER].flip();
buffers[ARRAY_BUFFER] = ByteBuffer.allocate(array.length); buffers[ARRAY_BUFFER] = ByteBuffer.allocate(array.length);
buffers[ARRAY_BUFFER].put(array); buffers[ARRAY_BUFFER].put(array);
buffers[ARRAY_BUFFER].flip();
buffers[WRAPPED_BUFFER] = ByteBuffer.wrap(array); buffers[WRAPPED_BUFFER] = ByteBuffer.wrap(array);
...@@ -121,6 +143,7 @@ public class DefineClassByteBuffer { ...@@ -121,6 +143,7 @@ public class DefineClassByteBuffer {
public Class findClass(String name) { public Class findClass(String name) {
CodeSource cs = null; CodeSource cs = null;
count++;
return defineClass(name, buffers[loaderType], cs); return defineClass(name, buffers[loaderType], cs);
} }
} /* DummyClassLoader */ } /* DummyClassLoader */
......
#!/bin/sh #!/bin/sh
# #
# Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
# #
# This code is free software; you can redistribute it and/or modify it # This code is free software; you can redistribute it and/or modify it
...@@ -58,6 +58,10 @@ case "$OS" in ...@@ -58,6 +58,10 @@ case "$OS" in
PATHSEP=":" PATHSEP=":"
FILESEP="/" FILESEP="/"
;; ;;
CYGWIN* )
PATHSEP=";"
FILESEP="/"
;;
Windows* ) Windows* )
PATHSEP=";" PATHSEP=";"
FILESEP="\\" FILESEP="\\"
......
...@@ -23,7 +23,8 @@ ...@@ -23,7 +23,8 @@
/* /*
* @test * @test
* @bug 4273454 7052537 * @bug 4273454 7054918 7052537
* @library ../testlibrary
* @summary Make sure getProviders(filter) doesn't throw NPE * @summary Make sure getProviders(filter) doesn't throw NPE
* @run main/othervm NoInstalledProviders * @run main/othervm NoInstalledProviders
*/ */
...@@ -32,7 +33,16 @@ import java.security.*; ...@@ -32,7 +33,16 @@ import java.security.*;
public class NoInstalledProviders { public class NoInstalledProviders {
public static void main(String[] argv) { public static void main(String[] args) throws Exception {
ProvidersSnapshot snapshot = ProvidersSnapshot.create();
try {
main0(args);
} finally {
snapshot.restore();
}
}
public static void main0(String[] args) throws Exception {
Provider[] provs = Security.getProviders(); Provider[] provs = Security.getProviders();
// make sure there are no providers in the system // make sure there are no providers in the system
......
/* /*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,8 @@ ...@@ -23,7 +23,8 @@
/* /*
* @test * @test
* @bug 4162583 * @bug 4162583 7054918
* @library ../testlibrary
* @summary Make sure Provider api implementations are synchronized properly * @summary Make sure Provider api implementations are synchronized properly
*/ */
...@@ -31,7 +32,16 @@ import java.security.*; ...@@ -31,7 +32,16 @@ import java.security.*;
public class SynchronizedAccess { public class SynchronizedAccess {
public static void main(String[] args) { public static void main(String[] args) throws Exception {
ProvidersSnapshot snapshot = ProvidersSnapshot.create();
try {
main0(args);
} finally {
snapshot.restore();
}
}
public static void main0(String[] args) throws Exception {
AccessorThread[] acc = new AccessorThread[200]; AccessorThread[] acc = new AccessorThread[200];
for (int i=0; i < acc.length; i++) for (int i=0; i < acc.length; i++)
acc[i] = new AccessorThread("thread"+i); acc[i] = new AccessorThread("thread"+i);
......
/* /*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,8 @@ ...@@ -23,7 +23,8 @@
/** /**
* @test * @test
* @bug 4963416 * @bug 4963416 7054918
* @library ../../testlibrary
* @summary make sure removeProvider() always works correctly * @summary make sure removeProvider() always works correctly
* @author Andreas Sterbenz * @author Andreas Sterbenz
*/ */
...@@ -35,6 +36,15 @@ import java.security.*; ...@@ -35,6 +36,15 @@ import java.security.*;
public class RemoveProviders { public class RemoveProviders {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ProvidersSnapshot snapshot = ProvidersSnapshot.create();
try {
main0(args);
} finally {
snapshot.restore();
}
}
public static void main0(String[] args) throws Exception {
Provider[] providers = Security.getProviders(); Provider[] providers = Security.getProviders();
System.out.println("Providers: " + Arrays.asList(providers)); System.out.println("Providers: " + Arrays.asList(providers));
......
/* /*
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -24,6 +24,7 @@ ...@@ -24,6 +24,7 @@
/* /*
* @test * @test
* @bug 4513737 * @bug 4513737
* @run main/othervm Equals
* @summary UnresolvedPermission.equals() throws NullPointerException * @summary UnresolvedPermission.equals() throws NullPointerException
*/ */
......
...@@ -25,13 +25,12 @@ ...@@ -25,13 +25,12 @@
* @test * @test
* @bug 6738532 * @bug 6738532
* @summary Check EllipticCurve.equals() does not compare seed value of curve. * @summary Check EllipticCurve.equals() does not compare seed value of curve.
* @run main/othervm EllipticCurveMatch
* @author Mike StJohns * @author Mike StJohns
*/ */
import java.security.spec.*; import java.security.spec.*;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.SecureRandom; import java.util.Random;
public class EllipticCurveMatch { public class EllipticCurveMatch {
static String primeP256 = static String primeP256 =
...@@ -45,7 +44,7 @@ public class EllipticCurveMatch { ...@@ -45,7 +44,7 @@ public class EllipticCurveMatch {
private static EllipticCurve addSeedToCurve(EllipticCurve curve) private static EllipticCurve addSeedToCurve(EllipticCurve curve)
{ {
SecureRandom rand = new SecureRandom(); Random rand = new Random();
byte[] seed = new byte[12]; byte[] seed = new byte[12];
rand.nextBytes(seed); rand.nextBytes(seed);
......
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.Provider;
import java.security.Security;
public class ProvidersSnapshot {
private Provider[] oldProviders;
private ProvidersSnapshot() {
oldProviders = Security.getProviders();
}
public static ProvidersSnapshot create() {
return new ProvidersSnapshot();
}
public void restore() {
Provider[] newProviders = Security.getProviders();
for (Provider p: newProviders) {
Security.removeProvider(p.getName());
}
for (Provider p: oldProviders) {
Security.addProvider(p);
}
}
}
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* 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 7045594
* @summary ResourceBundle setting race in Logger.getLogger(name, rbName)
* @author Daniel D. Daugherty
* @build RacingThreadsTest LoggerResourceBundleRace
* @run main LoggerResourceBundleRace
*/
import java.util.concurrent.atomic.AtomicInteger;
import java.util.ListResourceBundle;
import java.util.logging.Logger;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class LoggerResourceBundleRace extends RacingThreadsTest {
private final static int N_LOOPS = 500000; // # of race loops
private final static int N_SECS = 15; // # of secs to run test
// # of parallel threads; must match number of MyResources inner classes
private final static int N_THREADS = 3;
private final static String LOGGER_PREFIX = "myLogger-";
private final static String RESOURCE_PREFIX
= "LoggerResourceBundleRace$MyResources";
// these counters are AtomicInteger since any worker thread can increment
private final static AtomicInteger iaeCnt = new AtomicInteger();
private final static AtomicInteger worksCnt = new AtomicInteger();
Logger dummy; // dummy Logger
LoggerResourceBundleRace(String name, int n_threads, int n_loops,
int n_secs) {
super(name, n_threads, n_loops, n_secs);
}
// Main test driver
//
public static void main(String[] args) {
LoggerResourceBundleRace test
= new LoggerResourceBundleRace("LoggerResourceBundleRace",
N_THREADS, N_LOOPS, N_SECS);
test.setVerbose(
Boolean.getBoolean("LoggerResourceBundleRace.verbose"));
DriverThread driver = new DriverThread(test);
MyWorkerThread[] workers = new MyWorkerThread[N_THREADS];
for (int i = 0; i < workers.length; i++) {
workers[i] = new MyWorkerThread(i, test);
}
test.runTest(driver, workers);
}
public void oneTimeDriverInit(DriverThread dt) {
super.oneTimeDriverInit(dt);
dummy = null;
}
public void perRaceDriverInit(DriverThread dt) {
super.perRaceDriverInit(dt);
// - allocate a new dummy Logger without a ResourceBundle;
// this gives the racing threads less to do
// - reset the counters
dummy = Logger.getLogger(LOGGER_PREFIX + getLoopCnt());
iaeCnt.set(0);
worksCnt.set(0);
}
public void executeRace(WorkerThread wt) {
super.executeRace(wt);
Logger myLogger = null;
try {
MyWorkerThread mwt = (MyWorkerThread) wt; // short hand
// Here is the race:
// - the target Logger object has already been created by
// the DriverThread without a ResourceBundle name
// - in parallel, each WorkerThread calls Logger.getLogger()
// with a different ResourceBundle name
// - Logger.getLogger() should only successfully set the
// ResourceBundle name for one WorkerThread; all other
// WorkerThread calls to Logger.getLogger() should throw
// IllegalArgumentException
myLogger = Logger.getLogger(LOGGER_PREFIX + getLoopCnt(),
mwt.rbName);
if (myLogger.getResourceBundleName().equals(mwt.rbName)) {
// no exception and the ResourceBundle names match
worksCnt.incrementAndGet(); // ignore return
} else {
System.err.println(wt.getName()
+ ": ERROR: expected ResourceBundleName '"
+ mwt.rbName + "' does not match actual '"
+ myLogger.getResourceBundleName() + "'");
incAndGetFailCnt(); // ignore return
}
} catch (IllegalArgumentException iae) {
iaeCnt.incrementAndGet(); // ignore return
} catch (MissingResourceException mre) {
// This exception happens when N_THREADS above does not
// match the number of MyResources inner classes below.
// We exit since this is a coding error.
unexpectedException(wt, mre);
System.exit(2);
}
}
public void checkRaceResults(DriverThread dt) {
super.checkRaceResults(dt);
if (worksCnt.get() != 1) {
System.err.println(dt.getName() + ": ERROR: worksCnt should be 1"
+ ": loopCnt=" + getLoopCnt() + ", worksCnt=" + worksCnt.get());
incAndGetFailCnt(); // ignore return
} else if (iaeCnt.get() != N_THREADS - 1) {
System.err.println(dt.getName() + ": ERROR: iaeCnt should be "
+ (N_THREADS - 1) + ": loopCnt=" + getLoopCnt()
+ ", iaeCnt=" + iaeCnt.get());
incAndGetFailCnt(); // ignore return
}
}
public void oneTimeDriverEpilog(DriverThread dt) {
super.oneTimeDriverEpilog(dt);
// Use the dummy Logger after the testing loop to make sure that
// dummy doesn't get optimized away in the testing loop.
dummy.info("This is a test message.");
}
// N_THREADS above must match number of MyResources inner classes
//
public static class MyResources0 extends ListResourceBundle {
final static Object[][] contents = {
{"sample1", "translation #1 for sample1"},
{"sample2", "translation #1 for sample2"},
};
public Object[][] getContents() {
return contents;
}
}
public static class MyResources1 extends ListResourceBundle {
final static Object[][] contents = {
{"sample1", "translation #2 for sample1"},
{"sample2", "translation #2 for sample2"},
};
public Object[][] getContents() {
return contents;
}
}
public static class MyResources2 extends ListResourceBundle {
final static Object[][] contents = {
{"sample1", "translation #3 for sample1"},
{"sample2", "translation #3 for sample2"},
};
public Object[][] getContents() {
return contents;
}
}
// WorkerThread with a thread specific ResourceBundle name
//
public static class MyWorkerThread extends WorkerThread {
public final String rbName; // ResourceBundle name
MyWorkerThread(int workerNum, RacingThreadsTest test) {
super(workerNum, test);
rbName = RESOURCE_PREFIX + workerNum;
}
}
}
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
* @summary Calling LogManager.addLogger() and Logger.getLogger() cause deadlock * @summary Calling LogManager.addLogger() and Logger.getLogger() cause deadlock
* @author Serguei Spitsyn * @author Serguei Spitsyn
* @build LoggingDeadlock3 * @build LoggingDeadlock3
* @run main/timeout=15 LoggingDeadlock3 * @run main/timeout=80 LoggingDeadlock3
*/ */
import java.io.*; import java.io.*;
......
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
* RacingThreadsTest is a support class for creating a test
* where multiple threads are needed to exercise a code path.
* The RacingThreadsTest class is typically used as follows:
* <ul>
* <li>
* Extend RacingThreadsTest class in order to provide the test
* specific variables and/or code, e.g., <br>
* public class MyRacingThreadsTest extends RacingThreadsTest
* <li>
* Use
* "new MyRacingThreadsTest(name, n_threads, n_loops, n_secs)"
* to create your test with the specified name and the specified
* number of WorkerThreads that execute the test code in parallel
* up to n_loops iterations or n_secs seconds.
* <li>
* Use
* "new DriverThread(test)"
* to create the test DriverThread that manages all the
* WorkerThreads. The DriverThread class can be extended to
* provide test specific code and/or variables. However, that
* is typically done in your test's subclass.
* <li>
* Use
* "new WorkerThread(workerNum, test)"
* to create WorkerThread-workerNum that executes the test code.
* The WorkerThread class can be extended to provide test thread
* specific code and/or variables.
* <li>
* Use
* "RacingThreadsTest.runTest(driver, workers)"
* to run the test. If the test fails, then a RuntimeException
* is thrown.
* </ul>
*
* The RacingThreadsTest class provides many methods that can be
* overridden in order to provide test specific semantics at each
* identified test execution point. At a minimum, your test's
* subclass needs to override the
* "void executeRace(WorkerThread)"
* method in order to exercise your race condition and it needs to
* override the
* "void checkRaceResults(DriverThread)"
* method in order to check the results of the race. Your
* checkRaceResults() method should call the
* "int incAndGetFailCnt()"
* method when it detects a failure. It can also call the
* "void unexpectedException(Thread, Exception)"
* method if it detects an unexpected exception; this will cause
* an error message to be output and the failure count to be
* incremented. When the RacingThreadsTest.runTest() method is
* done running the races, if there is a non-zero failure count,
* then a RuntimeException will be thrown.
* <p>
* The RacingThreadsTest class uses three internal barriers to
* coordinate actions between the DriverThread and the WorkerThreads.
* These barriers should not be managed or used by your test's
* subclass and are only mentioned here to provide clarity about
* interactions between the DriverThread and the WorkerThreads.
* The following transaction diagram shows when the different
* RacingThreadsTest methods are called relative to the different
* barriers:
*
* <pre>
* DriverThread WorkerThread-0 WorkerThread-N-1
* --------------------- --------------------- ---------------------
* run(workers)
* oneTimeDriverInit()
* &lt;start WorkerThreads&gt; run() run()
* &lt;top of race loop&gt; : :
* perRaceDriverInit() oneTimeWorkerInit() oneTimeWorkerInit()
* : &lt;top of race loop&gt; &lt;top of race loop&gt;
* : perRaceWorkerInit() perRaceWorkerInit()
* startBarrier startBarrier startBarrier
* : executeRace() executeRace()
* finishBarrier finishBarrier finishBarrier
* checkRaceResults() : :
* resetBarrier resetBarrier resetBarrier
* perRaceDriverEpilog() perRaceWorkerEpilog() perRaceWorkerEpilog()
* &lt;repeat race or done&gt; &lt;repeat race or done&gt; &lt;repeat race or done&gt;
* : oneTimeWorkerEpilog() oneTimeWorkerEpilog()
* &lt;join WorkerThreads&gt; &lt;WorkerThread ends&gt; &lt;WorkerThread ends&gt;
* oneTimeDriverEpilog()
* &lt;DriverThread ends&gt;
* </pre>
*
* Just to be clear about the parallel parts of this infrastructure:
* <ul>
* <li>
* After the DriverThread starts the WorkerThreads, the DriverThread
* and the WorkerThreads are running in parallel until the startBarrier
* is reached.
* <li>
* After the WorkerThreads leave the startBarrier, they are running
* the code in executeRace() in parallel which is the whole point
* of this class.
* <li>
* The DriverThread heads straight to the finishBarrier and waits for
* the WorkerThreads to get there.
* <li>
* After the DriverThread leaves the finishBarrier, it checks the
* results of the race.
* <li>
* The WorkerThreads head straight to the resetBarrier and wait for
* the DriverThread to get there.
* <li>
* If this is not the last race, then after the DriverThread and
* WorkerThreads leave the resetBarrier, the DriverThread and the
* WorkerThreads are running in parallel until the startBarrier
* is reached.
* <li>
* If this is the last race, then after the DriverThread and
* WorkerThreads leave the resetBarrier, the DriverThread and the
* WorkerThreads are running in parallel as each WorkerThread ends.
* <li>
* The DriverThread waits for the WorkerThreads to end and
* then it ends
* </ul>
*
* Once the DriverThread has ended, the RacingThreadsTest.runTest()
* method checks the failure count. If there were no failures, then
* a "Test PASSed" message is printed. Otherwise, the failure count
* is printed, a "Test FAILed" message is printed and a RuntimeException
* is thrown.
*/
public class RacingThreadsTest {
/**
* name of the test
*/
public final String TEST_NAME;
/**
* maximum number of test iterations (race loops)
*/
public final int N_LOOPS;
/**
* the maximum number of seconds to execute the test loop
*/
public final int N_SECS;
/**
* number of WorkerThreads
*/
public final int N_THREADS;
/**
* Creates a test with the specified name and the specified number
* of WorkerThreads that execute the test code in parallel up to
* n_loops iterations or n_secs seconds. The RacingThreadsTest
* class is extended in order to provide the test specific variables
* and/or code.
* @param name the name of the test
* @param n_threads the number of WorkerThreads
* @param n_loops the maximum number of test iterations
* @param n_secs the maximum number of seconds to execute the test loop
*/
RacingThreadsTest(String name, int n_threads, int n_loops, int n_secs) {
TEST_NAME = name;
N_THREADS = n_threads;
N_LOOPS = n_loops;
N_SECS = n_secs;
finishBarrier = new CyclicBarrier(N_THREADS + 1);
resetBarrier = new CyclicBarrier(N_THREADS + 1);
startBarrier = new CyclicBarrier(N_THREADS + 1);
}
/**
* Entry point for exercising the RacingThreadsTest class.
*/
public static void main(String[] args) {
// a dummy test:
// - 2 threads
// - 3 loops
// - 2 seconds
// - standard DriverThread
// - standard WorkerThread
RacingThreadsTest test = new RacingThreadsTest("dummy", 2, 3, 2);
DriverThread driver = new DriverThread(test);
WorkerThread[] workers = new WorkerThread[2];
for (int i = 0; i < workers.length; i++) {
workers[i] = new WorkerThread(i, test);
}
test.runTest(driver, workers);
}
private static volatile boolean done = false; // test done flag
// # of fails; AtomicInteger since any WorkerThread can increment
private static final AtomicInteger failCnt = new AtomicInteger();
// # of loops; volatile is OK since only DriverThread increments
// but using AtomicInteger for consistency
private static final AtomicInteger loopCnt = new AtomicInteger();
private static boolean verbose
= Boolean.getBoolean("RacingThreadsTest.verbose");
// barriers for starting, finishing and resetting the race
private final CyclicBarrier finishBarrier;
private final CyclicBarrier resetBarrier;
private final CyclicBarrier startBarrier;
/**
* Get current done flag value.
* @return the current done flag value
*/
public boolean getDone() {
return done;
}
/**
* Set done flag to specified value.
* @param v the new done flag value
*/
public void setDone(boolean v) {
done = v;
}
/**
* Get current failure counter value.
* @return the current failure count
*/
public int getFailCnt() {
return failCnt.get();
}
/**
* Increment and get current failure counter value.
* @return the current failure count after incrementing
*/
public int incAndGetFailCnt() {
return failCnt.incrementAndGet();
}
/**
* Get current loop counter value.
* @return the current loop count
*/
public int getLoopCnt() {
return loopCnt.get();
}
/**
* Increment and get current loop counter value.
* @return the current loop count after incrementing
*/
public int incAndGetLoopCnt() {
return loopCnt.incrementAndGet();
}
/**
* Get current verbose flag value.
* @return the current verbose flag value
*/
public boolean getVerbose() {
return verbose;
}
/**
* Set verbose flag to specified value.
* @param v the new verbose flag value
*/
public void setVerbose(boolean v) {
verbose = v;
}
/**
* Run the test with the specified DriverThread and the
* specified WorkerThreads.
* @param driver the DriverThread for running the test
* @param workers the WorkerThreads for executing the race
* @exception RuntimeException the test has failed
*/
public void runTest(DriverThread driver, WorkerThread[] workers) {
driver.run(workers);
try {
driver.join();
} catch (InterruptedException ie) {
unexpectedException(Thread.currentThread(), ie);
// fall through to test failed below
}
if (failCnt.get() == 0) {
System.out.println(TEST_NAME + ": Test PASSed.");
} else {
System.out.println(TEST_NAME + ": failCnt=" + failCnt.get());
System.out.println(TEST_NAME + ": Test FAILed.");
throw new RuntimeException("Test Failed");
}
}
/**
* Helper method for reporting an unexpected Exception and
* calling incAndGetFailCnt();
* @param t the Thread that caught the exception
* @param e the Exception that was caught
*/
public void unexpectedException(Thread t, Exception e) {
System.err.println(t.getName() + ": ERROR: unexpected exception: " + e);
incAndGetFailCnt(); // ignore return
}
// The following methods are typically overridden by the subclass
// of RacingThreadsTest to provide test specific semantics at each
// identified test execution point:
/**
* Initialize 1-time items for the DriverThread.
* Called by the DriverThread before WorkerThreads are started.
* @param dt the DriverThread
*/
public void oneTimeDriverInit(DriverThread dt) {
if (verbose)
System.out.println(dt.getName() + ": oneTimeDriverInit() called");
}
/**
* Initialize 1-time items for a WorkerThread. Called by a
* WorkerThread after oneTimeDriverInit() and before the
* WorkerThread checks in with startBarrier. May execute in
* parallel with perRaceDriverInit() or with another
* WorkerThread's oneTimeWorkerInit() call or another
* WorkerThread's perRaceWorkerInit() call.
* @param wt the WorkerThread
*/
public void oneTimeWorkerInit(WorkerThread wt) {
if (verbose)
System.out.println(wt.getName() + ": oneTimeWorkerInit() called");
}
/**
* Initialize per-race items for the DriverThread. Called by the
* DriverThread before it checks in with startBarrier. May execute
* in parallel with oneTimeWorkerInit() and perRaceWorkerInit()
* calls. After any race except for the last race, this method may
* execute in parallel with perRaceWorkerEpilog().
* @param dt the DriverThread
*/
public void perRaceDriverInit(DriverThread dt) {
if (verbose)
System.out.println(dt.getName() + ": perRaceDriverInit() called");
}
/**
* Initialize per-race items for a WorkerThread. Called by each
* WorkerThread before it checks in with startBarrier. On the first
* call, this method may execute in parallel with another
* WorkerThread's oneTimeWorkerInit() call. On any call, this method
* may execute in parallel with perRaceDriverInit() or another
* WorkerThread's perRaceWorkerInit() call. After any race except
* for the last race, this method may execute in parallel with
* perRaceDriverEpilog() or another WorkerThread's
* perRaceWorkerEpilog() call.
* @param wt the WorkerThread
*/
public void perRaceWorkerInit(WorkerThread wt) {
if (verbose)
System.out.println(wt.getName() + ": perRaceWorkerInit() called");
}
/**
* Execute the race in a WorkerThread. Called by each WorkerThread
* after it has been released from startBarrier.
* @param wt the WorkerThread
*/
public void executeRace(WorkerThread wt) {
if (verbose)
System.out.println(wt.getName() + ": executeRace() called");
}
/**
* Check race results in the DriverThread. Called by the DriverThread
* after it has been released from finishBarrier and before the
* DriverThread checks in with resetBarrier.
* @param dt the DriverThread
*/
public void checkRaceResults(DriverThread dt) {
if (verbose)
System.out.println(dt.getName() + ": checkRaceResults() called");
}
/**
* Handle end-of-race items for the DriverThread. Called by the
* DriverThread after it has been released from resetBarrier and
* before the DriverThread checks in again with startBarrier. Can
* execute in parallel with perRaceWorkerEpilog(). If this is not
* the last race, can execute in parallel with perRaceWorkerInit().
* If this is the last race, can execute in parallel with
* oneTimeWorkerEpilog().
* @param dt the DriverThread
*/
public void perRaceDriverEpilog(DriverThread dt) {
if (verbose)
System.out.println(dt.getName() + ": perRaceDriverEpilog() called");
}
/**
* Handle end-of-race items for a WorkerThread. Called by each
* WorkerThread after it has been released from resetBarrier and
* before the WorkerThread checks in again with startBarrier.
* Can execute in parallel with perRaceDriverEpilog() or another
* WorkerThread's perRaceWorkerEpilog() call. If this is not the
* last race, can execute in parallel with perRaceDriverInit(),
* or another WorkerThread's perRaceWorkerInit() call. If this
* is the last race, can execute in parallel with another
* WorkerThread's oneTimeWorkerEpilog() call.
* @param wt the WorkerThread
*/
public void perRaceWorkerEpilog(WorkerThread wt) {
if (verbose)
System.out.println(wt.getName() + ": perRaceWorkerEpilog() called");
}
/**
* Handle end-of-test items for a WorkerThread. Called by each
* WorkerThread after it has detected that all races are done and
* before oneTimeDriverEpilog() is called. Can execute in parallel
* with perRaceDriverEpilog(), with another WorkerThread's
* perRaceWorkerEpilog() call or with another WorkerThread's
* oneTimeWorkerEpilog() call.
* @param wt the WorkerThread
*/
public void oneTimeWorkerEpilog(WorkerThread wt) {
if (verbose)
System.out.println(wt.getName() + ": oneTimeWorkerEpilog() called");
}
/**
* Handle end-of-test items for the DriverThread. Called by the
* DriverThread after all the WorkerThreads have called
* oneTimeWorkerEpilog().
* @param dt the DriverThread
*/
public void oneTimeDriverEpilog(DriverThread dt) {
if (verbose)
System.out.println(dt.getName() + ": oneTimeDriverEpilog() called");
}
/**
* DriverThread for executing the test.
*/
public static class DriverThread extends Thread {
private final RacingThreadsTest test;
/**
* Create the test DriverThread that manages all the WorkerThreads.
* The DriverThread class can be extended to provide test specific
* variables and/or code. However, that is typically done in the
* subclass of RacingThreadsTest.
* @parameter test the RacingThreadsTest being run
*/
DriverThread(RacingThreadsTest test) {
super("DriverThread");
this.test = test;
}
private void run(WorkerThread[] workers) {
System.out.println(getName() + ": is starting.");
System.out.println(getName() + ": # WorkerThreads: " + test.N_THREADS);
System.out.println(getName() + ": max # loops: " + test.N_LOOPS);
System.out.println(getName() + ": max # secs: " + test.N_SECS);
// initialize 1-time items for the DriverThread
test.oneTimeDriverInit(this);
// start all the threads
for (int i = 0; i < workers.length; i++) {
workers[i].start();
}
// All WorkerThreads call oneTimeWorkerInit() and
// perRaceWorkerInit() on the way to startBarrier.
long endTime = System.currentTimeMillis() + test.N_SECS * 1000;
for (; !test.getDone() && test.getLoopCnt() < test.N_LOOPS;
test.incAndGetLoopCnt()) {
if (test.getVerbose() && (test.N_LOOPS < 10 ||
(test.getLoopCnt() % (test.N_LOOPS / 10)) == 0)) {
System.out.println(getName() + ": race loop #"
+ test.getLoopCnt());
}
// initialize per-race items for the DriverThread
test.perRaceDriverInit(this);
try {
// we've setup the race so start it when all
// WorkerThreads get to the startBarrier
test.startBarrier.await();
} catch (BrokenBarrierException bbe) {
test.unexpectedException(this, bbe);
return;
} catch (InterruptedException ie) {
test.unexpectedException(this, ie);
return;
}
// All WorkerThreads are racing via executeRace()
// at this point
// wait for all threads to finish the race
try {
test.finishBarrier.await();
} catch (BrokenBarrierException bbe) {
test.unexpectedException(this, bbe);
return;
} catch (InterruptedException ie) {
test.unexpectedException(this, ie);
return;
}
// All WorkerThreads are heading to resetBarrier at this
// point so we can check the race results before we reset
// for another race (or bail because we are done).
test.checkRaceResults(this);
if (test.getLoopCnt() + 1 >= test.N_LOOPS ||
System.currentTimeMillis() >= endTime) {
// This is the last loop or we're out of time.
// Let test threads know we are done before we release
// them from resetBarrier
test.setDone(true);
}
// release the WorkerThreads from resetBarrier
try {
test.resetBarrier.await();
} catch (BrokenBarrierException bbe) {
test.unexpectedException(this, bbe);
return;
} catch (InterruptedException ie) {
test.unexpectedException(this, ie);
return;
}
// All WorkerThreads call perRaceWorkerEpilog(). If
// this is not the last loop, then all WorkerThreads
// will also call perRaceWorkerInit() on the way to
// startBarrier. If this is the last loop, then all
// WorkerThreads will call oneTimeWorkerEpilog() on
// their way to ending.
// handle end-of-race items for the DriverThread
test.perRaceDriverEpilog(this);
}
System.out.println(getName() + ": completed " + test.getLoopCnt()
+ " race loops.");
if (test.getLoopCnt() < test.N_LOOPS) {
System.out.println(getName() + ": race stopped @ " + test.N_SECS
+ " seconds.");
}
for (int i = 0; i < workers.length; i++) {
try {
workers[i].join();
} catch (InterruptedException ie) {
test.unexpectedException(this, ie);
return;
}
}
// handle end-of-test items for the DriverThread
test.oneTimeDriverEpilog(this);
System.out.println(getName() + ": is done.");
}
}
/**
* WorkerThread for executing the race.
*/
public static class WorkerThread extends Thread {
private final RacingThreadsTest test;
private final int workerNum;
/**
* Creates WorkerThread-N that executes the test code. The
* WorkerThread class can be extended to provide test thread
* specific variables and/or code.
* @param workerNum the number for the new WorkerThread
* @parameter test the RacingThreadsTest being run
*/
WorkerThread(int workerNum, RacingThreadsTest test) {
super("WorkerThread-" + workerNum);
this.test = test;
this.workerNum = workerNum;
}
/**
* get the WorkerThread's number
* @return the WorkerThread's number
*/
public int getWorkerNum() {
return workerNum;
}
/**
* Run the race in a WorkerThread.
*/
public void run() {
System.out.println(getName() + ": is running.");
// initialize 1-time items for the WorkerThread
test.oneTimeWorkerInit(this);
while (!test.getDone()) {
// initialize per-race items for the WorkerThread
test.perRaceWorkerInit(this);
try {
test.startBarrier.await(); // wait for race to start
} catch (BrokenBarrierException bbe) {
test.unexpectedException(this, bbe);
return;
} catch (InterruptedException ie) {
test.unexpectedException(this, ie);
return;
}
// execute the race for the WorkerThread
test.executeRace(this);
try {
test.finishBarrier.await(); // this thread is done
} catch (BrokenBarrierException bbe) {
test.unexpectedException(this, bbe);
return;
} catch (InterruptedException ie) {
test.unexpectedException(this, ie);
return;
}
try {
test.resetBarrier.await(); // wait for race to reset
} catch (BrokenBarrierException bbe) {
test.unexpectedException(this, bbe);
return;
} catch (InterruptedException ie) {
test.unexpectedException(this, ie);
return;
}
// handle end-of-race items for the WorkerThread
test.perRaceWorkerEpilog(this);
}
// handle end-of-test items for the WorkerThread
test.oneTimeWorkerEpilog(this);
System.out.println(getName() + ": is ending.");
}
}
}
/* /*
* Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,8 @@ ...@@ -23,7 +23,8 @@
/** /**
* @test * @test
* @bug 4508341 * @bug 4508341 7055362
* @library ../../../java/security/testlibrary
* @summary Test the error conditions of * @summary Test the error conditions of
* EncryptedPrivateKeyInfo.getKeySpec(...) methods. * EncryptedPrivateKeyInfo.getKeySpec(...) methods.
* @author Valerie Peng * @author Valerie Peng
...@@ -97,7 +98,16 @@ public class GetKeySpecException { ...@@ -97,7 +98,16 @@ public class GetKeySpecException {
} }
} }
public static void main(String[] argv) throws Exception { public static void main(String[] args) throws Exception {
ProvidersSnapshot snapshot = ProvidersSnapshot.create();
try {
main0(args);
} finally {
snapshot.restore();
}
}
public static void main0(String[] args) throws Exception {
if ((GOOD_PARAMS == null) || (BAD_PARAMS == null)) { if ((GOOD_PARAMS == null) || (BAD_PARAMS == null)) {
throw new Exception("Static parameter generation failed"); throw new Exception("Static parameter generation failed");
} }
......
/* /*
* Copyright (c) 2006, 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,7 +23,8 @@ ...@@ -23,7 +23,8 @@
/* /*
* @test * @test
* @bug 6377058 * @bug 6377058 7055362
* @library ../../../java/security/testlibrary
* @summary SunJCE depends on sun.security.provider.SignatureImpl * @summary SunJCE depends on sun.security.provider.SignatureImpl
* behaviour, BC can't load into 1st slot. * behaviour, BC can't load into 1st slot.
* @author Brad R. Wetmore * @author Brad R. Wetmore
...@@ -35,7 +36,16 @@ import java.io.*; ...@@ -35,7 +36,16 @@ import java.io.*;
public class SunJCE_BC_LoadOrdering { public class SunJCE_BC_LoadOrdering {
public static void main(String args[]) throws Exception { public static void main(String[] args) throws Exception {
ProvidersSnapshot snapshot = ProvidersSnapshot.create();
try {
main0(args);
} finally {
snapshot.restore();
}
}
public static void main0(String[] args) throws Exception {
/* /*
* Generate a random key, and encrypt the data * Generate a random key, and encrypt the data
*/ */
......
#
# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# 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 7043737
# @summary klist does not detect non-existing keytab
# @run shell ktmissing.sh
#
OS=`uname -s`
case "$OS" in
CYGWIN* )
FS="/"
;;
Windows_* )
FS="\\"
;;
* )
FS="/"
echo "Unsupported system!"
exit 0;
;;
esac
${TESTJAVA}${FS}bin${FS}klist -k this_file_does_not_exist && exit 1
echo ABC > this_is_not_a_keytab
${TESTJAVA}${FS}bin${FS}klist -k this_is_not_a_keytab && exit 2
exit 0
/* /*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -25,10 +25,10 @@ ...@@ -25,10 +25,10 @@
* @test * @test
* @bug 6313675 6323647 * @bug 6313675 6323647
* @summary Verify that all ciphersuites work in FIPS mode * @summary Verify that all ciphersuites work in FIPS mode
* @library ..
* @ignore JSSE supported cipher suites are changed with CR 6916074, * @ignore JSSE supported cipher suites are changed with CR 6916074,
* need to update this test case in JDK 7 soon * need to update this test case in JDK 7 soon
* @author Andreas Sterbenz * @author Andreas Sterbenz
* @library ..
*/ */
import java.security.*; import java.security.*;
......
/*
* Copyright (c) 2001, 2003, Oracle and/or its affiliates. All rights reserved.
* 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 4393337
* @summary [TEST RUNS ON SOLARIS ONLY] Throw an InterruptedIOException
* when read on SSLSocket is * interrupted.
*/
import java.io.InputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.Socket;
import javax.net.ssl.*;
/**
* Interrupts an SSL socket that is blocked on a read. An
* InterruptedIOException will be thrown and handled within the test if the
* test completes correctly.
*/
public class InterruptedIO {
/**
* Starts a client and a server thread. Gives the client enough time to
* block in a read, then interrupts it.
*/
public static void main(String[] args) throws Exception {
String reason =
"Test valid only on SunOS.\n" +
"=========================\n" +
"It was determined that Thread.interrupt() could \n" +
"not be reliably return InterruptedIOException \n" +
"on non-Solaris implementations. Thread.interrupt() \n" +
"API was updated in merlin (JDK 1.4) to reflect this.\n";
System.out.println(reason);
String osName = System.getProperty("os.name", "");
if (!osName.equalsIgnoreCase("SunOS")) {
System.out.println("Ignoring test on '" + osName + "'");
return;
}
String testRoot = System.getProperty("test.src", ".");
System.setProperty("javax.net.ssl.keyStore",
testRoot +
"/../../../../../../../etc/keystore");
System.setProperty("javax.net.ssl.keyStorePassword",
"passphrase");
System.setProperty("javax.net.ssl.trustStore",
testRoot +
"/../../../../../../../etc/truststore");
Server server = new Server();
server.start();
Client client = new Client(server.getPort()); // Will do handshake
client.start(); // Will block in read
// sleep for 5 seconds
System.out.println("Main - Pausing for 5 seconds...");
Thread.sleep(5 * 1000);
System.out.println("Main - Interrupting client reader thread");
client.interrupt();
client.join(); // Wait for client thread to complete
if (client.failed())
throw new Exception("Main - Test InterruptedIO failed "
+ "on client side.");
else
System.out.println("Main - Test InterruptedIO successful!");
}
/**
* Accepts an incoming SSL Connection. Then blocks in a read.
*/
static class Server extends Thread {
private SSLServerSocket ss;
public Server() throws Exception {
ss = (SSLServerSocket) SSLServerSocketFactory.getDefault().
createServerSocket(0);
}
public int getPort() {
return ss.getLocalPort();
}
public void run() {
try {
System.out.println("Server - Will accept connections on port "
+ getPort());
Socket s = ss.accept();
InputStream is = s.getInputStream();
// We want the client to block so deadlock
is.read();
} catch (IOException e) {
// Happens when client closese connection.
// If an error occurs, Client will detect problem
}
}
}
/**
* Initiates an SSL connection to a server. Then blocks in a read. It
* should be interrupted by another thread. An InterruptedIOException
* is expected to be thrown.
*/
static class Client extends Thread {
private SSLSocket socket;
private InputStream inStream;
private boolean failed = false;
public Client(int port) throws Exception {
socket = (SSLSocket) SSLSocketFactory.getDefault().
createSocket("localhost", port);
inStream = socket.getInputStream();
System.out.println("Client - "
+ "Connected to: localhost" + ":" + port);
System.out.println("Client - "
+ "Doing SSL Handshake...");
socket.startHandshake(); // Asynchronous call
System.out.println("Client - Done with SSL Handshake");
}
public void run() {
try {
System.out.println("Client - Reading from input stream ...");
if (inStream.read() == -1) {
System.out.println("Client - End-of-stream detected");
failed = true;
}
} catch (InterruptedIOException e) {
System.out.println("Client - "
+ "As expected, InterruptedIOException "
+ "was thrown. Message: "
+ e.getMessage());
} catch (Exception e) {
System.out.println("Client - Unexpected exception:");
e.printStackTrace();
failed = true;
} finally {
try {
socket.close();
} catch (IOException e) {
// Squelch it
}
}
}
public boolean failed() {
return failed;
}
}
}
...@@ -299,8 +299,8 @@ public class ExecutionEnvironment { ...@@ -299,8 +299,8 @@ public class ExecutionEnvironment {
if (TestHelper.is32Bit) { if (TestHelper.is32Bit) {
tr = TestHelper.doExec(TestHelper.javaCmd, "-client", "-version"); tr = TestHelper.doExec(TestHelper.javaCmd, "-client", "-version");
if (!tr.matches("Java.*Client VM.*")) { if (!tr.matches(".*Client VM.*")) {
System.out.println("FAIL: the expected vm -client did launch"); System.out.println("FAIL: the expected vm -client did not launch");
System.out.println(tr); System.out.println(tr);
errors++; errors++;
} else { } else {
...@@ -308,8 +308,8 @@ public class ExecutionEnvironment { ...@@ -308,8 +308,8 @@ public class ExecutionEnvironment {
} }
} }
tr = TestHelper.doExec(TestHelper.javaCmd, "-server", "-version"); tr = TestHelper.doExec(TestHelper.javaCmd, "-server", "-version");
if (!tr.matches("Java.*Server VM.*")) { if (!tr.matches(".*Server VM.*")) {
System.out.println("FAIL: the expected vm -server did launch"); System.out.println("FAIL: the expected vm -server did not launch");
System.out.println(tr); System.out.println(tr);
errors++; errors++;
} else { } else {
......
...@@ -132,7 +132,7 @@ public class VersionCheck { ...@@ -132,7 +132,7 @@ public class VersionCheck {
StringBuilder out = new StringBuilder(); StringBuilder out = new StringBuilder();
// remove the HotSpot line // remove the HotSpot line
for (String x : alist) { for (String x : alist) {
if (!x.contains("HotSpot")) { if (!x.matches(".*Client.*VM.*|.*Server.*VM.*")) {
out = out.append(x + "\n"); out = out.append(x + "\n");
} }
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册