diff --git a/jdk/.hgtags b/jdk/.hgtags index e6027fc4c5b..fe87fc38b47 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -389,3 +389,4 @@ e93b7ea559759f036c9f69fd2ddaf47bb4e98385 jdk-9+140 efa71dc820eb8bd5a6c9f2f66f39c383ac3ee99d jdk-9+144 99b7853cfbd8227c4441de4b6119c10742556840 jdk-9+145 6e4ff59afb5d0adf21a72c4ff534326594a99e5d jdk-9+146 +c41140100bf1e5c10c7b8f3bde91c16eff7485f5 jdk-9+147 diff --git a/jdk/make/lib/Awt2dLibraries.gmk b/jdk/make/lib/Awt2dLibraries.gmk index d522a30812f..09423e4d770 100644 --- a/jdk/make/lib/Awt2dLibraries.gmk +++ b/jdk/make/lib/Awt2dLibraries.gmk @@ -395,7 +395,7 @@ LCMS_CFLAGS=-DCMS_DONT_USE_FAST_FLOOR ifeq ($(USE_EXTERNAL_LCMS), true) # If we're using an external library, we'll just need the wrapper part. - # By including it explicitely, all other files will be excluded. + # By including it explicitly, all other files will be excluded. BUILD_LIBLCMS_INCLUDE_FILES := LCMS.c else BUILD_LIBLCMS_INCLUDE_FILES := diff --git a/jdk/make/lib/CoreLibraries.gmk b/jdk/make/lib/CoreLibraries.gmk index 345c4253389..27dad3553ee 100644 --- a/jdk/make/lib/CoreLibraries.gmk +++ b/jdk/make/lib/CoreLibraries.gmk @@ -33,10 +33,22 @@ $(eval $(call IncludeCustomExtension, jdk, lib/CoreLibraries.gmk)) # libfdlibm is statically linked with libjava below and not delivered into the # product on its own. -BUILD_LIBFDLIBM_OPTIMIZATION := HIGH +BUILD_LIBFDLIBM_OPTIMIZATION := NONE -ifneq ($(OPENJDK_TARGET_OS), solaris) - BUILD_LIBFDLIBM_OPTIMIZATION := NONE +ifeq ($(OPENJDK_TARGET_OS), solaris) + BUILD_LIBFDLIBM_OPTIMIZATION := HIGH +endif + +ifeq ($(OPENJDK_TARGET_OS), linux) + ifeq ($(OPENJDK_TARGET_CPU), ppc64) + BUILD_LIBFDLIBM_OPTIMIZATION := HIGH + else ifeq ($(OPENJDK_TARGET_CPU), ppc64le) + BUILD_LIBFDLIBM_OPTIMIZATION := HIGH + else ifeq ($(OPENJDK_TARGET_CPU), s390x) + BUILD_LIBFDLIBM_OPTIMIZATION := HIGH + else ifeq ($(OPENJDK_TARGET_CPU), aarch64) + BUILD_LIBFDLIBM_OPTIMIZATION := HIGH + endif endif LIBFDLIBM_SRC := $(JDK_TOPDIR)/src/java.base/share/native/libfdlibm @@ -51,6 +63,10 @@ ifneq ($(OPENJDK_TARGET_OS), macosx) CFLAGS := $(CFLAGS_JDKLIB) $(LIBFDLIBM_CFLAGS), \ CFLAGS_windows_debug := -DLOGGING, \ CFLAGS_aix := -qfloat=nomaf, \ + CFLAGS_linux_ppc64 := -ffp-contract=off, \ + CFLAGS_linux_ppc64le := -ffp-contract=off, \ + CFLAGS_linux_s390x := -ffp-contract=off, \ + CFLAGS_linux_aarch64 := -ffp-contract=off, \ DISABLED_WARNINGS_gcc := sign-compare, \ DISABLED_WARNINGS_microsoft := 4146 4244 4018, \ ARFLAGS := $(ARFLAGS), \ diff --git a/jdk/make/src/classes/build/tools/module/GenModuleInfoSource.java b/jdk/make/src/classes/build/tools/module/GenModuleInfoSource.java index 368fcc7271a..60d0b6e3132 100644 --- a/jdk/make/src/classes/build/tools/module/GenModuleInfoSource.java +++ b/jdk/make/src/classes/build/tools/module/GenModuleInfoSource.java @@ -146,9 +146,10 @@ public class GenModuleInfoSource { for (String l : lines) { writer.println(l); if (l.trim().startsWith("module ")) { - writer.format(" // source file: %s%n", sourceFile); + // print URI rather than file path to avoid escape + writer.format(" // source file: %s%n", sourceFile.toUri()); for (Path file: extraFiles) { - writer.format(" // %s%n", file); + writer.format(" // %s%n", file.toUri()); } break; } diff --git a/jdk/src/java.base/macosx/classes/sun/util/locale/provider/HostLocaleProviderAdapterImpl.java b/jdk/src/java.base/macosx/classes/sun/util/locale/provider/HostLocaleProviderAdapterImpl.java index 9fbf1f03776..a3b91bd1cc2 100644 --- a/jdk/src/java.base/macosx/classes/sun/util/locale/provider/HostLocaleProviderAdapterImpl.java +++ b/jdk/src/java.base/macosx/classes/sun/util/locale/provider/HostLocaleProviderAdapterImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,6 +47,7 @@ import java.util.spi.CalendarNameProvider; import java.util.spi.CurrencyNameProvider; import java.util.spi.LocaleNameProvider; import java.util.spi.TimeZoneNameProvider; +import sun.text.spi.JavaTimeDateTimePatternProvider; import sun.util.spi.CalendarProvider; /** @@ -147,6 +148,165 @@ public class HostLocaleProviderAdapterImpl { return Locale.forLanguageTag(langTag); } + public static JavaTimeDateTimePatternProvider getJavaTimeDateTimePatternProvider() { + return new JavaTimeDateTimePatternProvider() { + @Override + public Locale[] getAvailableLocales() { + return getSupportedCalendarLocales(); + } + + @Override + public boolean isSupportedLocale(Locale locale) { + return isSupportedCalendarLocale(locale); + } + + @Override + public String getJavaTimeDateTimePattern(int timeStyle, int dateStyle, String calType, Locale locale) { + return toJavaTimeDateTimePattern(calType, getDateTimePattern(dateStyle, timeStyle, locale)); + + } + + private String getDateTimePattern(int dateStyle, int timeStyle, Locale locale) { + AtomicReferenceArray dateFormatPatterns; + SoftReference> ref = dateFormatPatternsMap.get(locale); + + if (ref == null || (dateFormatPatterns = ref.get()) == null) { + dateFormatPatterns = new AtomicReferenceArray<>(5 * 5); + ref = new SoftReference<>(dateFormatPatterns); + dateFormatPatternsMap.put(locale, ref); + } + int index = (dateStyle + 1) * 5 + timeStyle + 1; + String pattern = dateFormatPatterns.get(index); + if (pattern == null) { + String langTag = locale.toLanguageTag(); + pattern = translateDateFormatLetters(getCalendarID(langTag), + getDateTimePatternNative(dateStyle, timeStyle, langTag)); + if (!dateFormatPatterns.compareAndSet(index, null, pattern)) { + pattern = dateFormatPatterns.get(index); + } + } + return pattern; + } + + /** + * This method will convert JRE Date/time Pattern String to JSR310 + * type Date/Time Pattern + */ + private String toJavaTimeDateTimePattern(String calendarType, String jrePattern) { + int length = jrePattern.length(); + StringBuilder sb = new StringBuilder(length); + boolean inQuote = false; + int count = 0; + char lastLetter = 0; + for (int i = 0; i < length; i++) { + char c = jrePattern.charAt(i); + if (c == '\'') { + // '' is treated as a single quote regardless of being + // in a quoted section. + if ((i + 1) < length) { + char nextc = jrePattern.charAt(i + 1); + if (nextc == '\'') { + i++; + if (count != 0) { + convert(calendarType, lastLetter, count, sb); + lastLetter = 0; + count = 0; + } + sb.append("''"); + continue; + } + } + if (!inQuote) { + if (count != 0) { + convert(calendarType, lastLetter, count, sb); + lastLetter = 0; + count = 0; + } + inQuote = true; + } else { + inQuote = false; + } + sb.append(c); + continue; + } + if (inQuote) { + sb.append(c); + continue; + } + if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) { + if (count != 0) { + convert(calendarType, lastLetter, count, sb); + lastLetter = 0; + count = 0; + } + sb.append(c); + continue; + } + if (lastLetter == 0 || lastLetter == c) { + lastLetter = c; + count++; + continue; + } + convert(calendarType, lastLetter, count, sb); + lastLetter = c; + count = 1; + } + if (inQuote) { + // should not come here. + // returning null so that FALLBACK provider will kick in. + return null; + } + if (count != 0) { + convert(calendarType, lastLetter, count, sb); + } + return sb.toString(); + } + + private void convert(String calendarType, char letter, int count, StringBuilder sb) { + switch (letter) { + case 'G': + if (calendarType.equals("japanese")) { + if (count >= 4) { + count = 1; + } else { + count = 5; + } + } else if (!calendarType.equals("iso8601")) { + // Gregorian calendar is iso8601 for java.time + // Adjust the number of 'G's + if (count >= 4) { + // JRE full -> JavaTime full + count = 4; + } else { + // JRE short -> JavaTime short + count = 1; + } + } + break; + case 'y': + if (calendarType.equals("japanese") && count >= 4) { + // JRE specific "gan-nen" support + count = 1; + } + break; + default: + // JSR 310 and CLDR define 5-letter patterns for narrow text. + if (count > 4) { + count = 4; + } + break; + } + appendN(letter, count, sb); + } + + private void appendN(char c, int n, StringBuilder sb) { + for (int i = 0; i < n; i++) { + sb.append(c); + } + } + }; + } + public static DateFormatProvider getDateFormatProvider() { return new DateFormatProvider() { @@ -163,20 +323,20 @@ public class HostLocaleProviderAdapterImpl { @Override public DateFormat getDateInstance(int style, Locale locale) { return new SimpleDateFormat(getDateTimePattern(style, -1, locale), - getCalendarLocale(locale)); + getCalendarLocale(locale)); } @Override public DateFormat getTimeInstance(int style, Locale locale) { return new SimpleDateFormat(getDateTimePattern(-1, style, locale), - getCalendarLocale(locale)); + getCalendarLocale(locale)); } @Override public DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale locale) { return new SimpleDateFormat(getDateTimePattern(dateStyle, timeStyle, locale), - getCalendarLocale(locale)); + getCalendarLocale(locale)); } private String getDateTimePattern(int dateStyle, int timeStyle, Locale locale) { diff --git a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java index 09b1060eab0..7ae757fe6f2 100644 --- a/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java +++ b/jdk/src/java.base/share/classes/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnectionOldImpl.java @@ -39,6 +39,7 @@ import java.net.URL; import java.net.Proxy; import java.net.ProtocolException; import java.io.*; +import java.net.Authenticator; import javax.net.ssl.*; import java.security.Permission; import java.util.Map; @@ -489,4 +490,9 @@ public class HttpsURLConnectionOldImpl public void setChunkedStreamingMode (int chunklen) { delegate.setChunkedStreamingMode(chunklen); } + + @Override + public void setAuthenticator(Authenticator auth) { + delegate.setAuthenticator(auth); + } } diff --git a/jdk/src/java.base/share/classes/java/io/FilePermission.java b/jdk/src/java.base/share/classes/java/io/FilePermission.java index 34f3d522242..c3d51135905 100644 --- a/jdk/src/java.base/share/classes/java/io/FilePermission.java +++ b/jdk/src/java.base/share/classes/java/io/FilePermission.java @@ -1077,7 +1077,10 @@ final class FilePermissionCollection extends PermissionCollection // Add permission to map if it is absent, or replace with new // permission if applicable. perms.merge(fp.getName(), fp, - (existingVal, newVal) -> { + new java.util.function.BiFunction<>() { + @Override + public Permission apply(Permission existingVal, + Permission newVal) { int oldMask = ((FilePermission)existingVal).getMask(); int newMask = ((FilePermission)newVal).getMask(); if (oldMask != newMask) { @@ -1092,6 +1095,7 @@ final class FilePermissionCollection extends PermissionCollection } return existingVal; } + } ); } diff --git a/jdk/src/java.base/share/classes/java/lang/AbstractStringBuilder.java b/jdk/src/java.base/share/classes/java/lang/AbstractStringBuilder.java index 2aa9ff36a7f..f9c8eea6c89 100644 --- a/jdk/src/java.base/share/classes/java/lang/AbstractStringBuilder.java +++ b/jdk/src/java.base/share/classes/java/lang/AbstractStringBuilder.java @@ -1553,13 +1553,20 @@ abstract class AbstractStringBuilder implements Appendable, CharSequence { */ @Override public IntStream chars() { - byte[] val = this.value; int count = this.count; byte coder = this.coder; - checkOffset(count, val.length >> coder); // Reuse String-based spliterator. This requires a supplier to // capture the value and count when the terminal operation is executed return StreamSupport.intStream( - () -> coder == LATIN1 ? new StringLatin1.CharsSpliterator(val, 0, count, 0) - : new StringUTF16.CharsSpliterator(val, 0, count, 0), + () -> { + // The combined set of field reads are not atomic and thread + // safe but bounds checks will ensure no unsafe reads from + // the byte array + byte[] val = this.value; + int count = this.count; + byte coder = this.coder; + return coder == LATIN1 + ? new StringLatin1.CharsSpliterator(val, 0, count, 0) + : new StringUTF16.CharsSpliterator(val, 0, count, 0); + }, Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED, false); } @@ -1570,13 +1577,20 @@ abstract class AbstractStringBuilder implements Appendable, CharSequence { */ @Override public IntStream codePoints() { - byte[] val = this.value; int count = this.count; byte coder = this.coder; - checkOffset(count, val.length >> coder); // Reuse String-based spliterator. This requires a supplier to // capture the value and count when the terminal operation is executed return StreamSupport.intStream( - () -> coder == LATIN1 ? new StringLatin1.CharsSpliterator(val, 0, count, 0) - : new StringUTF16.CodePointsSpliterator(val, 0, count, 0), + () -> { + // The combined set of field reads are not atomic and thread + // safe but bounds checks will ensure no unsafe reads from + // the byte array + byte[] val = this.value; + int count = this.count; + byte coder = this.coder; + return coder == LATIN1 + ? new StringLatin1.CharsSpliterator(val, 0, count, 0) + : new StringUTF16.CodePointsSpliterator(val, 0, count, 0); + }, Spliterator.ORDERED, false); } diff --git a/jdk/src/java.base/share/classes/java/lang/StringUTF16.java b/jdk/src/java.base/share/classes/java/lang/StringUTF16.java index 600bdd45154..2c0dd917a8f 100644 --- a/jdk/src/java.base/share/classes/java/lang/StringUTF16.java +++ b/jdk/src/java.base/share/classes/java/lang/StringUTF16.java @@ -811,7 +811,9 @@ final class StringUTF16 { throw new NullPointerException(); if (((a = array).length >> 1) >= (hi = fence) && (i = index) >= 0 && i < (index = hi)) { - do { action.accept(getChar(a, i)); } while (++i < hi); + do { + action.accept(charAt(a, i)); + } while (++i < hi); } } @@ -819,8 +821,10 @@ final class StringUTF16 { public boolean tryAdvance(IntConsumer action) { if (action == null) throw new NullPointerException(); - if (index >= 0 && index < fence) { - action.accept(getChar(array, index++)); + int i = index; + if (i >= 0 && i < fence) { + action.accept(charAt(array, i)); + index++; return true; } return false; @@ -860,8 +864,8 @@ final class StringUTF16 { int midOneLess; // If the mid-point intersects a surrogate pair - if (Character.isLowSurrogate(getChar(array, mid)) && - Character.isHighSurrogate(getChar(array, midOneLess = (mid -1)))) { + if (Character.isLowSurrogate(charAt(array, mid)) && + Character.isHighSurrogate(charAt(array, midOneLess = (mid -1)))) { // If there is only one pair it cannot be split if (lo >= midOneLess) return null; @@ -898,10 +902,10 @@ final class StringUTF16 { // Advance one code point from the index, i, and return the next // index to advance from private static int advance(byte[] a, int i, int hi, IntConsumer action) { - char c1 = getChar(a, i++); + char c1 = charAt(a, i++); int cp = c1; if (Character.isHighSurrogate(c1) && i < hi) { - char c2 = getChar(a, i); + char c2 = charAt(a, i); if (Character.isLowSurrogate(c2)) { i++; cp = Character.toCodePoint(c1, c2); diff --git a/jdk/src/java.base/share/classes/java/net/Authenticator.java b/jdk/src/java.base/share/classes/java/net/Authenticator.java index 81a87c79987..16af2845c8c 100644 --- a/jdk/src/java.base/share/classes/java/net/Authenticator.java +++ b/jdk/src/java.base/share/classes/java/net/Authenticator.java @@ -25,6 +25,8 @@ package java.net; +import sun.net.www.protocol.http.AuthenticatorKeys; + /** * The class Authenticator represents an object that knows how to obtain * authentication for a network connection. Usually, it will do this @@ -70,6 +72,7 @@ class Authenticator { private String requestingScheme; private URL requestingURL; private RequestorType requestingAuthType; + private final String key = AuthenticatorKeys.computeKey(this); /** * The type of the entity requesting authentication. @@ -348,6 +351,75 @@ class Authenticator { } } + /** + * Ask the given {@code authenticator} for a password. If the given + * {@code authenticator} is null, the authenticator, if any, that has been + * registered with the system using {@link #setDefault(java.net.Authenticator) + * setDefault} is used. + *

+ * First, if there is a security manager, its {@code checkPermission} + * method is called with a + * {@code NetPermission("requestPasswordAuthentication")} permission. + * This may result in a java.lang.SecurityException. + * + * @param authenticator the authenticator, or {@code null}. + * @param host The hostname of the site requesting authentication. + * @param addr The InetAddress of the site requesting authorization, + * or null if not known. + * @param port the port for the requested connection + * @param protocol The protocol that's requesting the connection + * ({@link java.net.Authenticator#getRequestingProtocol()}) + * @param prompt A prompt string for the user + * @param scheme The authentication scheme + * @param url The requesting URL that caused the authentication + * @param reqType The type (server or proxy) of the entity requesting + * authentication. + * + * @return The username/password, or {@code null} if one can't be gotten. + * + * @throws SecurityException + * if a security manager exists and its + * {@code checkPermission} method doesn't allow + * the password authentication request. + * + * @see SecurityManager#checkPermission + * @see java.net.NetPermission + * + * @since 9 + */ + public static PasswordAuthentication requestPasswordAuthentication( + Authenticator authenticator, + String host, + InetAddress addr, + int port, + String protocol, + String prompt, + String scheme, + URL url, + RequestorType reqType) { + + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + NetPermission requestPermission + = new NetPermission("requestPasswordAuthentication"); + sm.checkPermission(requestPermission); + } + + Authenticator a = authenticator == null ? theAuthenticator : authenticator; + if (a == null) { + return null; + } else { + return a.requestPasswordAuthenticationInstance(host, + addr, + port, + protocol, + prompt, + scheme, + url, + reqType); + } + } + /** * Ask this authenticator for a password. * @@ -493,4 +565,11 @@ class Authenticator { protected RequestorType getRequestorType () { return requestingAuthType; } + + static String getKey(Authenticator a) { + return a.key; + } + static { + AuthenticatorKeys.setAuthenticatorKeyAccess(Authenticator::getKey); + } } diff --git a/jdk/src/java.base/share/classes/java/net/HttpURLConnection.java b/jdk/src/java.base/share/classes/java/net/HttpURLConnection.java index 94b537d2658..9e428e59584 100644 --- a/jdk/src/java.base/share/classes/java/net/HttpURLConnection.java +++ b/jdk/src/java.base/share/classes/java/net/HttpURLConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -102,6 +102,53 @@ public abstract class HttpURLConnection extends URLConnection { */ protected long fixedContentLengthLong = -1; + /** + * Supplies an {@link java.net.Authenticator Authenticator} to be used + * when authentication is requested through the HTTP protocol for + * this {@code HttpURLConnection}. + * If no authenticator is supplied, the + * {@linkplain Authenticator#setDefault(java.net.Authenticator) default + * authenticator} will be used. + * + * @implSpec The default behavior of this method is to unconditionally + * throw {@link UnsupportedOperationException}. Concrete + * implementations of {@code HttpURLConnection} + * which support supplying an {@code Authenticator} for a + * specific {@code HttpURLConnection} instance should + * override this method to implement a different behavior. + * + * @implNote Depending on authentication schemes, an implementation + * may or may not need to use the provided authenticator + * to obtain a password. For instance, an implementation that + * relies on third-party security libraries may still invoke the + * default authenticator if these libraries are configured + * to do so. + * Likewise, an implementation that supports transparent + * NTLM authentication may let the system attempt + * to connect using the system user credentials first, + * before invoking the provided authenticator. + *
+ * However, if an authenticator is specifically provided, + * then the underlying connection may only be reused for + * {@code HttpURLConnection} instances which share the same + * {@code Authenticator} instance, and authentication information, + * if cached, may only be reused for an {@code HttpURLConnection} + * sharing that same {@code Authenticator}. + * + * @param auth The {@code Authenticator} that should be used by this + * {@code HttpURLConnection}. + * + * @throws UnsupportedOperationException if setting an Authenticator is + * not supported by the underlying implementation. + * @throws IllegalStateException if URLConnection is already connected. + * @throws NullPointerException if the supplied {@code auth} is {@code null}. + * @since 9 + */ + public void setAuthenticator(Authenticator auth) { + throw new UnsupportedOperationException("Supplying an authenticator" + + " is not supported by " + this.getClass()); + } + /** * Returns the key for the {@code n}th header field. * Some implementations may treat the {@code 0}th diff --git a/jdk/src/java.base/share/classes/java/net/URLClassLoader.java b/jdk/src/java.base/share/classes/java/net/URLClassLoader.java index 602f9d7f61a..57f45027ea2 100644 --- a/jdk/src/java.base/share/classes/java/net/URLClassLoader.java +++ b/jdk/src/java.base/share/classes/java/net/URLClassLoader.java @@ -72,6 +72,10 @@ import sun.security.util.SecurityConstants; *

* The classes that are loaded are by default granted permission only to * access the URLs specified when the URLClassLoader was created. + *

+ * This class loader supports the loading of classes from the contents of a + * multi-release JAR file + * that is referred to by a given URL. * * @author David Connelly * @since 1.2 diff --git a/jdk/src/java.base/share/classes/java/time/format/DateTimeFormatterBuilder.java b/jdk/src/java.base/share/classes/java/time/format/DateTimeFormatterBuilder.java index 9beb6955c0c..0e6eb066fd3 100644 --- a/jdk/src/java.base/share/classes/java/time/format/DateTimeFormatterBuilder.java +++ b/jdk/src/java.base/share/classes/java/time/format/DateTimeFormatterBuilder.java @@ -119,6 +119,7 @@ import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import sun.text.spi.JavaTimeDateTimePatternProvider; import sun.util.locale.provider.LocaleProviderAdapter; import sun.util.locale.provider.LocaleResources; import sun.util.locale.provider.TimeZoneNameUtility; @@ -212,9 +213,10 @@ public final class DateTimeFormatterBuilder { if (dateStyle == null && timeStyle == null) { throw new IllegalArgumentException("Either dateStyle or timeStyle must be non-null"); } - LocaleResources lr = LocaleProviderAdapter.getResourceBundleBased().getLocaleResources(locale); - String pattern = lr.getJavaTimeDateTimePattern( - convertStyle(timeStyle), convertStyle(dateStyle), chrono.getCalendarType()); + LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(JavaTimeDateTimePatternProvider.class, locale); + JavaTimeDateTimePatternProvider provider = adapter.getJavaTimeDateTimePatternProvider(); + String pattern = provider.getJavaTimeDateTimePattern(convertStyle(timeStyle), + convertStyle(dateStyle), chrono.getCalendarType(), locale); return pattern; } diff --git a/jdk/src/java.base/share/classes/java/util/jar/JarFile.java b/jdk/src/java.base/share/classes/java/util/jar/JarFile.java index abf4b2fefab..ba072d7aa5d 100644 --- a/jdk/src/java.base/share/classes/java/util/jar/JarFile.java +++ b/jdk/src/java.base/share/classes/java/util/jar/JarFile.java @@ -48,8 +48,8 @@ import sun.security.util.SignatureFileVerifier; * processing multi-release jar files. The {@code Manifest} can be used * to specify meta-information about the jar file and its entries. * - *

A multi-release jar file is a jar file that contains - * a manifest with a main attribute named "Multi-Release", + *

A multi-release jar file is a jar file that + * contains a manifest with a main attribute named "Multi-Release", * a set of "base" entries, some of which are public classes with public * or protected methods that comprise the public interface of the jar file, * and a set of "versioned" entries contained in subdirectories of the diff --git a/jdk/src/java.base/share/classes/module-info.java b/jdk/src/java.base/share/classes/module-info.java index 0d6402fe7d2..ab4e031d507 100644 --- a/jdk/src/java.base/share/classes/module-info.java +++ b/jdk/src/java.base/share/classes/module-info.java @@ -305,6 +305,7 @@ module java.base { uses jdk.internal.logger.DefaultLoggerFinder; uses sun.security.ssl.ClientKeyExchangeService; uses sun.security.util.AuthResourcesProvider; + uses sun.text.spi.JavaTimeDateTimePatternProvider; uses sun.util.spi.CalendarProvider; uses sun.util.locale.provider.LocaleDataMetaInfo; uses sun.util.resources.LocaleData.CommonResourceBundleProvider; diff --git a/jdk/src/java.base/share/classes/sun/net/www/http/HttpClient.java b/jdk/src/java.base/share/classes/sun/net/www/http/HttpClient.java index 580842b2faf..9237d37a354 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/http/HttpClient.java +++ b/jdk/src/java.base/share/classes/sun/net/www/http/HttpClient.java @@ -28,6 +28,7 @@ package sun.net.www.http; import java.io.*; import java.net.*; import java.util.Locale; +import java.util.Objects; import java.util.Properties; import sun.net.NetworkClient; import sun.net.ProgressSource; @@ -35,6 +36,7 @@ import sun.net.www.MessageHeader; import sun.net.www.HeaderParser; import sun.net.www.MeteredStream; import sun.net.www.ParseUtil; +import sun.net.www.protocol.http.AuthenticatorKeys; import sun.net.www.protocol.http.HttpURLConnection; import sun.util.logging.PlatformLogger; import static sun.net.www.protocol.http.HttpURLConnection.TunnelState.*; @@ -132,6 +134,8 @@ public class HttpClient extends NetworkClient { } } + protected volatile String authenticatorKey; + /** * A NOP method kept for backwards binary compatibility * @deprecated -- system properties are no longer cached. @@ -279,10 +283,12 @@ public class HttpClient extends NetworkClient { ret = null; } } - if (ret != null) { - if ((ret.proxy != null && ret.proxy.equals(p)) || - (ret.proxy == null && p == null)) { + String ak = httpuc == null ? AuthenticatorKeys.DEFAULT + : httpuc.getAuthenticatorKey(); + boolean compatible = Objects.equals(ret.proxy, p) + && Objects.equals(ret.getAuthenticatorKey(), ak); + if (compatible) { synchronized (ret) { ret.cachedHttpClient = true; assert ret.inCache; @@ -306,6 +312,9 @@ public class HttpClient extends NetworkClient { } if (ret == null) { ret = new HttpClient(url, p, to); + if (httpuc != null) { + ret.authenticatorKey = httpuc.getAuthenticatorKey(); + } } else { SecurityManager security = System.getSecurityManager(); if (security != null) { @@ -341,6 +350,12 @@ public class HttpClient extends NetworkClient { to, useCache, httpuc); } + public final String getAuthenticatorKey() { + String k = authenticatorKey; + if (k == null) return AuthenticatorKeys.DEFAULT; + return k; + } + /* return it to the cache as still usable, if: * 1) It's keeping alive, AND * 2) It still has some connections left, AND diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthCache.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthCache.java index 6af6dd6e2bf..5ca44fa64e6 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthCache.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthCache.java @@ -38,7 +38,8 @@ public interface AuthCache { /** * Put an entry in the cache. pkey is a string specified as follows: * - * A:[B:]C:D:E[:F] Between 4 and 6 fields separated by ":" + * A:[B:]C:D:E[:F][;key=value] Between 4 and 6 fields separated by ":", + * and an optional semicolon-separated key=value list postfix, * where the fields have the following meaning: * A is "s" or "p" for server or proxy authentication respectively * B is optional and is the {@link AuthScheme}, e.g. BASIC, DIGEST, NTLM, etc @@ -47,6 +48,11 @@ public interface AuthCache { * E is the port number * F is optional and if present is the realm * + * The semi-colon separated key=value list postfix can be used to + * provide additional contextual information, thus allowing + * to separate AuthCacheValue instances obtained from different + * contexts. + * * Generally, two entries are created for each AuthCacheValue, * one including the realm and one without the realm. * Also, for some schemes (digest) multiple entries may be created diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java index 487e17ecd37..7d0dae92a8a 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ import java.io.ObjectInputStream; import java.net.PasswordAuthentication; import java.net.URL; import java.util.HashMap; +import java.util.Objects; import sun.net.www.HeaderParser; @@ -190,8 +191,18 @@ public abstract class AuthenticationInfo extends AuthCacheValue implements Clone /** The shortest path from the URL we authenticated against. */ String path; + /** + * A key identifying the authenticator from which the credentials + * were obtained. + * {@link AuthenticatorKeys#DEFAULT} identifies the {@linkplain + * java.net.Authenticator#setDefault(java.net.Authenticator) default} + * authenticator. + */ + String authenticatorKey; + /** Use this constructor only for proxy entries */ - public AuthenticationInfo(char type, AuthScheme authScheme, String host, int port, String realm) { + public AuthenticationInfo(char type, AuthScheme authScheme, String host, + int port, String realm, String authenticatorKey) { this.type = type; this.authScheme = authScheme; this.protocol = ""; @@ -199,6 +210,7 @@ public abstract class AuthenticationInfo extends AuthCacheValue implements Clone this.port = port; this.realm = realm; this.path = null; + this.authenticatorKey = Objects.requireNonNull(authenticatorKey); } public Object clone() { @@ -214,7 +226,8 @@ public abstract class AuthenticationInfo extends AuthCacheValue implements Clone * Constructor used to limit the authorization to the path within * the URL. Use this constructor for origin server entries. */ - public AuthenticationInfo(char type, AuthScheme authScheme, URL url, String realm) { + public AuthenticationInfo(char type, AuthScheme authScheme, URL url, String realm, + String authenticatorKey) { this.type = type; this.authScheme = authScheme; this.protocol = url.getProtocol().toLowerCase(); @@ -231,7 +244,16 @@ public abstract class AuthenticationInfo extends AuthCacheValue implements Clone else { this.path = reducePath (urlPath); } + this.authenticatorKey = Objects.requireNonNull(authenticatorKey); + } + /** + * The {@linkplain java.net.Authenticator#getKey(java.net.Authenticator) key} + * of the authenticator that was used to obtain the credentials. + * @return The authenticator's key. + */ + public final String getAuthenticatorKey() { + return authenticatorKey; } /* @@ -256,13 +278,14 @@ public abstract class AuthenticationInfo extends AuthCacheValue implements Clone * don't yet know the realm * (i.e. when we're preemptively setting the auth). */ - static AuthenticationInfo getServerAuth(URL url) { + static AuthenticationInfo getServerAuth(URL url, String authenticatorKey) { int port = url.getPort(); if (port == -1) { port = url.getDefaultPort(); } String key = SERVER_AUTHENTICATION + ":" + url.getProtocol().toLowerCase() - + ":" + url.getHost().toLowerCase() + ":" + port; + + ":" + url.getHost().toLowerCase() + ":" + port + + ";auth=" + authenticatorKey; return getAuth(key, url); } @@ -272,13 +295,17 @@ public abstract class AuthenticationInfo extends AuthCacheValue implements Clone * In this case we do not use the path because the protection space * is identified by the host:port:realm only */ - static String getServerAuthKey(URL url, String realm, AuthScheme scheme) { + static String getServerAuthKey(URL url, String realm, AuthScheme scheme, + String authenticatorKey) { int port = url.getPort(); if (port == -1) { port = url.getDefaultPort(); } - String key = SERVER_AUTHENTICATION + ":" + scheme + ":" + url.getProtocol().toLowerCase() - + ":" + url.getHost().toLowerCase() + ":" + port + ":" + realm; + String key = SERVER_AUTHENTICATION + ":" + scheme + ":" + + url.getProtocol().toLowerCase() + + ":" + url.getHost().toLowerCase() + + ":" + port + ":" + realm + + ";auth=" + authenticatorKey; return key; } @@ -309,8 +336,10 @@ public abstract class AuthenticationInfo extends AuthCacheValue implements Clone * for preemptive header-setting. Note, the protocol field is always * blank for proxies. */ - static AuthenticationInfo getProxyAuth(String host, int port) { - String key = PROXY_AUTHENTICATION + "::" + host.toLowerCase() + ":" + port; + static AuthenticationInfo getProxyAuth(String host, int port, + String authenticatorKey) { + String key = PROXY_AUTHENTICATION + "::" + host.toLowerCase() + ":" + port + + ";auth=" + authenticatorKey; AuthenticationInfo result = (AuthenticationInfo) cache.get(key, null); return result; } @@ -320,9 +349,12 @@ public abstract class AuthenticationInfo extends AuthCacheValue implements Clone * Used in response to a challenge. Note, the protocol field is always * blank for proxies. */ - static String getProxyAuthKey(String host, int port, String realm, AuthScheme scheme) { - String key = PROXY_AUTHENTICATION + ":" + scheme + "::" + host.toLowerCase() - + ":" + port + ":" + realm; + static String getProxyAuthKey(String host, int port, String realm, + AuthScheme scheme, String authenticatorKey) { + String key = PROXY_AUTHENTICATION + ":" + scheme + + "::" + host.toLowerCase() + + ":" + port + ":" + realm + + ";auth=" + authenticatorKey; return key; } @@ -424,27 +456,34 @@ public abstract class AuthenticationInfo extends AuthCacheValue implements Clone String cacheKey(boolean includeRealm) { // This must be kept in sync with the getXXXAuth() methods in this // class. + String authenticatorKey = getAuthenticatorKey(); if (includeRealm) { return type + ":" + authScheme + ":" + protocol + ":" - + host + ":" + port + ":" + realm; + + host + ":" + port + ":" + realm + + ";auth=" + authenticatorKey; } else { - return type + ":" + protocol + ":" + host + ":" + port; + return type + ":" + protocol + ":" + host + ":" + port + + ";auth=" + authenticatorKey; } } String s1, s2; /* used for serialization of pw */ - private void readObject(ObjectInputStream s) + private synchronized void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject (); pw = new PasswordAuthentication (s1, s2.toCharArray()); s1 = null; s2= null; + if (authenticatorKey == null) { + authenticatorKey = AuthenticatorKeys.DEFAULT; + } } private synchronized void writeObject(java.io.ObjectOutputStream s) throws IOException { + Objects.requireNonNull(authenticatorKey); s1 = pw.getUserName(); s2 = new String (pw.getPassword()); s.defaultWriteObject (); diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticatorKeys.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticatorKeys.java new file mode 100644 index 00000000000..3ae256ca50f --- /dev/null +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/AuthenticatorKeys.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. 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.net.www.protocol.http; + +import java.net.Authenticator; +import java.util.concurrent.atomic.AtomicLong; + +/** + * A class used to tie a key to an authenticator instance. + */ +public final class AuthenticatorKeys { + private AuthenticatorKeys() { + throw new InternalError("Trying to instantiate static class"); + } + + public static final String DEFAULT = "default"; + private static final AtomicLong IDS = new AtomicLong(); + + public static String computeKey(Authenticator a) { + return System.identityHashCode(a) + "-" + IDS.incrementAndGet() + + "@" + a.getClass().getName(); + } + + /** + * Returns a key for the given authenticator. + * + * @param authenticator The authenticator; {@code null} should be + * passed when the {@linkplain + * Authenticator#setDefault(java.net.Authenticator) default} + * authenticator is meant. + * @return A key for the given authenticator, {@link #DEFAULT} for + * {@code null}. + */ + public static String getKey(Authenticator authenticator) { + if (authenticator == null) { + return DEFAULT; + } + return authenticatorKeyAccess.getKey(authenticator); + } + + @FunctionalInterface + public interface AuthenticatorKeyAccess { + public String getKey(Authenticator a); + } + + private static AuthenticatorKeyAccess authenticatorKeyAccess; + public static void setAuthenticatorKeyAccess(AuthenticatorKeyAccess access) { + if (authenticatorKeyAccess == null && access != null) { + authenticatorKeyAccess = access; + } + } + +} diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/BasicAuthentication.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/BasicAuthentication.java index e77da6157f1..db2e880e7e3 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/BasicAuthentication.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/BasicAuthentication.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,7 @@ import java.net.PasswordAuthentication; import java.io.IOException; import java.io.OutputStream; import java.util.Base64; +import java.util.Objects; import sun.net.www.HeaderParser; /** @@ -54,9 +55,11 @@ class BasicAuthentication extends AuthenticationInfo { * Create a BasicAuthentication */ public BasicAuthentication(boolean isProxy, String host, int port, - String realm, PasswordAuthentication pw) { + String realm, PasswordAuthentication pw, + String authenticatorKey) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, - AuthScheme.BASIC, host, port, realm); + AuthScheme.BASIC, host, port, realm, + Objects.requireNonNull(authenticatorKey)); String plain = pw.getUserName() + ":"; byte[] nameBytes = null; try { @@ -84,9 +87,11 @@ class BasicAuthentication extends AuthenticationInfo { * Create a BasicAuthentication */ public BasicAuthentication(boolean isProxy, String host, int port, - String realm, String auth) { + String realm, String auth, + String authenticatorKey) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, - AuthScheme.BASIC, host, port, realm); + AuthScheme.BASIC, host, port, realm, + Objects.requireNonNull(authenticatorKey)); this.auth = "Basic " + auth; } @@ -94,9 +99,11 @@ class BasicAuthentication extends AuthenticationInfo { * Create a BasicAuthentication */ public BasicAuthentication(boolean isProxy, URL url, String realm, - PasswordAuthentication pw) { + PasswordAuthentication pw, + String authenticatorKey) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, - AuthScheme.BASIC, url, realm); + AuthScheme.BASIC, url, realm, + Objects.requireNonNull(authenticatorKey)); String plain = pw.getUserName() + ":"; byte[] nameBytes = null; try { @@ -124,9 +131,10 @@ class BasicAuthentication extends AuthenticationInfo { * Create a BasicAuthentication */ public BasicAuthentication(boolean isProxy, URL url, String realm, - String auth) { + String auth, String authenticatorKey) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, - AuthScheme.BASIC, url, realm); + AuthScheme.BASIC, url, realm, + Objects.requireNonNull(authenticatorKey)); this.auth = "Basic " + auth; } @@ -202,4 +210,3 @@ class BasicAuthentication extends AuthenticationInfo { return npath; } } - diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java index 32fe64c609e..7d49792b099 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/DigestAuthentication.java @@ -38,6 +38,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivilegedAction; import java.security.AccessController; +import java.util.Objects; import static sun.net.www.protocol.http.HttpURLConnection.HTTP_CONNECT; /** @@ -193,11 +194,12 @@ class DigestAuthentication extends AuthenticationInfo { */ public DigestAuthentication(boolean isProxy, URL url, String realm, String authMethod, PasswordAuthentication pw, - Parameters params) { + Parameters params, String authenticatorKey) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, AuthScheme.DIGEST, url, - realm); + realm, + Objects.requireNonNull(authenticatorKey)); this.authMethod = authMethod; this.pw = pw; this.params = params; @@ -205,12 +207,13 @@ class DigestAuthentication extends AuthenticationInfo { public DigestAuthentication(boolean isProxy, String host, int port, String realm, String authMethod, PasswordAuthentication pw, - Parameters params) { + Parameters params, String authenticatorKey) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, AuthScheme.DIGEST, host, port, - realm); + realm, + Objects.requireNonNull(authenticatorKey)); this.authMethod = authMethod; this.pw = pw; this.params = params; diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpCallerInfo.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpCallerInfo.java index 9537275ee37..038f7adfe90 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpCallerInfo.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpCallerInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,7 @@ package sun.net.www.protocol.http; +import java.net.Authenticator; import java.net.Authenticator.RequestorType; import java.net.InetAddress; import java.net.URL; @@ -49,6 +50,7 @@ public final class HttpCallerInfo { public final int port; public final InetAddress addr; public final RequestorType authType; + public final Authenticator authenticator; /** * Create a schemed object based on an un-schemed one. @@ -62,12 +64,13 @@ public final class HttpCallerInfo { this.addr = old.addr; this.authType = old.authType; this.scheme = scheme; + this.authenticator = old.authenticator; } /** * Constructor an un-schemed object for site access. */ - public HttpCallerInfo(URL url) { + public HttpCallerInfo(URL url, Authenticator a) { this.url= url; prompt = ""; host = url.getHost(); @@ -90,12 +93,13 @@ public final class HttpCallerInfo { protocol = url.getProtocol(); authType = RequestorType.SERVER; scheme = ""; + authenticator = a; } /** * Constructor an un-schemed object for proxy access. */ - public HttpCallerInfo(URL url, String host, int port) { + public HttpCallerInfo(URL url, String host, int port, Authenticator a) { this.url= url; this.host = host; this.port = port; @@ -104,5 +108,6 @@ public final class HttpCallerInfo { protocol = url.getProtocol(); authType = RequestorType.PROXY; scheme = ""; + authenticator = a; } } diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java index 058de37b3b8..5e23b043a69 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -78,6 +78,7 @@ import java.text.SimpleDateFormat; import java.util.TimeZone; import java.net.MalformedURLException; import java.nio.ByteBuffer; +import java.util.Objects; import java.util.Properties; import static sun.net.www.protocol.http.AuthScheme.BASIC; import static sun.net.www.protocol.http.AuthScheme.DIGEST; @@ -304,6 +305,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { protected HttpClient http; protected Handler handler; protected Proxy instProxy; + protected volatile Authenticator authenticator; + protected volatile String authenticatorKey; private CookieHandler cookieHandler; private final ResponseCache cacheHandler; @@ -433,6 +436,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { */ private static PasswordAuthentication privilegedRequestPasswordAuthentication( + final Authenticator authenticator, final String host, final InetAddress addr, final int port, @@ -448,7 +452,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { logger.finest("Requesting Authentication: host =" + host + " url = " + url); } PasswordAuthentication pass = Authenticator.requestPasswordAuthentication( - host, addr, port, protocol, + authenticator, host, addr, port, protocol, prompt, scheme, url, authType); if (logger.isLoggable(PlatformLogger.Level.FINEST)) { logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null")); @@ -507,6 +511,22 @@ public class HttpURLConnection extends java.net.HttpURLConnection { this.authObj = authObj; } + @Override + public synchronized void setAuthenticator(Authenticator auth) { + if (connecting || connected) { + throw new IllegalStateException( + "Authenticator must be set before connecting"); + } + authenticator = Objects.requireNonNull(auth); + authenticatorKey = AuthenticatorKeys.getKey(authenticator); + } + + public String getAuthenticatorKey() { + String k = authenticatorKey; + if (k == null) return AuthenticatorKeys.getKey(authenticator); + return k; + } + /* * checks the validity of http message header and throws * IllegalArgumentException if invalid. @@ -631,7 +651,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { requests.setIfNotSet("If-Modified-Since", fo.format(date)); } // check for preemptive authorization - AuthenticationInfo sauth = AuthenticationInfo.getServerAuth(url); + AuthenticationInfo sauth = AuthenticationInfo.getServerAuth(url, + getAuthenticatorKey()); if (sauth != null && sauth.supportsPreemptiveAuthorization() ) { // Sets "Authorization" requests.setIfNotSet(sauth.getHeaderName(), sauth.getHeaderValue(url,method)); @@ -800,15 +821,15 @@ public class HttpURLConnection extends java.net.HttpURLConnection { * if present */ protected void setProxiedClient (URL url, - String proxyHost, int proxyPort, - boolean useCache) + String proxyHost, int proxyPort, + boolean useCache) throws IOException { proxiedConnect(url, proxyHost, proxyPort, useCache); } protected void proxiedConnect(URL url, - String proxyHost, int proxyPort, - boolean useCache) + String proxyHost, int proxyPort, + boolean useCache) throws IOException { http = HttpClient.New (url, proxyHost, proxyPort, useCache, connectTimeout, this); @@ -878,10 +899,14 @@ public class HttpURLConnection extends java.net.HttpURLConnection { boolean redir; int redirects = 0; InputStream in; + Authenticator a = null; do { if (c instanceof HttpURLConnection) { ((HttpURLConnection) c).setInstanceFollowRedirects(false); + if (a == null) { + a = ((HttpURLConnection) c).authenticator; + } } // We want to open the input stream before @@ -912,6 +937,9 @@ public class HttpURLConnection extends java.net.HttpURLConnection { } redir = true; c = target.openConnection(); + if (a != null && c instanceof HttpURLConnection) { + ((HttpURLConnection)c).setAuthenticator(a); + } redirects++; } } @@ -1612,7 +1640,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { responses, new HttpCallerInfo(url, http.getProxyHostUsed(), - http.getProxyPortUsed()), + http.getProxyPortUsed(), + authenticator), dontUseNegotiate, disabledProxyingSchemes ); @@ -1684,7 +1713,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { srvHdr = new AuthenticationHeader ( "WWW-Authenticate", responses, - new HttpCallerInfo(url), + new HttpCallerInfo(url, authenticator), dontUseNegotiate ); @@ -1762,7 +1791,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { /* path could be an abs_path or a complete URI */ URL u = new URL (url, path); DigestAuthentication d = new DigestAuthentication ( - false, u, realm, "Digest", pw, digestparams); + false, u, realm, "Digest", pw, + digestparams, srv.authenticatorKey); d.addToCache (); } catch (Exception e) {} } @@ -2065,7 +2095,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { responses, new HttpCallerInfo(url, http.getProxyHostUsed(), - http.getProxyPortUsed()), + http.getProxyPortUsed(), + authenticator), dontUseNegotiate, disabledTunnelingSchemes ); @@ -2174,7 +2205,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { private void setPreemptiveProxyAuthentication(MessageHeader requests) throws IOException { AuthenticationInfo pauth = AuthenticationInfo.getProxyAuth(http.getProxyHostUsed(), - http.getProxyPortUsed()); + http.getProxyPortUsed(), + getAuthenticatorKey()); if (pauth != null && pauth.supportsPreemptiveAuthorization()) { String value; if (pauth instanceof DigestAuthentication) { @@ -2228,7 +2260,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { if (realm == null) realm = ""; - proxyAuthKey = AuthenticationInfo.getProxyAuthKey(host, port, realm, authScheme); + proxyAuthKey = AuthenticationInfo.getProxyAuthKey(host, port, realm, + authScheme, getAuthenticatorKey()); ret = AuthenticationInfo.getProxyAuth(proxyAuthKey); if (ret == null) { switch (authScheme) { @@ -2248,21 +2281,25 @@ public class HttpURLConnection extends java.net.HttpURLConnection { } PasswordAuthentication a = privilegedRequestPasswordAuthentication( + authenticator, host, addr, port, "http", realm, scheme, url, RequestorType.PROXY); if (a != null) { - ret = new BasicAuthentication(true, host, port, realm, a); + ret = new BasicAuthentication(true, host, port, realm, a, + getAuthenticatorKey()); } break; case DIGEST: a = privilegedRequestPasswordAuthentication( + authenticator, host, null, port, url.getProtocol(), realm, scheme, url, RequestorType.PROXY); if (a != null) { DigestAuthentication.Parameters params = new DigestAuthentication.Parameters(); ret = new DigestAuthentication(true, host, port, realm, - scheme, a, params); + scheme, a, params, + getAuthenticatorKey()); } break; case NTLM: @@ -2288,6 +2325,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { logger.finest("Trying Transparent NTLM authentication"); } else { a = privilegedRequestPasswordAuthentication( + authenticator, host, null, port, url.getProtocol(), "", scheme, url, RequestorType.PROXY); } @@ -2299,7 +2337,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { */ if (tryTransparentNTLMProxy || (!tryTransparentNTLMProxy && a != null)) { - ret = NTLMAuthenticationProxy.proxy.create(true, host, port, a); + ret = NTLMAuthenticationProxy.proxy.create(true, host, + port, a, getAuthenticatorKey()); } /* set to false so that we do not try again */ @@ -2330,7 +2369,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { URL u = new URL("http", host, port, "/"); String a = defaultAuth.authString(u, scheme, realm); if (a != null) { - ret = new BasicAuthentication (true, host, port, realm, a); + ret = new BasicAuthentication (true, host, port, realm, a, + getAuthenticatorKey()); // not in cache by default - cache on success } } catch (java.net.MalformedURLException ignored) { @@ -2383,7 +2423,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { domain = p.findValue ("domain"); if (realm == null) realm = ""; - serverAuthKey = AuthenticationInfo.getServerAuthKey(url, realm, authScheme); + serverAuthKey = AuthenticationInfo.getServerAuthKey(url, realm, authScheme, + getAuthenticatorKey()); ret = AuthenticationInfo.getServerAuth(serverAuthKey); InetAddress addr = null; if (ret == null) { @@ -2409,19 +2450,24 @@ public class HttpURLConnection extends java.net.HttpURLConnection { case BASIC: PasswordAuthentication a = privilegedRequestPasswordAuthentication( + authenticator, url.getHost(), addr, port, url.getProtocol(), realm, scheme, url, RequestorType.SERVER); if (a != null) { - ret = new BasicAuthentication(false, url, realm, a); + ret = new BasicAuthentication(false, url, realm, a, + getAuthenticatorKey()); } break; case DIGEST: a = privilegedRequestPasswordAuthentication( + authenticator, url.getHost(), addr, port, url.getProtocol(), realm, scheme, url, RequestorType.SERVER); if (a != null) { digestparams = new DigestAuthentication.Parameters(); - ret = new DigestAuthentication(false, url, realm, scheme, a, digestparams); + ret = new DigestAuthentication(false, url, realm, scheme, + a, digestparams, + getAuthenticatorKey()); } break; case NTLM: @@ -2452,6 +2498,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { logger.finest("Trying Transparent NTLM authentication"); } else { a = privilegedRequestPasswordAuthentication( + authenticator, url.getHost(), addr, port, url.getProtocol(), "", scheme, url, RequestorType.SERVER); } @@ -2464,7 +2511,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { */ if (tryTransparentNTLMServer || (!tryTransparentNTLMServer && a != null)) { - ret = NTLMAuthenticationProxy.proxy.create(false, url1, a); + ret = NTLMAuthenticationProxy.proxy.create(false, + url1, a, getAuthenticatorKey()); } /* set to false so that we do not try again */ @@ -2488,7 +2536,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { && defaultAuth.schemeSupported(scheme)) { String a = defaultAuth.authString(url, scheme, realm); if (a != null) { - ret = new BasicAuthentication (false, url, realm, a); + ret = new BasicAuthentication (false, url, realm, a, + getAuthenticatorKey()); // not in cache by default - cache on success } } diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/NTLMAuthenticationProxy.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/NTLMAuthenticationProxy.java index 335670ee699..d7961a3f0f7 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/NTLMAuthenticationProxy.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/NTLMAuthenticationProxy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -45,21 +45,22 @@ class NTLMAuthenticationProxy { static final boolean supported = proxy != null ? true : false; static final boolean supportsTransparentAuth = supported ? supportsTransparentAuth() : false; - private final Constructor threeArgCtr; - private final Constructor fiveArgCtr; + private final Constructor fourArgCtr; + private final Constructor sixArgCtr; - private NTLMAuthenticationProxy(Constructor threeArgCtr, - Constructor fiveArgCtr) { - this.threeArgCtr = threeArgCtr; - this.fiveArgCtr = fiveArgCtr; + private NTLMAuthenticationProxy(Constructor fourArgCtr, + Constructor sixArgCtr) { + this.fourArgCtr = fourArgCtr; + this.sixArgCtr = sixArgCtr; } AuthenticationInfo create(boolean isProxy, URL url, - PasswordAuthentication pw) { + PasswordAuthentication pw, + String authenticatorKey) { try { - return threeArgCtr.newInstance(isProxy, url, pw); + return fourArgCtr.newInstance(isProxy, url, pw, authenticatorKey); } catch (ReflectiveOperationException roe) { finest(roe); } @@ -70,9 +71,10 @@ class NTLMAuthenticationProxy { AuthenticationInfo create(boolean isProxy, String host, int port, - PasswordAuthentication pw) { + PasswordAuthentication pw, + String authenticatorKey) { try { - return fiveArgCtr.newInstance(isProxy, host, port, pw); + return sixArgCtr.newInstance(isProxy, host, port, pw, authenticatorKey); } catch (ReflectiveOperationException roe) { finest(roe); } @@ -115,21 +117,23 @@ class NTLMAuthenticationProxy { @SuppressWarnings("unchecked") private static NTLMAuthenticationProxy tryLoadNTLMAuthentication() { Class cl; - Constructor threeArg, fiveArg; + Constructor fourArg, sixArg; try { cl = (Class)Class.forName(clazzStr, true, null); if (cl != null) { - threeArg = cl.getConstructor(boolean.class, + fourArg = cl.getConstructor(boolean.class, URL.class, - PasswordAuthentication.class); - fiveArg = cl.getConstructor(boolean.class, + PasswordAuthentication.class, + String.class); + sixArg = cl.getConstructor(boolean.class, String.class, int.class, - PasswordAuthentication.class); + PasswordAuthentication.class, + String.class); supportsTA = cl.getDeclaredMethod(supportsTAStr); isTrustedSite = cl.getDeclaredMethod(isTrustedSiteStr, java.net.URL.class); - return new NTLMAuthenticationProxy(threeArg, - fiveArg); + return new NTLMAuthenticationProxy(fourArg, + sixArg); } } catch (ClassNotFoundException cnfe) { finest(cnfe); diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java index 820f3eda8a0..d7c379f0d47 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -68,7 +68,8 @@ class NegotiateAuthentication extends AuthenticationInfo { super(RequestorType.PROXY==hci.authType ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, hci.scheme.equalsIgnoreCase("Negotiate") ? NEGOTIATE : KERBEROS, hci.url, - ""); + "", + AuthenticatorKeys.getKey(hci.authenticator)); this.hci = hci; } diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java index eadd290e215..628323047bf 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsClient.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,6 +39,7 @@ import java.net.InetSocketAddress; import java.net.Proxy; import java.security.Principal; import java.security.cert.*; +import java.util.Objects; import java.util.StringTokenizer; import java.util.Vector; @@ -46,6 +47,7 @@ import javax.security.auth.x500.X500Principal; import javax.net.ssl.*; import sun.net.www.http.HttpClient; +import sun.net.www.protocol.http.AuthenticatorKeys; import sun.net.www.protocol.http.HttpURLConnection; import sun.security.action.*; @@ -334,8 +336,12 @@ final class HttpsClient extends HttpClient } if (ret != null) { - if ((ret.proxy != null && ret.proxy.equals(p)) || - (ret.proxy == null && p == Proxy.NO_PROXY)) { + String ak = httpuc == null ? AuthenticatorKeys.DEFAULT + : httpuc.getAuthenticatorKey(); + boolean compatible = ((ret.proxy != null && ret.proxy.equals(p)) || + (ret.proxy == null && p == Proxy.NO_PROXY)) + && Objects.equals(ret.getAuthenticatorKey(), ak); + if (compatible) { synchronized (ret) { ret.cachedHttpClient = true; assert ret.inCache; @@ -364,6 +370,9 @@ final class HttpsClient extends HttpClient } if (ret == null) { ret = new HttpsClient(sf, url, p, connectTimeout); + if (httpuc != null) { + ret.authenticatorKey = httpuc.getAuthenticatorKey(); + } } else { SecurityManager security = System.getSecurityManager(); if (security != null) { diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java index 429079804f0..1b2a584a79b 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,6 +39,7 @@ import java.net.URL; import java.net.Proxy; import java.net.ProtocolException; import java.io.*; +import java.net.Authenticator; import javax.net.ssl.*; import java.security.Permission; import java.security.Principal; @@ -517,4 +518,9 @@ public class HttpsURLConnectionImpl public void setChunkedStreamingMode (int chunklen) { delegate.setChunkedStreamingMode(chunklen); } + + @Override + public void setAuthenticator(Authenticator auth) { + delegate.setAuthenticator(auth); + } } diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java index a4bb68150a5..90559598aee 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java @@ -324,15 +324,17 @@ public final class AlgorithmChecker extends PKIXCertPathChecker { PublicKey currPubKey = cert.getPublicKey(); - // Check against DisabledAlgorithmConstraints certpath constraints. - // permits() will throw exception on failure. - certPathDefaultConstraints.permits(primitives, + if (constraints instanceof DisabledAlgorithmConstraints) { + // Check against DisabledAlgorithmConstraints certpath constraints. + // permits() will throw exception on failure. + ((DisabledAlgorithmConstraints)constraints).permits(primitives, new CertConstraintParameters((X509Certificate)cert, trustedMatch, pkixdate, jarTimestamp)); - // If there is no previous key, set one and exit - if (prevPubKey == null) { - prevPubKey = currPubKey; - return; + // If there is no previous key, set one and exit + if (prevPubKey == null) { + prevPubKey = currPubKey; + return; + } } X509CertImpl x509Cert; diff --git a/jdk/src/java.base/share/classes/sun/text/spi/JavaTimeDateTimePatternProvider.java b/jdk/src/java.base/share/classes/sun/text/spi/JavaTimeDateTimePatternProvider.java new file mode 100644 index 00000000000..c8fd888e2b2 --- /dev/null +++ b/jdk/src/java.base/share/classes/sun/text/spi/JavaTimeDateTimePatternProvider.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. 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.text.spi; + +import java.util.Locale; +import java.util.spi.LocaleServiceProvider; + +/** + * Service Provider Interface for retrieving DateTime patterns from + * specified Locale provider for java.time. + */ + +public abstract class JavaTimeDateTimePatternProvider extends LocaleServiceProvider { + + protected JavaTimeDateTimePatternProvider() { + } + + /** + * Gets the formatting pattern for a timeStyle + * dateStyle, calendarType and locale. + * Concrete implementation of this method will retrieve + * a java.time specific dateTime Pattern from selected Locale Provider. + * + * @param timeStyle an {@code int} value representing FormatStyle constant, -1 + * for date-only pattern + * @param dateStyle an {@code int} value,representing FormatStyle constant, -1 + * for time-only pattern + * @param locale {@code locale}, non-null + * @param calType a {@code String},non-null representing CalendarType such as "japanese", + * "iso8601" + * @return formatting pattern {@code String} + * @see java.time.format.DateTimeFormatterBuilder#convertStyle(java.time.format.FormatStyle) + * @since 9 + */ + public abstract String getJavaTimeDateTimePattern(int timeStyle, int dateStyle, String calType, Locale locale); +} diff --git a/jdk/src/java.base/share/classes/sun/util/locale/provider/AuxLocaleProviderAdapter.java b/jdk/src/java.base/share/classes/sun/util/locale/provider/AuxLocaleProviderAdapter.java index 1963b4d1d6c..89cc217f34c 100644 --- a/jdk/src/java.base/share/classes/sun/util/locale/provider/AuxLocaleProviderAdapter.java +++ b/jdk/src/java.base/share/classes/sun/util/locale/provider/AuxLocaleProviderAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -45,6 +45,7 @@ import java.util.spi.CurrencyNameProvider; import java.util.spi.LocaleNameProvider; import java.util.spi.LocaleServiceProvider; import java.util.spi.TimeZoneNameProvider; +import sun.text.spi.JavaTimeDateTimePatternProvider; import sun.util.spi.CalendarProvider; /** @@ -156,6 +157,11 @@ public abstract class AuxLocaleProviderAdapter extends LocaleProviderAdapter { return null; } + @Override + public JavaTimeDateTimePatternProvider getJavaTimeDateTimePatternProvider() { + return getLocaleServiceProvider(JavaTimeDateTimePatternProvider.class); + } + private static Locale[] availableLocales = null; @Override diff --git a/jdk/src/java.base/share/classes/sun/util/locale/provider/JRELocaleProviderAdapter.java b/jdk/src/java.base/share/classes/sun/util/locale/provider/JRELocaleProviderAdapter.java index c16c012fcf1..db17c386304 100644 --- a/jdk/src/java.base/share/classes/sun/util/locale/provider/JRELocaleProviderAdapter.java +++ b/jdk/src/java.base/share/classes/sun/util/locale/provider/JRELocaleProviderAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -50,6 +50,7 @@ import java.util.spi.CurrencyNameProvider; import java.util.spi.LocaleNameProvider; import java.util.spi.LocaleServiceProvider; import java.util.spi.TimeZoneNameProvider; +import sun.text.spi.JavaTimeDateTimePatternProvider; import sun.util.resources.LocaleData; import sun.util.spi.CalendarProvider; @@ -109,6 +110,8 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R return (P) getCalendarNameProvider(); case "CalendarProvider": return (P) getCalendarProvider(); + case "JavaTimeDateTimePatternProvider": + return (P) getJavaTimeDateTimePatternProvider(); default: throw new InternalError("should not come down here"); } @@ -128,6 +131,7 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R private volatile CalendarNameProvider calendarNameProvider; private volatile CalendarProvider calendarProvider; + private volatile JavaTimeDateTimePatternProvider javaTimeDateTimePatternProvider; /* * Getter methods for java.text.spi.* providers @@ -354,6 +358,27 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R return calendarProvider; } + /** + * Getter methods for sun.text.spi.JavaTimeDateTimePatternProvider provider + */ + @Override + public JavaTimeDateTimePatternProvider getJavaTimeDateTimePatternProvider() { + if (javaTimeDateTimePatternProvider == null) { + JavaTimeDateTimePatternProvider provider = AccessController.doPrivileged( + (PrivilegedAction) () + -> new JavaTimeDateTimePatternImpl( + getAdapterType(), + getLanguageTagSet("FormatData"))); + + synchronized (this) { + if (javaTimeDateTimePatternProvider == null) { + javaTimeDateTimePatternProvider = provider; + } + } + } + return javaTimeDateTimePatternProvider; + } + @Override public LocaleResources getLocaleResources(Locale locale) { LocaleResources lr = localeResourcesMap.get(locale); diff --git a/jdk/src/java.base/share/classes/sun/util/locale/provider/JavaTimeDateTimePatternImpl.java b/jdk/src/java.base/share/classes/sun/util/locale/provider/JavaTimeDateTimePatternImpl.java new file mode 100644 index 00000000000..41de2dd7f65 --- /dev/null +++ b/jdk/src/java.base/share/classes/sun/util/locale/provider/JavaTimeDateTimePatternImpl.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. 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.util.locale.provider; + +import java.util.Locale; +import java.util.Set; +import sun.text.spi.JavaTimeDateTimePatternProvider; + +/** + * Concrete implementation of the {@link sun.text.spi.JavaTimeDateTimePatternProvider + * } class for the JRE LocaleProviderAdapter. + * + */ +public class JavaTimeDateTimePatternImpl extends JavaTimeDateTimePatternProvider implements AvailableLanguageTags { + + private final LocaleProviderAdapter.Type type; + private final Set langtags; + + public JavaTimeDateTimePatternImpl(LocaleProviderAdapter.Type type, Set langtags) { + this.type = type; + this.langtags = langtags; + } + + /** + * Returns an array of all locales for which this locale service provider + * can provide localized objects or names. + * + * @return An array of all locales for which this locale service provider + * can provide localized objects or names. + */ + @Override + public Locale[] getAvailableLocales() { + return LocaleProviderAdapter.toLocaleArray(langtags); + } + + @Override + public boolean isSupportedLocale(Locale locale) { + return LocaleProviderAdapter.forType(type).isSupportedProviderLocale(locale, langtags); + } + + @Override + public String getJavaTimeDateTimePattern(int timeStyle, int dateStyle, String calType, Locale locale) { + LocaleResources lr = LocaleProviderAdapter.getResourceBundleBased().getLocaleResources(locale); + String pattern = lr.getJavaTimeDateTimePattern( + timeStyle, dateStyle, calType); + return pattern; + + } + + @Override + public Set getAvailableLanguageTags() { + return langtags; + } +} diff --git a/jdk/src/java.base/share/classes/sun/util/locale/provider/LocaleProviderAdapter.java b/jdk/src/java.base/share/classes/sun/util/locale/provider/LocaleProviderAdapter.java index bafb81976d7..d99b48dcd7b 100644 --- a/jdk/src/java.base/share/classes/sun/util/locale/provider/LocaleProviderAdapter.java +++ b/jdk/src/java.base/share/classes/sun/util/locale/provider/LocaleProviderAdapter.java @@ -47,6 +47,7 @@ import java.util.spi.LocaleNameProvider; import java.util.spi.LocaleServiceProvider; import java.util.spi.TimeZoneNameProvider; import sun.security.action.GetPropertyAction; +import sun.text.spi.JavaTimeDateTimePatternProvider; import sun.util.spi.CalendarProvider; /** @@ -428,6 +429,14 @@ public abstract class LocaleProviderAdapter { */ public abstract CalendarProvider getCalendarProvider(); + /** + * Returns a JavaTimeDateTimePatternProvider for this LocaleProviderAdapter, + * or null if no JavaTimeDateTimePatternProvider is available. + * + * @return a JavaTimeDateTimePatternProvider + */ + public abstract JavaTimeDateTimePatternProvider getJavaTimeDateTimePatternProvider(); + public abstract LocaleResources getLocaleResources(Locale locale); public abstract Locale[] getAvailableLocales(); diff --git a/jdk/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java b/jdk/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java index 85bbd53ad43..01213c04360 100644 --- a/jdk/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java +++ b/jdk/src/java.base/unix/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,7 @@ import java.net.UnknownHostException; import java.net.URL; import java.security.GeneralSecurityException; import java.util.Base64; +import java.util.Objects; import sun.net.www.HeaderParser; import sun.net.www.protocol.http.AuthenticationInfo; @@ -116,11 +117,13 @@ public class NTLMAuthentication extends AuthenticationInfo { * If this notation is not used, then the domain will be taken * from a system property: "http.auth.ntlm.domain". */ - public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw) { + public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw, + String authenticatorKey) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, AuthScheme.NTLM, url, - ""); + "", + Objects.requireNonNull(authenticatorKey)); init (pw); } @@ -157,12 +160,14 @@ public class NTLMAuthentication extends AuthenticationInfo { * Constructor used for proxy entries */ public NTLMAuthentication(boolean isProxy, String host, int port, - PasswordAuthentication pw) { + PasswordAuthentication pw, + String authenticatorKey) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, AuthScheme.NTLM, host, port, - ""); + "", + Objects.requireNonNull(authenticatorKey)); init (pw); } @@ -242,4 +247,3 @@ public class NTLMAuthentication extends AuthenticationInfo { return result; } } - diff --git a/jdk/src/java.base/windows/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java b/jdk/src/java.base/windows/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java index 50e056862c9..212e03e834f 100644 --- a/jdk/src/java.base/windows/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java +++ b/jdk/src/java.base/windows/classes/sun/net/www/protocol/http/ntlm/NTLMAuthentication.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ import java.net.InetAddress; import java.net.PasswordAuthentication; import java.net.UnknownHostException; import java.net.URL; +import java.util.Objects; import sun.net.www.HeaderParser; import sun.net.www.protocol.http.AuthenticationInfo; import sun.net.www.protocol.http.AuthScheme; @@ -88,11 +89,13 @@ public class NTLMAuthentication extends AuthenticationInfo { * If this notation is not used, then the domain will be taken * from a system property: "http.auth.ntlm.domain". */ - public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw) { + public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw, + String authenticatorKey) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, AuthScheme.NTLM, url, - ""); + "", + Objects.requireNonNull(authenticatorKey)); init (pw); } @@ -122,12 +125,14 @@ public class NTLMAuthentication extends AuthenticationInfo { * Constructor used for proxy entries */ public NTLMAuthentication(boolean isProxy, String host, int port, - PasswordAuthentication pw) { + PasswordAuthentication pw, + String authenticatorKey) { super(isProxy?PROXY_AUTHENTICATION:SERVER_AUTHENTICATION, AuthScheme.NTLM, host, port, - ""); + "", + Objects.requireNonNull(authenticatorKey)); init (pw); } diff --git a/jdk/src/java.base/windows/classes/sun/util/locale/provider/HostLocaleProviderAdapterImpl.java b/jdk/src/java.base/windows/classes/sun/util/locale/provider/HostLocaleProviderAdapterImpl.java index 71e999f47bf..2f4fd0e89c6 100644 --- a/jdk/src/java.base/windows/classes/sun/util/locale/provider/HostLocaleProviderAdapterImpl.java +++ b/jdk/src/java.base/windows/classes/sun/util/locale/provider/HostLocaleProviderAdapterImpl.java @@ -52,6 +52,7 @@ import java.util.spi.CalendarDataProvider; import java.util.spi.CalendarNameProvider; import java.util.spi.CurrencyNameProvider; import java.util.spi.LocaleNameProvider; +import sun.text.spi.JavaTimeDateTimePatternProvider; import sun.util.spi.CalendarProvider; /** @@ -525,6 +526,167 @@ public class HostLocaleProviderAdapterImpl { }; } + public static JavaTimeDateTimePatternProvider getJavaTimeDateTimePatternProvider() { + return new JavaTimeDateTimePatternProvider() { + @Override + public Locale[] getAvailableLocales() { + return getSupportedCalendarLocales(); + } + + @Override + public boolean isSupportedLocale(Locale locale) { + return isSupportedCalendarLocale(locale); + } + + @Override + public String getJavaTimeDateTimePattern(int timeStyle, int dateStyle, String calType, Locale locale) { + AtomicReferenceArray patterns = getDateTimePatterns(locale); + String pattern = new StringBuilder(patterns.get(dateStyle / 2)) + .append(" ") + .append(patterns.get(timeStyle / 2 + 2)) + .toString(); + return toJavaTimeDateTimePattern(calType, pattern); + + } + + private AtomicReferenceArray getDateTimePatterns(Locale locale) { + AtomicReferenceArray patterns; + SoftReference> ref = dateFormatCache.get(locale); + + if (ref == null || (patterns = ref.get()) == null) { + String langtag = removeExtensions(locale).toLanguageTag(); + patterns = new AtomicReferenceArray<>(4); + patterns.compareAndSet(0, null, convertDateTimePattern( + getDateTimePattern(DateFormat.LONG, -1, langtag))); + patterns.compareAndSet(1, null, convertDateTimePattern( + getDateTimePattern(DateFormat.SHORT, -1, langtag))); + patterns.compareAndSet(2, null, convertDateTimePattern( + getDateTimePattern(-1, DateFormat.LONG, langtag))); + patterns.compareAndSet(3, null, convertDateTimePattern( + getDateTimePattern(-1, DateFormat.SHORT, langtag))); + ref = new SoftReference<>(patterns); + dateFormatCache.put(locale, ref); + } + return patterns; + } + /** + * This method will convert JRE Date/time Pattern String to JSR310 + * type Date/Time Pattern + */ + private String toJavaTimeDateTimePattern(String calendarType, String jrePattern) { + int length = jrePattern.length(); + StringBuilder sb = new StringBuilder(length); + boolean inQuote = false; + int count = 0; + char lastLetter = 0; + for (int i = 0; i < length; i++) { + char c = jrePattern.charAt(i); + if (c == '\'') { + // '' is treated as a single quote regardless of being + // in a quoted section. + if ((i + 1) < length) { + char nextc = jrePattern.charAt(i + 1); + if (nextc == '\'') { + i++; + if (count != 0) { + convert(calendarType, lastLetter, count, sb); + lastLetter = 0; + count = 0; + } + sb.append("''"); + continue; + } + } + if (!inQuote) { + if (count != 0) { + convert(calendarType, lastLetter, count, sb); + lastLetter = 0; + count = 0; + } + inQuote = true; + } else { + inQuote = false; + } + sb.append(c); + continue; + } + if (inQuote) { + sb.append(c); + continue; + } + if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) { + if (count != 0) { + convert(calendarType, lastLetter, count, sb); + lastLetter = 0; + count = 0; + } + sb.append(c); + continue; + } + if (lastLetter == 0 || lastLetter == c) { + lastLetter = c; + count++; + continue; + } + convert(calendarType, lastLetter, count, sb); + lastLetter = c; + count = 1; + } + if (inQuote) { + // should not come here. + // returning null so that FALLBACK provider will kick in. + return null; + } + if (count != 0) { + convert(calendarType, lastLetter, count, sb); + } + return sb.toString(); + } + + private void convert(String calendarType, char letter, int count, StringBuilder sb) { + switch (letter) { + case 'G': + if (calendarType.equals("japanese")) { + if (count >= 4) { + count = 1; + } else { + count = 5; + } + } else if (!calendarType.equals("iso8601")) { + // Adjust the number of 'G's + // Gregorian calendar is iso8601 for java.time + if (count >= 4) { + // JRE full -> JavaTime full + count = 4; + } else { + // JRE short -> JavaTime short + count = 1; + } + } + break; + case 'y': + if (calendarType.equals("japanese") && count >= 4) { + // JRE specific "gan-nen" support + count = 1; + } + break; + default: + // JSR 310 and CLDR define 5-letter patterns for narrow text. + if (count > 4) { + count = 4; + } + break; + } + appendN(letter, count, sb); + } + + private void appendN(char c, int n, StringBuilder sb) { + for (int i = 0; i < n; i++) { + sb.append(c); + } + } + }; + } private static String convertDateTimePattern(String winPattern) { String ret = winPattern.replaceAll("dddd", "EEEE"); diff --git a/jdk/src/java.security.jgss/share/classes/sun/net/www/protocol/http/spnego/NegotiateCallbackHandler.java b/jdk/src/java.security.jgss/share/classes/sun/net/www/protocol/http/spnego/NegotiateCallbackHandler.java index db03ab580d1..43003bfb811 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/net/www/protocol/http/spnego/NegotiateCallbackHandler.java +++ b/jdk/src/java.security.jgss/share/classes/sun/net/www/protocol/http/spnego/NegotiateCallbackHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -63,6 +63,7 @@ public class NegotiateCallbackHandler implements CallbackHandler { answered = true; PasswordAuthentication passAuth = Authenticator.requestPasswordAuthentication( + hci.authenticator, hci.host, hci.addr, hci.port, hci.protocol, hci.prompt, hci.scheme, hci.url, hci.authType); /** diff --git a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java index 566b99ba0f3..f9b32761f05 100644 --- a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java +++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java @@ -774,6 +774,12 @@ class Main { /* parse file arguments */ int n = args.length - count; if (n > 0) { + if (printModuleDescriptor) { + // "--print-module-descriptor/-d" does not require file argument(s) + error(formatMsg("error.bad.dflag", args[count])); + usageError(); + return false; + } int version = BASE_VERSION; int k = 0; String[] nameBuf = new String[n]; diff --git a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties index 7e2f6e6a164..f1e281619ef 100644 --- a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties +++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties @@ -44,6 +44,8 @@ error.bad.uflag=\ error.bad.eflag=\ 'e' flag and manifest with the 'Main-Class' attribute cannot be specified \n\ together! +error.bad.dflag=\ + '-d, --print-module-descriptor' option requires no input file(s) to be specified: {0} error.nosuch.fileordir=\ {0} : no such file or directory error.write.file=\ diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index dfaa8325ea9..247de4ee6ee 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -234,8 +234,6 @@ javax/sound/sampled/Clip/Drain/ClipDrain.java 7062792 generic-all javax/sound/sampled/Mixers/DisabledAssertionCrash.java 7067310 generic-all -javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java 8168881 generic-all - ############################################################################ # jdk_imageio @@ -312,6 +310,7 @@ demo/jvmti/compiledMethodLoad/CompiledMethodLoadTest.java 8151899 generic- # jdk_other com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java 8169942 linux-i586,macosx-all,windows-x64 +com/sun/jndi/rmi/registry/RegistryContext/UnbindIdempotent.java 8170669 generic-all javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java 8169737 linux-all javax/xml/ws/clientjar/TestWsImport.java 8170370 generic-all diff --git a/jdk/test/TEST.groups b/jdk/test/TEST.groups index def84c827b3..448f871ee4d 100644 --- a/jdk/test/TEST.groups +++ b/jdk/test/TEST.groups @@ -741,7 +741,8 @@ needs_compact2 = \ java/util/ResourceBundle/Bug6359330.java \ java/util/Spliterator/SpliteratorCharacteristics.java \ java/util/Spliterator/SpliteratorCollisions.java \ - java/util/Spliterator/SpliteratorLateBindingFailFastTest.java \ + java/util/Spliterator/SpliteratorLateBindingTest.java \ + java/util/Spliterator/SpliteratorFailFastTest.java \ java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java \ java/util/StringJoiner/MergeTest.java \ java/util/StringJoiner/StringJoinerTest.java \ diff --git a/jdk/test/com/sun/jndi/rmi/registry/RegistryContext/ContextWithNullProperties.java b/jdk/test/com/sun/jndi/rmi/registry/RegistryContext/ContextWithNullProperties.java index d8590f0682d..2004d96f2f9 100644 --- a/jdk/test/com/sun/jndi/rmi/registry/RegistryContext/ContextWithNullProperties.java +++ b/jdk/test/com/sun/jndi/rmi/registry/RegistryContext/ContextWithNullProperties.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ * @modules jdk.naming.rmi/com.sun.jndi.rmi.registry java.rmi/sun.rmi.registry * java.rmi/sun.rmi.server java.rmi/sun.rmi.transport java.rmi/sun.rmi.transport.tcp * @library ../../../../../../java/rmi/testlibrary + * @build TestLibrary * @compile --add-modules jdk.naming.rmi ContextWithNullProperties.java * @run main ContextWithNullProperties */ @@ -37,7 +38,7 @@ import java.rmi.registry.Registry; public class ContextWithNullProperties { public static void main(String[] args) throws Exception { - Registry registry = TestLibrary.createRegistryOnUnusedPort(); + Registry registry = TestLibrary.createRegistryOnEphemeralPort(); int registryPort = TestLibrary.getRegistryPort(registry); System.out.println("Connecting to the default Registry..."); // Connect to the default Registry. diff --git a/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPSetAuthenticatorTest.java b/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPSetAuthenticatorTest.java new file mode 100644 index 00000000000..543ebc5e821 --- /dev/null +++ b/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPSetAuthenticatorTest.java @@ -0,0 +1,295 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.IOException; +import java.net.Authenticator; +import java.net.HttpURLConnection; +import java.net.Proxy; +import java.net.URL; +import java.util.Arrays; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * @test + * @bug 8169415 + * @library /lib/testlibrary/ + * @modules java.base/sun.net.www + * java.base/sun.net.www.protocol.http + * jdk.httpserver/sun.net.httpserver + * @build jdk.testlibrary.SimpleSSLContext HTTPTest HTTPTestServer HTTPTestClient HTTPSetAuthenticatorTest + * @summary A simple HTTP test that starts an echo server supporting the given + * authentication scheme, then starts a regular HTTP client to invoke it. + * The client first does a GET request on "/", then follows on + * with a POST request that sends "Hello World!" to the server. + * The client expects to receive "Hello World!" in return. + * The test supports several execution modes: + * SERVER: The server performs Server authentication; + * PROXY: The server pretends to be a proxy and performs + * Proxy authentication; + * SERVER307: The server redirects the client (307) to another + * server that perform Server authentication; + * PROXY305: The server attempts to redirect + * the client to a proxy using 305 code; + * This test runs the client several times, providing different + * authenticators to the HttpURLConnection and verifies that + * the authenticator is invoked as expected - validating that + * connections with different authenticators do not share each + * other's socket channel and authentication info. + * Note: BASICSERVER means that the server will let the underlying + * com.sun.net.httpserver.HttpServer perform BASIC + * authentication when in Server mode. There should be + * no real difference between BASICSERVER and BASIC - it should + * be transparent on the client side. + * @run main/othervm HTTPSetAuthenticatorTest NONE SERVER PROXY SERVER307 PROXY305 + * @run main/othervm HTTPSetAuthenticatorTest DIGEST SERVER + * @run main/othervm HTTPSetAuthenticatorTest DIGEST PROXY + * @run main/othervm HTTPSetAuthenticatorTest DIGEST PROXY305 + * @run main/othervm HTTPSetAuthenticatorTest DIGEST SERVER307 + * @run main/othervm HTTPSetAuthenticatorTest BASIC SERVER + * @run main/othervm HTTPSetAuthenticatorTest BASIC PROXY + * @run main/othervm HTTPSetAuthenticatorTest BASIC PROXY305 + * @run main/othervm HTTPSetAuthenticatorTest BASIC SERVER307 + * @run main/othervm HTTPSetAuthenticatorTest BASICSERVER SERVER + * @run main/othervm HTTPSetAuthenticatorTest BASICSERVER SERVER307 + * + * @author danielfuchs + */ +public class HTTPSetAuthenticatorTest extends HTTPTest { + + public static void main(String[] args) throws Exception { + String[] schemes; + String[] params; + if (args == null || args.length == 0) { + schemes = Stream.of(HttpSchemeType.values()) + .map(HttpSchemeType::name) + .collect(Collectors.toList()) + .toArray(new String[0]); + params = new String[0]; + } else { + schemes = new String[] { args[0] }; + params = Arrays.copyOfRange(args, 1, args.length); + } + for (String scheme : schemes) { + System.out.println("==== Testing with scheme=" + scheme + " ====\n"); + new HTTPSetAuthenticatorTest(HttpSchemeType.valueOf(scheme)) + .execute(params); + System.out.println(); + } + } + + final HttpSchemeType scheme; + public HTTPSetAuthenticatorTest(HttpSchemeType scheme) { + this.scheme = scheme; + } + + @Override + public HttpSchemeType getHttpSchemeType() { + return scheme; + } + + @Override + public int run(HTTPTestServer server, + HttpProtocolType protocol, + HttpAuthType mode) + throws IOException + { + HttpTestAuthenticator authOne = new HttpTestAuthenticator("dublin", "foox"); + HttpTestAuthenticator authTwo = new HttpTestAuthenticator("dublin", "foox"); + int expectedIncrement = scheme == HttpSchemeType.NONE + ? 0 : EXPECTED_AUTH_CALLS_PER_TEST; + int count; + int defaultCount = AUTHENTICATOR.count.get(); + + // Connect to the server with a GET request, then with a + // POST that contains "Hello World!" + // Uses authenticator #1 + System.out.println("\nClient: Using authenticator #1: " + + toString(authOne)); + HTTPTestClient.connect(protocol, server, mode, authOne); + count = authOne.count.get(); + if (count != expectedIncrement) { + throw new AssertionError("Authenticator #1 called " + count(count) + + " expected it to be called " + expected(expectedIncrement)); + } + + // Connect to the server with a GET request, then with a + // POST that contains "Hello World!" + // Uses authenticator #2 + System.out.println("\nClient: Using authenticator #2: " + + toString(authTwo)); + HTTPTestClient.connect(protocol, server, mode, authTwo); + count = authTwo.count.get(); + if (count != expectedIncrement) { + throw new AssertionError("Authenticator #2 called " + count(count) + + " expected it to be called " + expected(expectedIncrement)); + } + count = authTwo.count.get(); + if (count != expectedIncrement) { + throw new AssertionError("Authenticator #2 called " + count(count) + + " expected it to be called " + expected(expectedIncrement)); + } + + // Connect to the server with a GET request, then with a + // POST that contains "Hello World!" + // Uses authenticator #1 + System.out.println("\nClient: Using authenticator #1 again: " + + toString(authOne)); + HTTPTestClient.connect(protocol, server, mode, authOne); + count = authOne.count.get(); + if (count != expectedIncrement) { + throw new AssertionError("Authenticator #1 called " + count(count) + + " expected it to be called " + expected(expectedIncrement)); + } + count = authTwo.count.get(); + if (count != expectedIncrement) { + throw new AssertionError("Authenticator #2 called " + count(count) + + " expected it to be called " + expected(expectedIncrement)); + } + count = AUTHENTICATOR.count.get(); + if (count != defaultCount) { + throw new AssertionError("Default Authenticator called " + count(count) + + " expected it to be called " + expected(defaultCount)); + } + + // Now tries with the default authenticator: it should be invoked. + System.out.println("\nClient: Using the default authenticator: " + + toString(null)); + HTTPTestClient.connect(protocol, server, mode, null); + count = authOne.count.get(); + if (count != expectedIncrement) { + throw new AssertionError("Authenticator #1 called " + count(count) + + " expected it to be called " + expected(expectedIncrement)); + } + count = authTwo.count.get(); + if (count != expectedIncrement) { + throw new AssertionError("Authenticator #2 called " + count(count) + + " expected it to be called " + expected(expectedIncrement)); + } + count = AUTHENTICATOR.count.get(); + if (count != defaultCount + expectedIncrement) { + throw new AssertionError("Default Authenticator called " + count(count) + + " expected it to be called " + expected(defaultCount + expectedIncrement)); + } + + // Now tries with explicitly setting the default authenticator: it should + // be invoked again. + // Uncomment the code below when 8169068 is available. +// System.out.println("\nClient: Explicitly setting the default authenticator: " +// + toString(Authenticator.getDefault())); +// HTTPTestClient.connect(protocol, server, mode, Authenticator.getDefault()); +// count = authOne.count.get(); +// if (count != expectedIncrement) { +// throw new AssertionError("Authenticator #1 called " + count(count) +// + " expected it to be called " + expected(expectedIncrement)); +// } +// count = authTwo.count.get(); +// if (count != expectedIncrement) { +// throw new AssertionError("Authenticator #2 called " + count(count) +// + " expected it to be called " + expected(expectedIncrement)); +// } +// count = AUTHENTICATOR.count.get(); +// if (count != defaultCount + 2 * expectedIncrement) { +// throw new AssertionError("Default Authenticator called " + count(count) +// + " expected it to be called " +// + expected(defaultCount + 2 * expectedIncrement)); +// } + + // Now tries to set an authenticator on a connected connection. + URL url = url(protocol, server.getAddress(), "/"); + Proxy proxy = proxy(server, mode); + HttpURLConnection conn = openConnection(url, mode, proxy); + try { + conn.setAuthenticator(null); + throw new RuntimeException("Expected NullPointerException" + + " trying to set a null authenticator" + + " not raised."); + } catch (NullPointerException npe) { + System.out.println("Client: caught expected NPE" + + " trying to set a null authenticator: " + + npe); + } + conn.connect(); + try { + try { + conn.setAuthenticator(authOne); + throw new RuntimeException("Expected IllegalStateException" + + " trying to set an authenticator after connect" + + " not raised."); + } catch (IllegalStateException ise) { + System.out.println("Client: caught expected ISE" + + " trying to set an authenticator after connect: " + + ise); + } + // Uncomment the code below when 8169068 is available. +// try { +// conn.setAuthenticator(Authenticator.getDefault()); +// throw new RuntimeException("Expected IllegalStateException" +// + " trying to set an authenticator after connect" +// + " not raised."); +// } catch (IllegalStateException ise) { +// System.out.println("Client: caught expected ISE" +// + " trying to set an authenticator after connect: " +// + ise); +// } + try { + conn.setAuthenticator(null); + throw new RuntimeException("Expected" + + " IllegalStateException or NullPointerException" + + " trying to set a null authenticator after connect" + + " not raised."); + } catch (IllegalStateException | NullPointerException xxe) { + System.out.println("Client: caught expected " + + xxe.getClass().getSimpleName() + + " trying to set a null authenticator after connect: " + + xxe); + } + } finally { + conn.disconnect(); + } + + // double check that authOne and authTwo haven't been invoked. + count = authOne.count.get(); + if (count != expectedIncrement) { + throw new AssertionError("Authenticator #1 called " + count(count) + + " expected it to be called " + expected(expectedIncrement)); + } + count = authTwo.count.get(); + if (count != expectedIncrement) { + throw new AssertionError("Authenticator #2 called " + count(count) + + " expected it to be called " + expected(expectedIncrement)); + } + + // All good! + // return the number of times the default authenticator is supposed + // to have been called. + return scheme == HttpSchemeType.NONE ? 0 : 1 * EXPECTED_AUTH_CALLS_PER_TEST; + } + + static String toString(Authenticator a) { + return sun.net.www.protocol.http.AuthenticatorKeys.getKey(a); + } + +} diff --git a/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPTest.java b/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPTest.java new file mode 100644 index 00000000000..87e9a4b407f --- /dev/null +++ b/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPTest.java @@ -0,0 +1,283 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.Authenticator; +import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.net.MalformedURLException; +import java.net.PasswordAuthentication; +import java.net.Proxy; +import java.net.URL; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Stream; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import jdk.testlibrary.SimpleSSLContext; + +/** + * @test + * @bug 8169415 + * @library /lib/testlibrary/ + * @modules java.base/sun.net.www + * jdk.httpserver/sun.net.httpserver + * @build jdk.testlibrary.SimpleSSLContext HTTPTest HTTPTestServer HTTPTestClient + * @summary A simple HTTP test that starts an echo server supporting Digest + * authentication, then starts a regular HTTP client to invoke it. + * The client first does a GET request on "/", then follows on + * with a POST request that sends "Hello World!" to the server. + * The client expects to receive "Hello World!" in return. + * The test supports several execution modes: + * SERVER: The server performs Digest Server authentication; + * PROXY: The server pretends to be a proxy and performs + * Digest Proxy authentication; + * SERVER307: The server redirects the client (307) to another + * server that perform Digest authentication; + * PROXY305: The server attempts to redirect + * the client to a proxy using 305 code; + * @run main/othervm HTTPTest SERVER + * @run main/othervm HTTPTest PROXY + * @run main/othervm HTTPTest SERVER307 + * @run main/othervm HTTPTest PROXY305 + * + * @author danielfuchs + */ +public class HTTPTest { + + public static final boolean DEBUG = + Boolean.parseBoolean(System.getProperty("test.debug", "false")); + public static enum HttpAuthType { SERVER, PROXY, SERVER307, PROXY305 }; + public static enum HttpProtocolType { HTTP, HTTPS }; + public static enum HttpSchemeType { NONE, BASICSERVER, BASIC, DIGEST }; + public static final HttpAuthType DEFAULT_HTTP_AUTH_TYPE = HttpAuthType.SERVER; + public static final HttpProtocolType DEFAULT_PROTOCOL_TYPE = HttpProtocolType.HTTP; + public static final HttpSchemeType DEFAULT_SCHEME_TYPE = HttpSchemeType.DIGEST; + + public static class HttpTestAuthenticator extends Authenticator { + private final String realm; + private final String username; + // Used to prevent incrementation of 'count' when calling the + // authenticator from the server side. + private final ThreadLocal skipCount = new ThreadLocal<>(); + // count will be incremented every time getPasswordAuthentication() + // is called from the client side. + final AtomicInteger count = new AtomicInteger(); + + public HttpTestAuthenticator(String realm, String username) { + this.realm = realm; + this.username = username; + } + + @Override + protected PasswordAuthentication getPasswordAuthentication() { + if (skipCount.get() == null || skipCount.get().booleanValue() == false) { + System.out.println("Authenticator called: " + count.incrementAndGet()); + } + return new PasswordAuthentication(getUserName(), + new char[] {'b','a','r'}); + } + + // Called by the server side to get the password of the user + // being authentified. + public final char[] getPassword(String user) { + if (user.equals(username)) { + skipCount.set(Boolean.TRUE); + try { + return getPasswordAuthentication().getPassword(); + } finally { + skipCount.set(Boolean.FALSE); + } + } + throw new SecurityException("User unknown: " + user); + } + + public final String getUserName() { + return username; + } + public final String getRealm() { + return realm; + } + + } + public static final HttpTestAuthenticator AUTHENTICATOR; + static { + AUTHENTICATOR = new HttpTestAuthenticator("dublin", "foox"); + Authenticator.setDefault(AUTHENTICATOR); + } + + static { + try { + HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }); + SSLContext.setDefault(new SimpleSSLContext().get()); + } catch (IOException ex) { + throw new ExceptionInInitializerError(ex); + } + } + + static final Logger logger = Logger.getLogger ("com.sun.net.httpserver"); + static { + if (DEBUG) logger.setLevel(Level.ALL); + Stream.of(Logger.getLogger("").getHandlers()) + .forEach(h -> h.setLevel(Level.ALL)); + } + + static final int EXPECTED_AUTH_CALLS_PER_TEST = 1; + + public static void main(String[] args) throws Exception { + // new HTTPTest().execute(HttpAuthType.SERVER.name()); + new HTTPTest().execute(args); + } + + public void execute(String... args) throws Exception { + Stream modes; + if (args == null || args.length == 0) { + modes = Stream.of(HttpAuthType.values()); + } else { + modes = Stream.of(args).map(HttpAuthType::valueOf); + } + modes.forEach(this::test); + System.out.println("Test PASSED - Authenticator called: " + + expected(AUTHENTICATOR.count.get())); + } + + public void test(HttpAuthType mode) { + for (HttpProtocolType type: HttpProtocolType.values()) { + test(type, mode); + } + } + + public HttpSchemeType getHttpSchemeType() { + return DEFAULT_SCHEME_TYPE; + } + + public void test(HttpProtocolType protocol, HttpAuthType mode) { + if (mode == HttpAuthType.PROXY305 && protocol == HttpProtocolType.HTTPS ) { + // silently skip unsupported test combination + return; + } + System.out.println("\n**** Testing " + protocol + " " + + mode + " mode ****\n"); + int authCount = AUTHENTICATOR.count.get(); + int expectedIncrement = 0; + try { + // Creates an HTTP server that echoes back whatever is in the + // request body. + HTTPTestServer server = + HTTPTestServer.create(protocol, + mode, + AUTHENTICATOR, + getHttpSchemeType()); + try { + expectedIncrement += run(server, protocol, mode); + } finally { + server.stop(); + } + } catch (IOException ex) { + ex.printStackTrace(System.err); + throw new UncheckedIOException(ex); + } + int count = AUTHENTICATOR.count.get(); + if (count != authCount + expectedIncrement) { + throw new AssertionError("Authenticator called " + count(count) + + " expected it to be called " + + expected(authCount + expectedIncrement)); + } + } + + /** + * Runs the test with the given parameters. + * @param server The server + * @param protocol The protocol (HTTP/HTTPS) + * @param mode The mode (PROXY, SERVER, SERVER307...) + * @return The number of times the default authenticator should have been + * called. + * @throws IOException in case of connection or protocol issues + */ + public int run(HTTPTestServer server, + HttpProtocolType protocol, + HttpAuthType mode) + throws IOException + { + // Connect to the server with a GET request, then with a + // POST that contains "Hello World!" + HTTPTestClient.connect(protocol, server, mode, null); + // return the number of times the default authenticator is supposed + // to have been called. + return EXPECTED_AUTH_CALLS_PER_TEST; + } + + public static String count(int count) { + switch(count) { + case 0: return "not even once"; + case 1: return "once"; + case 2: return "twice"; + default: return String.valueOf(count) + " times"; + } + } + + public static String expected(int count) { + switch(count) { + default: return count(count); + } + } + public static String protocol(HttpProtocolType type) { + return type.name().toLowerCase(Locale.US); + } + + public static URL url(HttpProtocolType protocol, InetSocketAddress address, + String path) throws MalformedURLException { + return new URL(protocol(protocol), + address.getHostString(), + address.getPort(), path); + } + + public static Proxy proxy(HTTPTestServer server, HttpAuthType authType) { + return (authType == HttpAuthType.PROXY) + ? new Proxy(Proxy.Type.HTTP, server.getAddress()) + : null; + } + + public static HttpURLConnection openConnection(URL url, + HttpAuthType authType, + Proxy proxy) + throws IOException { + + HttpURLConnection conn = (HttpURLConnection) + (authType == HttpAuthType.PROXY + ? url.openConnection(proxy) + : url.openConnection()); + return conn; + } +} diff --git a/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPTestClient.java b/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPTestClient.java new file mode 100644 index 00000000000..3da0a7ae2d9 --- /dev/null +++ b/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPTestClient.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.IOException; +import java.net.Authenticator; +import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.URL; +import javax.net.ssl.HttpsURLConnection; + +/** + * A simple Http client that connects to the HTTPTestServer. + * @author danielfuchs + */ +public class HTTPTestClient extends HTTPTest { + + public static void connect(HttpProtocolType protocol, + HTTPTestServer server, + HttpAuthType authType, + Authenticator auth) + throws IOException { + + InetSocketAddress address = server.getAddress(); + final URL url = url(protocol, address, "/"); + final Proxy proxy = proxy(server, authType); + + System.out.println("Client: FIRST request: " + url + " GET"); + HttpURLConnection conn = openConnection(url, authType, proxy); + configure(conn, auth); + System.out.println("Response code: " + conn.getResponseCode()); + String result = new String(conn.getInputStream().readAllBytes(), "UTF-8"); + System.out.println("Response body: " + result); + if (!result.isEmpty()) { + throw new RuntimeException("Unexpected response to GET: " + result); + } + System.out.println("\nClient: NEXT request: " + url + " POST"); + conn = openConnection(url, authType, proxy); + configure(conn, auth); + conn.setRequestMethod("POST"); + conn.setDoOutput(true); + conn.setDoInput(true); + conn.getOutputStream().write("Hello World!".getBytes("UTF-8")); + System.out.println("Response code: " + conn.getResponseCode()); + result = new String(conn.getInputStream().readAllBytes(), "UTF-8"); + System.out.println("Response body: " + result); + if ("Hello World!".equals(result)) { + System.out.println("Test passed!"); + } else { + throw new RuntimeException("Unexpected response to POST: " + result); + } + } + + private static void configure(HttpURLConnection conn, Authenticator auth) + throws IOException { + if (auth != null) { + conn.setAuthenticator(auth); + } + if (conn instanceof HttpsURLConnection) { + System.out.println("Client: configuring SSL connection"); + // We have set a default SSLContext so we don't need to do + // anything here. Otherwise it could look like: + // HttpsURLConnection httpsConn = (HttpsURLConnection)conn; + // httpsConn.setSSLSocketFactory( + // new SimpleSSLContext().get().getSocketFactory()); + } + } + +} diff --git a/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPTestServer.java b/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPTestServer.java new file mode 100644 index 00000000000..6479de13700 --- /dev/null +++ b/jdk/test/java/net/HttpURLConnection/SetAuthenticator/HTTPTestServer.java @@ -0,0 +1,995 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.net.httpserver.BasicAuthenticator; +import com.sun.net.httpserver.Filter; +import com.sun.net.httpserver.Headers; +import com.sun.net.httpserver.HttpContext; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsParameters; +import com.sun.net.httpserver.HttpsServer; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.Writer; +import java.math.BigInteger; +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.MalformedURLException; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.URL; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Objects; +import java.util.Random; +import java.util.stream.Collectors; +import javax.net.ssl.SSLContext; +import sun.net.www.HeaderParser; + +/** + * A simple HTTP server that supports Digest authentication. + * By default this server will echo back whatever is present + * in the request body. + * @author danielfuchs + */ +public class HTTPTestServer extends HTTPTest { + + final HttpServer serverImpl; // this server endpoint + final HTTPTestServer redirect; // the target server where to redirect 3xx + final HttpHandler delegate; // unused + + private HTTPTestServer(HttpServer server, HTTPTestServer target, + HttpHandler delegate) { + this.serverImpl = server; + this.redirect = target; + this.delegate = delegate; + } + + public static void main(String[] args) + throws IOException { + + HTTPTestServer server = create(HTTPTest.DEFAULT_PROTOCOL_TYPE, + HTTPTest.DEFAULT_HTTP_AUTH_TYPE, + HTTPTest.AUTHENTICATOR, + HTTPTest.DEFAULT_SCHEME_TYPE); + try { + System.out.println("Server created at " + server.getAddress()); + System.out.println("Strike to exit"); + System.in.read(); + } finally { + System.out.println("stopping server"); + server.stop(); + } + } + + private static String toString(Headers headers) { + return headers.entrySet().stream() + .map((e) -> e.getKey() + ": " + e.getValue()) + .collect(Collectors.joining("\n")); + } + + public static HTTPTestServer create(HttpProtocolType protocol, + HttpAuthType authType, + HttpTestAuthenticator auth, + HttpSchemeType schemeType) + throws IOException { + return create(protocol, authType, auth, schemeType, null); + } + + public static HTTPTestServer create(HttpProtocolType protocol, + HttpAuthType authType, + HttpTestAuthenticator auth, + HttpSchemeType schemeType, + HttpHandler delegate) + throws IOException { + Objects.requireNonNull(authType); + Objects.requireNonNull(auth); + switch(authType) { + // A server that performs Server Digest authentication. + case SERVER: return createServer(protocol, authType, auth, + schemeType, delegate, "/"); + // A server that pretends to be a Proxy and performs + // Proxy Digest authentication. If protocol is HTTPS, + // then this will create a HttpsProxyTunnel that will + // handle the CONNECT request for tunneling. + case PROXY: return createProxy(protocol, authType, auth, + schemeType, delegate, "/"); + // A server that sends 307 redirect to a server that performs + // Digest authentication. + // Note: 301 doesn't work here because it transforms POST into GET. + case SERVER307: return createServerAndRedirect(protocol, + HttpAuthType.SERVER, + auth, schemeType, + delegate, 307); + // A server that sends 305 redirect to a proxy that performs + // Digest authentication. + case PROXY305: return createServerAndRedirect(protocol, + HttpAuthType.PROXY, + auth, schemeType, + delegate, 305); + default: + throw new InternalError("Unknown server type: " + authType); + } + } + + static HttpServer createHttpServer(HttpProtocolType protocol) throws IOException { + switch (protocol) { + case HTTP: return HttpServer.create(); + case HTTPS: return configure(HttpsServer.create()); + default: throw new InternalError("Unsupported protocol " + protocol); + } + } + + static HttpsServer configure(HttpsServer server) throws IOException { + try { + SSLContext ctx = SSLContext.getDefault(); + server.setHttpsConfigurator(new Configurator(ctx)); + } catch (NoSuchAlgorithmException ex) { + throw new IOException(ex); + } + return server; + } + + + static void setContextAuthenticator(HttpContext ctxt, + HttpTestAuthenticator auth) { + final String realm = auth.getRealm(); + com.sun.net.httpserver.Authenticator authenticator = + new BasicAuthenticator(realm) { + @Override + public boolean checkCredentials(String username, String pwd) { + return auth.getUserName().equals(username) + && new String(auth.getPassword(username)).equals(pwd); + } + }; + ctxt.setAuthenticator(authenticator); + } + + public static HTTPTestServer createServer(HttpProtocolType protocol, + HttpAuthType authType, + HttpTestAuthenticator auth, + HttpSchemeType schemeType, + HttpHandler delegate, + String path) + throws IOException { + Objects.requireNonNull(authType); + Objects.requireNonNull(auth); + + HttpServer impl = createHttpServer(protocol); + final HTTPTestServer server = new HTTPTestServer(impl, null, delegate); + final HttpHandler hh = server.createHandler(schemeType, auth, authType); + HttpContext ctxt = impl.createContext(path, hh); + server.configureAuthentication(ctxt, schemeType, auth, authType); + impl.bind(new InetSocketAddress("127.0.0.1", 0), 0); + impl.start(); + return server; + } + + public static HTTPTestServer createProxy(HttpProtocolType protocol, + HttpAuthType authType, + HttpTestAuthenticator auth, + HttpSchemeType schemeType, + HttpHandler delegate, + String path) + throws IOException { + Objects.requireNonNull(authType); + Objects.requireNonNull(auth); + + HttpServer impl = createHttpServer(protocol); + final HTTPTestServer server = protocol == HttpProtocolType.HTTPS + ? new HttpsProxyTunnel(impl, null, delegate) + : new HTTPTestServer(impl, null, delegate); + final HttpHandler hh = server.createHandler(schemeType, auth, authType); + HttpContext ctxt = impl.createContext(path, hh); + server.configureAuthentication(ctxt, schemeType, auth, authType); + + impl.bind(new InetSocketAddress("127.0.0.1", 0), 0); + impl.start(); + + return server; + } + + public static HTTPTestServer createServerAndRedirect( + HttpProtocolType protocol, + HttpAuthType targetAuthType, + HttpTestAuthenticator auth, + HttpSchemeType schemeType, + HttpHandler targetDelegate, + int code300) + throws IOException { + Objects.requireNonNull(targetAuthType); + Objects.requireNonNull(auth); + + // The connection between client and proxy can only + // be a plain connection: SSL connection to proxy + // is not supported by our client connection. + HttpProtocolType targetProtocol = targetAuthType == HttpAuthType.PROXY + ? HttpProtocolType.HTTP + : protocol; + HTTPTestServer redirectTarget = + (targetAuthType == HttpAuthType.PROXY) + ? createProxy(protocol, targetAuthType, + auth, schemeType, targetDelegate, "/") + : createServer(targetProtocol, targetAuthType, + auth, schemeType, targetDelegate, "/"); + HttpServer impl = createHttpServer(protocol); + final HTTPTestServer redirectingServer = + new HTTPTestServer(impl, redirectTarget, null); + InetSocketAddress redirectAddr = redirectTarget.getAddress(); + URL locationURL = url(targetProtocol, redirectAddr, "/"); + final HttpHandler hh = redirectingServer.create300Handler(locationURL, + HttpAuthType.SERVER, code300); + impl.createContext("/", hh); + impl.bind(new InetSocketAddress("127.0.0.1", 0), 0); + impl.start(); + return redirectingServer; + } + + public InetSocketAddress getAddress() { + return serverImpl.getAddress(); + } + + public void stop() { + serverImpl.stop(0); + if (redirect != null) { + redirect.stop(); + } + } + + protected void writeResponse(HttpExchange he) throws IOException { + if (delegate == null) { + he.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); + he.getResponseBody().write(he.getRequestBody().readAllBytes()); + } else { + delegate.handle(he); + } + } + + private HttpHandler createHandler(HttpSchemeType schemeType, + HttpTestAuthenticator auth, + HttpAuthType authType) { + return new HttpNoAuthHandler(authType); + } + + private void configureAuthentication(HttpContext ctxt, + HttpSchemeType schemeType, + HttpTestAuthenticator auth, + HttpAuthType authType) { + switch(schemeType) { + case DIGEST: + // DIGEST authentication is handled by the handler. + ctxt.getFilters().add(new HttpDigestFilter(auth, authType)); + break; + case BASIC: + // BASIC authentication is handled by the filter. + ctxt.getFilters().add(new HttpBasicFilter(auth, authType)); + break; + case BASICSERVER: + switch(authType) { + case PROXY: case PROXY305: + // HttpServer can't support Proxy-type authentication + // => we do as if BASIC had been specified, and we will + // handle authentication in the handler. + ctxt.getFilters().add(new HttpBasicFilter(auth, authType)); + break; + case SERVER: case SERVER307: + // Basic authentication is handled by HttpServer + // directly => the filter should not perform + // authentication again. + setContextAuthenticator(ctxt, auth); + ctxt.getFilters().add(new HttpNoAuthFilter(authType)); + break; + default: + throw new InternalError("Invalid combination scheme=" + + schemeType + " authType=" + authType); + } + case NONE: + // No authentication at all. + ctxt.getFilters().add(new HttpNoAuthFilter(authType)); + break; + default: + throw new InternalError("No such scheme: " + schemeType); + } + } + + private HttpHandler create300Handler(URL proxyURL, + HttpAuthType type, int code300) throws MalformedURLException { + return new Http3xxHandler(proxyURL, type, code300); + } + + // Abstract HTTP filter class. + private abstract static class AbstractHttpFilter extends Filter { + + final HttpAuthType authType; + final String type; + public AbstractHttpFilter(HttpAuthType authType, String type) { + this.authType = authType; + this.type = type; + } + + String getLocation() { + return "Location"; + } + String getAuthenticate() { + return authType == HttpAuthType.PROXY + ? "Proxy-Authenticate" : "WWW-Authenticate"; + } + String getAuthorization() { + return authType == HttpAuthType.PROXY + ? "Proxy-Authorization" : "Authorization"; + } + int getUnauthorizedCode() { + return authType == HttpAuthType.PROXY + ? HttpURLConnection.HTTP_PROXY_AUTH + : HttpURLConnection.HTTP_UNAUTHORIZED; + } + String getKeepAlive() { + return "keep-alive"; + } + String getConnection() { + return authType == HttpAuthType.PROXY + ? "Proxy-Connection" : "Connection"; + } + protected abstract boolean isAuthentified(HttpExchange he) throws IOException; + protected abstract void requestAuthentication(HttpExchange he) throws IOException; + protected void accept(HttpExchange he, Chain chain) throws IOException { + chain.doFilter(he); + } + + @Override + public String description() { + return "Filter for " + type; + } + @Override + public void doFilter(HttpExchange he, Chain chain) throws IOException { + try { + System.out.println(type + ": Got " + he.getRequestMethod() + + ": " + he.getRequestURI() + + "\n" + HTTPTestServer.toString(he.getRequestHeaders())); + if (!isAuthentified(he)) { + try { + requestAuthentication(he); + he.sendResponseHeaders(getUnauthorizedCode(), 0); + System.out.println(type + + ": Sent back " + getUnauthorizedCode()); + } finally { + he.close(); + } + } else { + accept(he, chain); + } + } catch (RuntimeException | Error | IOException t) { + System.err.println(type + + ": Unexpected exception while handling request: " + t); + t.printStackTrace(System.err); + he.close(); + throw t; + } + } + + } + + private final static class DigestResponse { + final String realm; + final String username; + final String nonce; + final String cnonce; + final String nc; + final String uri; + final String algorithm; + final String response; + final String qop; + final String opaque; + + public DigestResponse(String realm, String username, String nonce, + String cnonce, String nc, String uri, + String algorithm, String qop, String opaque, + String response) { + this.realm = realm; + this.username = username; + this.nonce = nonce; + this.cnonce = cnonce; + this.nc = nc; + this.uri = uri; + this.algorithm = algorithm; + this.qop = qop; + this.opaque = opaque; + this.response = response; + } + + String getAlgorithm(String defval) { + return algorithm == null ? defval : algorithm; + } + String getQoP(String defval) { + return qop == null ? defval : qop; + } + + // Code stolen from DigestAuthentication: + + private static final char charArray[] = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' + }; + + private static String encode(String src, char[] passwd, MessageDigest md) { + try { + md.update(src.getBytes("ISO-8859-1")); + } catch (java.io.UnsupportedEncodingException uee) { + assert false; + } + if (passwd != null) { + byte[] passwdBytes = new byte[passwd.length]; + for (int i=0; i>> 4) & 0xf); + res.append(charArray[hashchar]); + hashchar = (digest[i] & 0xf); + res.append(charArray[hashchar]); + } + return res.toString(); + } + + public static String computeDigest(boolean isRequest, + String reqMethod, + char[] password, + DigestResponse params) + throws NoSuchAlgorithmException + { + + String A1, HashA1; + String algorithm = params.getAlgorithm("MD5"); + boolean md5sess = algorithm.equalsIgnoreCase ("MD5-sess"); + + MessageDigest md = MessageDigest.getInstance(md5sess?"MD5":algorithm); + + if (params.username == null) { + throw new IllegalArgumentException("missing username"); + } + if (params.realm == null) { + throw new IllegalArgumentException("missing realm"); + } + if (params.uri == null) { + throw new IllegalArgumentException("missing uri"); + } + if (params.nonce == null) { + throw new IllegalArgumentException("missing nonce"); + } + + A1 = params.username + ":" + params.realm + ":"; + HashA1 = encode(A1, password, md); + + String A2; + if (isRequest) { + A2 = reqMethod + ":" + params.uri; + } else { + A2 = ":" + params.uri; + } + String HashA2 = encode(A2, null, md); + String combo, finalHash; + + if ("auth".equals(params.qop)) { /* RRC2617 when qop=auth */ + if (params.cnonce == null) { + throw new IllegalArgumentException("missing nonce"); + } + if (params.nc == null) { + throw new IllegalArgumentException("missing nonce"); + } + combo = HashA1+ ":" + params.nonce + ":" + params.nc + ":" + + params.cnonce + ":auth:" +HashA2; + + } else { /* for compatibility with RFC2069 */ + combo = HashA1 + ":" + + params.nonce + ":" + + HashA2; + } + finalHash = encode(combo, null, md); + return finalHash; + } + + public static DigestResponse create(String raw) { + String username, realm, nonce, nc, uri, response, cnonce, + algorithm, qop, opaque; + HeaderParser parser = new HeaderParser(raw); + username = parser.findValue("username"); + realm = parser.findValue("realm"); + nonce = parser.findValue("nonce"); + nc = parser.findValue("nc"); + uri = parser.findValue("uri"); + cnonce = parser.findValue("cnonce"); + response = parser.findValue("response"); + algorithm = parser.findValue("algorithm"); + qop = parser.findValue("qop"); + opaque = parser.findValue("opaque"); + return new DigestResponse(realm, username, nonce, cnonce, nc, uri, + algorithm, qop, opaque, response); + } + + } + + private class HttpNoAuthFilter extends AbstractHttpFilter { + + public HttpNoAuthFilter(HttpAuthType authType) { + super(authType, authType == HttpAuthType.SERVER + ? "NoAuth Server" : "NoAuth Proxy"); + } + + @Override + protected boolean isAuthentified(HttpExchange he) throws IOException { + return true; + } + + @Override + protected void requestAuthentication(HttpExchange he) throws IOException { + throw new InternalError("Should not com here"); + } + + @Override + public String description() { + return "Passthrough Filter"; + } + + } + + // An HTTP Filter that performs Basic authentication + private class HttpBasicFilter extends AbstractHttpFilter { + + private final HttpTestAuthenticator auth; + public HttpBasicFilter(HttpTestAuthenticator auth, HttpAuthType authType) { + super(authType, authType == HttpAuthType.SERVER + ? "Basic Server" : "Basic Proxy"); + this.auth = auth; + } + + @Override + protected void requestAuthentication(HttpExchange he) + throws IOException { + he.getResponseHeaders().add(getAuthenticate(), + "Basic realm=\"" + auth.getRealm() + "\""); + System.out.println(type + ": Requesting Basic Authentication " + + he.getResponseHeaders().getFirst(getAuthenticate())); + } + + @Override + protected boolean isAuthentified(HttpExchange he) { + if (he.getRequestHeaders().containsKey(getAuthorization())) { + List authorization = + he.getRequestHeaders().get(getAuthorization()); + for (String a : authorization) { + System.out.println(type + ": processing " + a); + int sp = a.indexOf(' '); + if (sp < 0) return false; + String scheme = a.substring(0, sp); + if (!"Basic".equalsIgnoreCase(scheme)) { + System.out.println(type + ": Unsupported scheme '" + + scheme +"'"); + return false; + } + if (a.length() <= sp+1) { + System.out.println(type + ": value too short for '" + + scheme +"'"); + return false; + } + a = a.substring(sp+1); + return validate(a); + } + return false; + } + return false; + } + + boolean validate(String a) { + byte[] b = Base64.getDecoder().decode(a); + String userpass = new String (b); + int colon = userpass.indexOf (':'); + String uname = userpass.substring (0, colon); + String pass = userpass.substring (colon+1); + return auth.getUserName().equals(uname) && + new String(auth.getPassword(uname)).equals(pass); + } + + @Override + public String description() { + return "Filter for " + type; + } + + } + + + // An HTTP Filter that performs Digest authentication + private class HttpDigestFilter extends AbstractHttpFilter { + + // This is a very basic DIGEST - used only for the purpose of testing + // the client implementation. Therefore we can get away with never + // updating the server nonce as it makes the implementation of the + // server side digest simpler. + private final HttpTestAuthenticator auth; + private final byte[] nonce; + private final String ns; + public HttpDigestFilter(HttpTestAuthenticator auth, HttpAuthType authType) { + super(authType, authType == HttpAuthType.SERVER + ? "Digest Server" : "Digest Proxy"); + this.auth = auth; + nonce = new byte[16]; + new Random(Instant.now().toEpochMilli()).nextBytes(nonce); + ns = new BigInteger(1, nonce).toString(16); + } + + @Override + protected void requestAuthentication(HttpExchange he) + throws IOException { + he.getResponseHeaders().add(getAuthenticate(), + "Digest realm=\"" + auth.getRealm() + "\"," + + "\r\n qop=\"auth\"," + + "\r\n nonce=\"" + ns +"\""); + System.out.println(type + ": Requesting Digest Authentication " + + he.getResponseHeaders().getFirst(getAuthenticate())); + } + + @Override + protected boolean isAuthentified(HttpExchange he) { + if (he.getRequestHeaders().containsKey(getAuthorization())) { + List authorization = he.getRequestHeaders().get(getAuthorization()); + for (String a : authorization) { + System.out.println(type + ": processing " + a); + int sp = a.indexOf(' '); + if (sp < 0) return false; + String scheme = a.substring(0, sp); + if (!"Digest".equalsIgnoreCase(scheme)) { + System.out.println(type + ": Unsupported scheme '" + scheme +"'"); + return false; + } + if (a.length() <= sp+1) { + System.out.println(type + ": value too short for '" + scheme +"'"); + return false; + } + a = a.substring(sp+1); + DigestResponse dgr = DigestResponse.create(a); + return validate(he.getRequestMethod(), dgr); + } + return false; + } + return false; + } + + boolean validate(String reqMethod, DigestResponse dg) { + if (!"MD5".equalsIgnoreCase(dg.getAlgorithm("MD5"))) { + System.out.println(type + ": Unsupported algorithm " + + dg.algorithm); + return false; + } + if (!"auth".equalsIgnoreCase(dg.getQoP("auth"))) { + System.out.println(type + ": Unsupported qop " + + dg.qop); + return false; + } + try { + if (!dg.nonce.equals(ns)) { + System.out.println(type + ": bad nonce returned by client: " + + nonce + " expected " + ns); + return false; + } + if (dg.response == null) { + System.out.println(type + ": missing digest response."); + return false; + } + char[] pa = auth.getPassword(dg.username); + return verify(reqMethod, dg, pa); + } catch(IllegalArgumentException | SecurityException + | NoSuchAlgorithmException e) { + System.out.println(type + ": " + e.getMessage()); + return false; + } + } + + boolean verify(String reqMethod, DigestResponse dg, char[] pw) + throws NoSuchAlgorithmException { + String response = DigestResponse.computeDigest(true, reqMethod, pw, dg); + if (!dg.response.equals(response)) { + System.out.println(type + ": bad response returned by client: " + + dg.response + " expected " + response); + return false; + } else { + System.out.println(type + ": verified response " + response); + } + return true; + } + + @Override + public String description() { + return "Filter for DIGEST authentication"; + } + } + + // Abstract HTTP handler class. + private abstract static class AbstractHttpHandler implements HttpHandler { + + final HttpAuthType authType; + final String type; + public AbstractHttpHandler(HttpAuthType authType, String type) { + this.authType = authType; + this.type = type; + } + + String getLocation() { + return "Location"; + } + + @Override + public void handle(HttpExchange he) throws IOException { + try { + sendResponse(he); + } catch (RuntimeException | Error | IOException t) { + System.err.println(type + + ": Unexpected exception while handling request: " + t); + t.printStackTrace(System.err); + throw t; + } finally { + he.close(); + } + } + + protected abstract void sendResponse(HttpExchange he) throws IOException; + + } + + private class HttpNoAuthHandler extends AbstractHttpHandler { + + public HttpNoAuthHandler(HttpAuthType authType) { + super(authType, authType == HttpAuthType.SERVER + ? "NoAuth Server" : "NoAuth Proxy"); + } + + @Override + protected void sendResponse(HttpExchange he) throws IOException { + HTTPTestServer.this.writeResponse(he); + } + + } + + // A dummy HTTP Handler that redirects all incoming requests + // by sending a back 3xx response code (301, 305, 307 etc..) + private class Http3xxHandler extends AbstractHttpHandler { + + private final URL redirectTargetURL; + private final int code3XX; + public Http3xxHandler(URL proxyURL, HttpAuthType authType, int code300) { + super(authType, "Server" + code300); + this.redirectTargetURL = proxyURL; + this.code3XX = code300; + } + + int get3XX() { + return code3XX; + } + + @Override + public void sendResponse(HttpExchange he) throws IOException { + System.out.println(type + ": Got " + he.getRequestMethod() + + ": " + he.getRequestURI() + + "\n" + HTTPTestServer.toString(he.getRequestHeaders())); + System.out.println(type + ": Redirecting to " + + (authType == HttpAuthType.PROXY305 + ? "proxy" : "server")); + he.getResponseHeaders().add(getLocation(), + redirectTargetURL.toExternalForm().toString()); + he.sendResponseHeaders(get3XX(), 0); + System.out.println(type + ": Sent back " + get3XX() + " " + + getLocation() + ": " + redirectTargetURL.toExternalForm().toString()); + } + } + + static class Configurator extends HttpsConfigurator { + public Configurator(SSLContext ctx) { + super(ctx); + } + + @Override + public void configure (HttpsParameters params) { + params.setSSLParameters (getSSLContext().getSupportedSSLParameters()); + } + } + + // This is a bit hacky: HttpsProxyTunnel is an HTTPTestServer hidden + // behind a fake proxy that only understands CONNECT requests. + // The fake proxy is just a server socket that intercept the + // CONNECT and then redirect streams to the real server. + static class HttpsProxyTunnel extends HTTPTestServer + implements Runnable { + + final ServerSocket ss; + public HttpsProxyTunnel(HttpServer server, HTTPTestServer target, + HttpHandler delegate) + throws IOException { + super(server, target, delegate); + System.out.flush(); + System.err.println("WARNING: HttpsProxyTunnel is an experimental test class"); + ss = new ServerSocket(0, 0, InetAddress.getByName("127.0.0.1")); + start(); + } + + final void start() throws IOException { + Thread t = new Thread(this, "ProxyThread"); + t.setDaemon(true); + t.start(); + } + + @Override + public void stop() { + super.stop(); + try { + ss.close(); + } catch (IOException ex) { + if (DEBUG) ex.printStackTrace(System.out); + } + } + + // Pipe the input stream to the output stream. + private synchronized Thread pipe(InputStream is, OutputStream os, char tag) { + return new Thread("TunnelPipe("+tag+")") { + @Override + public void run() { + try { + try { + int c; + while ((c = is.read()) != -1) { + os.write(c); + os.flush(); + // if DEBUG prints a + or a - for each transferred + // character. + if (DEBUG) System.out.print(tag); + } + is.close(); + } finally { + os.close(); + } + } catch (IOException ex) { + if (DEBUG) ex.printStackTrace(System.out); + } + } + }; + } + + @Override + public InetSocketAddress getAddress() { + return new InetSocketAddress(ss.getInetAddress(), ss.getLocalPort()); + } + + // This is a bit shaky. It doesn't handle continuation + // lines, but our client shouldn't send any. + // Read a line from the input stream, swallowing the final + // \r\n sequence. Stops at the first \n, doesn't complain + // if it wasn't preceded by '\r'. + // + String readLine(InputStream r) throws IOException { + StringBuilder b = new StringBuilder(); + int c; + while ((c = r.read()) != -1) { + if (c == '\n') break; + b.appendCodePoint(c); + } + if (b.codePointAt(b.length() -1) == '\r') { + b.delete(b.length() -1, b.length()); + } + return b.toString(); + } + + @Override + public void run() { + Socket clientConnection = null; + try { + while (true) { + System.out.println("Tunnel: Waiting for client"); + Socket previous = clientConnection; + try { + clientConnection = ss.accept(); + } catch (IOException io) { + if (DEBUG) io.printStackTrace(System.out); + break; + } finally { + // close the previous connection + if (previous != null) previous.close(); + } + System.out.println("Tunnel: Client accepted"); + Socket targetConnection = null; + InputStream ccis = clientConnection.getInputStream(); + OutputStream ccos = clientConnection.getOutputStream(); + Writer w = new OutputStreamWriter( + clientConnection.getOutputStream(), "UTF-8"); + PrintWriter pw = new PrintWriter(w); + System.out.println("Tunnel: Reading request line"); + String requestLine = readLine(ccis); + System.out.println("Tunnel: Request line: " + requestLine); + if (requestLine.startsWith("CONNECT ")) { + // We should probably check that the next word following + // CONNECT is the host:port of our HTTPS serverImpl. + // Some improvement for a followup! + + // Read all headers until we find the empty line that + // signals the end of all headers. + while(!requestLine.equals("")) { + System.out.println("Tunnel: Reading header: " + + (requestLine = readLine(ccis))); + } + + targetConnection = new Socket( + serverImpl.getAddress().getAddress(), + serverImpl.getAddress().getPort()); + + // Then send the 200 OK response to the client + System.out.println("Tunnel: Sending " + + "HTTP/1.1 200 OK\r\n\r\n"); + pw.print("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + pw.flush(); + } else { + // This should not happen. If it does let our serverImpl + // deal with it. + throw new IOException("Tunnel: Unexpected status line: " + + requestLine); + } + + // Pipe the input stream of the client connection to the + // output stream of the target connection and conversely. + // Now the client and target will just talk to each other. + System.out.println("Tunnel: Starting tunnel pipes"); + Thread t1 = pipe(ccis, targetConnection.getOutputStream(), '+'); + Thread t2 = pipe(targetConnection.getInputStream(), ccos, '-'); + t1.start(); + t2.start(); + + // We have only 1 client... wait until it has finished before + // accepting a new connection request. + t1.join(); + t2.join(); + } + } catch (Throwable ex) { + try { + ss.close(); + } catch (IOException ex1) { + ex.addSuppressed(ex1); + } + ex.printStackTrace(System.err); + } + } + + } +} diff --git a/jdk/test/java/net/HttpURLConnection/getResponseCode.java b/jdk/test/java/net/HttpURLConnection/getResponseCode.java index eb6a64dc0c6..4eca0d5ea1a 100644 --- a/jdk/test/java/net/HttpURLConnection/getResponseCode.java +++ b/jdk/test/java/net/HttpURLConnection/getResponseCode.java @@ -24,6 +24,8 @@ /* * @test * @bug 4666195 + * @build getResponseCode + * @run main getResponseCode * @summary REGRESSION: HttpURLConnection.getResponseCode() returns always -1 */ import java.net.*; diff --git a/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/LeaseCheckInterval.java b/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/LeaseCheckInterval.java index 889a55e9879..3b61bb1f60e 100644 --- a/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/LeaseCheckInterval.java +++ b/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/LeaseCheckInterval.java @@ -43,7 +43,6 @@ * java.rmi/sun.rmi.transport.tcp * @build TestLibrary JavaVM LeaseCheckInterval_Stub SelfTerminator * @run main/othervm LeaseCheckInterval - * @key intermittent */ import java.rmi.Remote; @@ -88,9 +87,8 @@ public class LeaseCheckInterval implements Remote, Unreferenced { UnicastRemoteObject.exportObject(obj); System.err.println("exported remote object"); - int registryPort = TestLibrary.getUnusedRandomPort(); - Registry localRegistry = - LocateRegistry.createRegistry(registryPort); + Registry localRegistry = TestLibrary.createRegistryOnEphemeralPort(); + int registryPort = TestLibrary.getRegistryPort(localRegistry); System.err.println("created local registry"); localRegistry.bind(BINDING, obj); diff --git a/jdk/test/java/rmi/server/useCustomRef/UseCustomRef.java b/jdk/test/java/rmi/server/useCustomRef/UseCustomRef.java index bbb271c8b6b..a62cfadc1b9 100644 --- a/jdk/test/java/rmi/server/useCustomRef/UseCustomRef.java +++ b/jdk/test/java/rmi/server/useCustomRef/UseCustomRef.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -86,7 +86,7 @@ public class UseCustomRef System.err.println("creating Registry..."); - registry = TestLibrary.createRegistryOnUnusedPort(); + registry = TestLibrary.createRegistryOnEphemeralPort(); int port = TestLibrary.getRegistryPort(registry); /* * create object with custom ref and bind in registry diff --git a/jdk/test/java/util/Spliterator/SpliteratorFailFastTest.java b/jdk/test/java/util/Spliterator/SpliteratorFailFastTest.java new file mode 100644 index 00000000000..a0e71d24921 --- /dev/null +++ b/jdk/test/java/util/Spliterator/SpliteratorFailFastTest.java @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.ConcurrentModificationException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.PriorityQueue; +import java.util.Spliterator; +import java.util.Stack; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.Vector; +import java.util.WeakHashMap; +import java.util.function.Supplier; + +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +/** + * @test + * @bug 8148748 + * @summary Spliterator fail-fast tests + * @run testng SpliteratorFailFastTest + */ + +@Test +public class SpliteratorFailFastTest extends SpliteratorLateBindingFailFastHelper { + + static Object[][] spliteratorDataProvider; + + @DataProvider(name = "Source") + public static Object[][] spliteratorDataProvider() { + if (spliteratorDataProvider != null) { + return spliteratorDataProvider; + } + + List data = new ArrayList<>(); + SpliteratorDataBuilder db = + new SpliteratorDataBuilder<>(data, 5, Arrays.asList(1, 2, 3, 4)); + + // Collections + + db.addList(ArrayList::new); + + db.addList(LinkedList::new); + + db.addList(Vector::new); + + db.addList(AbstractRandomAccessListImpl::new); + + db.addCollection(HashSet::new); + + db.addCollection(LinkedHashSet::new); + + db.addCollection(TreeSet::new); + + db.addCollection(c -> { + Stack s = new Stack<>(); + s.addAll(c); + return s; + }); + + db.addCollection(PriorityQueue::new); + + // ArrayDeque fails some tests since its fail-fast support is weaker + // than other collections and limited to detecting most, but not all, + // removals. It probably requires its own test since it is difficult + // to abstract out the conditions under which it fails-fast. +// db.addCollection(ArrayDeque::new); + + // Maps + + db.addMap(HashMap::new); + + db.addMap(LinkedHashMap::new); + + // This fails when run through jtreg but passes when run through + // ant +// db.addMap(IdentityHashMap::new); + + db.addMap(WeakHashMap::new); + + // @@@ Descending maps etc + db.addMap(TreeMap::new); + + return spliteratorDataProvider = data.toArray(new Object[0][]); + } + + @Test(dataProvider = "Source") + public void testTryAdvance(String description, Supplier> ss) { + { + Source source = ss.get(); + Spliterator s = source.spliterator(); + + s.tryAdvance(e -> { + }); + source.update(); + + executeAndCatch(() -> s.tryAdvance(e -> { + })); + } + + { + Source source = ss.get(); + Spliterator s = source.spliterator(); + + s.tryAdvance(e -> { + }); + source.update(); + + executeAndCatch(() -> s.forEachRemaining(e -> { + })); + } + } + + @Test(dataProvider = "Source") + public void testForEach(String description, Supplier> ss) { + Source source = ss.get(); + Spliterator s = source.spliterator(); + + executeAndCatch(() -> s.forEachRemaining(e -> { + source.update(); + })); + } + + @Test(dataProvider = "Source") + public void testEstimateSize(String description, Supplier> ss) { + { + Source source = ss.get(); + Spliterator s = source.spliterator(); + + s.estimateSize(); + source.update(); + + executeAndCatch(() -> s.tryAdvance(e -> { + })); + } + + { + Source source = ss.get(); + Spliterator s = source.spliterator(); + + s.estimateSize(); + source.update(); + + executeAndCatch(() -> s.forEachRemaining(e -> { + })); + } + } + + private void executeAndCatch(Runnable r) { + executeAndCatch(ConcurrentModificationException.class, r); + } + + private void executeAndCatch(Class expected, Runnable r) { + Exception caught = null; + try { + r.run(); + } + catch (Exception e) { + caught = e; + } + + assertNotNull(caught, + String.format("No Exception was thrown, expected an Exception of %s to be thrown", + expected.getName())); + assertTrue(expected.isInstance(caught), + String.format("Exception thrown %s not an instance of %s", + caught.getClass().getName(), expected.getName())); + } + +} diff --git a/jdk/test/java/util/Spliterator/SpliteratorLateBindingFailFastHelper.java b/jdk/test/java/util/Spliterator/SpliteratorLateBindingFailFastHelper.java new file mode 100644 index 00000000000..a3c53b77b64 --- /dev/null +++ b/jdk/test/java/util/Spliterator/SpliteratorLateBindingFailFastHelper.java @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2016 Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.RandomAccess; +import java.util.Spliterator; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +class SpliteratorLateBindingFailFastHelper { + + interface Source { + Spliterator spliterator(); + + void update(); + + default boolean bindOnCharacteristics() { + return false; + } + } + + static class IntSource implements Source { + final T b; + final Function toSpliterator; + final Consumer updater; + final boolean bindOnCharacteristics; + + public IntSource(T b, Function toSpliterator, + Consumer updater) { + this(b, toSpliterator, updater, false); + } + + public IntSource(T b, Function toSpliterator, + Consumer updater, boolean bindOnCharacteristics) { + this.b = b; + this.toSpliterator = toSpliterator; + this.updater = updater; + this.bindOnCharacteristics = bindOnCharacteristics; + } + + @Override + public Spliterator.OfInt spliterator() { + return toSpliterator.apply(b); + } + + @Override + public void update() { + updater.accept(b); + } + + @Override + public boolean bindOnCharacteristics() { + return bindOnCharacteristics; + } + } + + static class SpliteratorDataBuilder { + final List data; + + final T newValue; + + final List exp; + + final Map mExp; + + SpliteratorDataBuilder(List data, T newValue, List exp) { + this.data = data; + this.newValue = newValue; + this.exp = exp; + this.mExp = createMap(exp); + } + + Map createMap(List l) { + Map m = new LinkedHashMap<>(); + for (T t : l) { + m.put(t, t); + } + return m; + } + + void add(String description, Supplier> s) { + data.add(new Object[]{description, s}); + } + + void addCollection(Function, ? extends Collection> f) { + class CollectionSource implements Source { + final Collection c = f.apply(exp); + + final Consumer> updater; + + CollectionSource(Consumer> updater) { + this.updater = updater; + } + + @Override + public Spliterator spliterator() { + return c.spliterator(); + } + + @Override + public void update() { + updater.accept(c); + } + } + + String description = "new " + f.apply(Collections.emptyList()).getClass().getName() + ".spliterator() "; + add(description + "ADD", () -> new CollectionSource(c -> c.add(newValue))); + add(description + "REMOVE", () -> new CollectionSource(c -> c.remove(c.iterator().next()))); + } + + void addList(Function, ? extends List> l) { + addCollection(l); + addCollection(l.andThen(list -> list.subList(0, list.size()))); + } + + void addMap(Function, ? extends Map> mapConstructor) { + class MapSource implements Source { + final Map m = mapConstructor.apply(mExp); + + final Collection c; + + final Consumer> updater; + + MapSource(Function, Collection> f, Consumer> updater) { + this.c = f.apply(m); + this.updater = updater; + } + + @Override + public Spliterator spliterator() { + return c.spliterator(); + } + + @Override + public void update() { + updater.accept(m); + } + } + + Map>> actions = new HashMap<>(); + actions.put("ADD", m -> m.put(newValue, newValue)); + actions.put("REMOVE", m -> m.remove(m.keySet().iterator().next())); + + String description = "new " + mapConstructor.apply(Collections.emptyMap()).getClass().getName(); + for (Map.Entry>> e : actions.entrySet()) { + add(description + ".keySet().spliterator() " + e.getKey(), + () -> new MapSource<>(m -> m.keySet(), e.getValue())); + add(description + ".values().spliterator() " + e.getKey(), + () -> new MapSource<>(m -> m.values(), e.getValue())); + add(description + ".entrySet().spliterator() " + e.getKey(), + () -> new MapSource<>(m -> m.entrySet(), e.getValue())); + } + } + } + + static class AbstractRandomAccessListImpl extends AbstractList implements RandomAccess { + List l; + + AbstractRandomAccessListImpl(Collection c) { + this.l = new ArrayList<>(c); + } + + @Override + public boolean add(Integer integer) { + modCount++; + return l.add(integer); + } + + @Override + public Iterator iterator() { + return l.iterator(); + } + + @Override + public Integer get(int index) { + return l.get(index); + } + + @Override + public boolean remove(Object o) { + modCount++; + return l.remove(o); + } + + @Override + public int size() { + return l.size(); + } + + @Override + public List subList(int fromIndex, int toIndex) { + return l.subList(fromIndex, toIndex); + } + } +} diff --git a/jdk/test/java/util/Spliterator/SpliteratorLateBindingFailFastTest.java b/jdk/test/java/util/Spliterator/SpliteratorLateBindingFailFastTest.java deleted file mode 100644 index 0aecca604bd..00000000000 --- a/jdk/test/java/util/Spliterator/SpliteratorLateBindingFailFastTest.java +++ /dev/null @@ -1,401 +0,0 @@ -/* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import java.util.AbstractList; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.PriorityQueue; -import java.util.RandomAccess; -import java.util.Set; -import java.util.Spliterator; -import java.util.Stack; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.Vector; -import java.util.WeakHashMap; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - -import static org.testng.Assert.*; - -/** - * @test - * @bug 8148748 - * @summary Spliterator last-binding and fail-fast tests - * @run testng SpliteratorLateBindingFailFastTest - */ - -@Test -public class SpliteratorLateBindingFailFastTest { - - private interface Source { - Collection asCollection(); - void update(); - } - - private static class SpliteratorDataBuilder { - final List data; - - final T newValue; - - final List exp; - - final Map mExp; - - SpliteratorDataBuilder(List data, T newValue, List exp) { - this.data = data; - this.newValue = newValue; - this.exp = exp; - this.mExp = createMap(exp); - } - - Map createMap(List l) { - Map m = new LinkedHashMap<>(); - for (T t : l) { - m.put(t, t); - } - return m; - } - - void add(String description, Supplier> s) { - description = joiner(description).toString(); - data.add(new Object[]{description, s}); - } - - void addCollection(Function, ? extends Collection> f) { - class CollectionSource implements Source { - final Collection c = f.apply(exp); - - final Consumer> updater; - - CollectionSource(Consumer> updater) { - this.updater = updater; - } - - @Override - public Collection asCollection() { - return c; - } - - @Override - public void update() { - updater.accept(c); - } - } - - String description = "new " + f.apply(Collections.emptyList()).getClass().getName() + ".spliterator() "; - add(description + "ADD", () -> new CollectionSource(c -> c.add(newValue))); - add(description + "REMOVE", () -> new CollectionSource(c -> c.remove(c.iterator().next()))); - } - - void addList(Function, ? extends List> l) { - addCollection(l); - addCollection(l.andThen(list -> list.subList(0, list.size()))); - } - - void addMap(Function, ? extends Map> mapConstructor) { - class MapSource implements Source { - final Map m = mapConstructor.apply(mExp); - - final Collection c; - - final Consumer> updater; - - MapSource(Function, Collection> f, Consumer> updater) { - this.c = f.apply(m); - this.updater = updater; - } - - @Override - public Collection asCollection() { - return c; - } - - @Override - public void update() { - updater.accept(m); - } - } - - Map>> actions = new HashMap<>(); - actions.put("ADD", m -> m.put(newValue, newValue)); - actions.put("REMOVE", m -> m.remove(m.keySet().iterator().next())); - - String description = "new " + mapConstructor.apply(Collections.emptyMap()).getClass().getName(); - for (Map.Entry>> e : actions.entrySet()) { - add(description + ".keySet().spliterator() " + e.getKey(), - () -> new MapSource(m -> m.keySet(), e.getValue())); - add(description + ".values().spliterator() " + e.getKey(), - () -> new MapSource(m -> m.values(), e.getValue())); - add(description + ".entrySet().spliterator() " + e.getKey(), - () -> new MapSource>(m -> m.entrySet(), e.getValue())); - } - } - - StringBuilder joiner(String description) { - return new StringBuilder(description). - append(" {"). - append("size=").append(exp.size()). - append("}"); - } - } - - static Object[][] spliteratorDataProvider; - - @DataProvider(name = "Source") - public static Object[][] spliteratorDataProvider() { - if (spliteratorDataProvider != null) { - return spliteratorDataProvider; - } - - List data = new ArrayList<>(); - SpliteratorDataBuilder db = new SpliteratorDataBuilder<>(data, 5, Arrays.asList(1, 2, 3, 4)); - - // Collections - - db.addList(ArrayList::new); - - db.addList(LinkedList::new); - - db.addList(Vector::new); - - class AbstractRandomAccessListImpl extends AbstractList implements RandomAccess { - List l; - - AbstractRandomAccessListImpl(Collection c) { - this.l = new ArrayList<>(c); - } - - @Override - public boolean add(Integer integer) { - modCount++; - return l.add(integer); - } - - @Override - public Iterator iterator() { - return l.iterator(); - } - - @Override - public Integer get(int index) { - return l.get(index); - } - - @Override - public boolean remove(Object o) { - modCount++; - return l.remove(o); - } - - @Override - public int size() { - return l.size(); - } - - @Override - public List subList(int fromIndex, int toIndex) { - return l.subList(fromIndex, toIndex); - } - } - db.addList(AbstractRandomAccessListImpl::new); - - db.addCollection(HashSet::new); - - db.addCollection(LinkedHashSet::new); - - db.addCollection(TreeSet::new); - - - db.addCollection(c -> { Stack s = new Stack<>(); s.addAll(c); return s;}); - - db.addCollection(PriorityQueue::new); - - // ArrayDeque fails some tests since its fail-fast support is weaker - // than other collections and limited to detecting most, but not all, - // removals. It probably requires its own test since it is difficult - // to abstract out the conditions under which it fails-fast. -// db.addCollection(ArrayDeque::new); - - // Maps - - db.addMap(HashMap::new); - - db.addMap(LinkedHashMap::new); - - // This fails when run through jtreg but passes when run through - // ant -// db.addMap(IdentityHashMap::new); - - db.addMap(WeakHashMap::new); - - // @@@ Descending maps etc - db.addMap(TreeMap::new); - - return spliteratorDataProvider = data.toArray(new Object[0][]); - } - - @Test(dataProvider = "Source") - public void lateBindingTestWithForEach(String description, Supplier> ss) { - Source source = ss.get(); - Collection c = source.asCollection(); - Spliterator s = c.spliterator(); - - source.update(); - - Set r = new HashSet<>(); - s.forEachRemaining(r::add); - - assertEquals(r, new HashSet<>(c)); - } - - @Test(dataProvider = "Source") - public void lateBindingTestWithTryAdvance(String description, Supplier> ss) { - Source source = ss.get(); - Collection c = source.asCollection(); - Spliterator s = c.spliterator(); - - source.update(); - - Set r = new HashSet<>(); - while (s.tryAdvance(r::add)) { } - - assertEquals(r, new HashSet<>(c)); - } - - @Test(dataProvider = "Source") - public void lateBindingTestWithCharacteritics(String description, Supplier> ss) { - Source source = ss.get(); - Collection c = source.asCollection(); - Spliterator s = c.spliterator(); - s.characteristics(); - - Set r = new HashSet<>(); - s.forEachRemaining(r::add); - - assertEquals(r, new HashSet<>(c)); - } - - - @Test(dataProvider = "Source") - public void testFailFastTestWithTryAdvance(String description, Supplier> ss) { - { - Source source = ss.get(); - Collection c = source.asCollection(); - Spliterator s = c.spliterator(); - - s.tryAdvance(e -> { - }); - source.update(); - - executeAndCatch(() -> s.tryAdvance(e -> { })); - } - - { - Source source = ss.get(); - Collection c = source.asCollection(); - Spliterator s = c.spliterator(); - - s.tryAdvance(e -> { - }); - source.update(); - - executeAndCatch(() -> s.forEachRemaining(e -> { - })); - } - } - - @Test(dataProvider = "Source") - public void testFailFastTestWithForEach(String description, Supplier> ss) { - Source source = ss.get(); - Collection c = source.asCollection(); - Spliterator s = c.spliterator(); - - executeAndCatch(() -> s.forEachRemaining(e -> { - source.update(); - })); - } - - @Test(dataProvider = "Source") - public void testFailFastTestWithEstimateSize(String description, Supplier> ss) { - { - Source source = ss.get(); - Collection c = source.asCollection(); - Spliterator s = c.spliterator(); - - s.estimateSize(); - source.update(); - - executeAndCatch(() -> s.tryAdvance(e -> { })); - } - - { - Source source = ss.get(); - Collection c = source.asCollection(); - Spliterator s = c.spliterator(); - - s.estimateSize(); - source.update(); - - executeAndCatch(() -> s.forEachRemaining(e -> { - })); - } - } - - private void executeAndCatch(Runnable r) { - executeAndCatch(ConcurrentModificationException.class, r); - } - - private void executeAndCatch(Class expected, Runnable r) { - Exception caught = null; - try { - r.run(); - } - catch (Exception e) { - caught = e; - } - - assertNotNull(caught, - String.format("No Exception was thrown, expected an Exception of %s to be thrown", - expected.getName())); - assertTrue(expected.isInstance(caught), - String.format("Exception thrown %s not an instance of %s", - caught.getClass().getName(), expected.getName())); - } - -} diff --git a/jdk/test/java/util/Spliterator/SpliteratorLateBindingTest.java b/jdk/test/java/util/Spliterator/SpliteratorLateBindingTest.java new file mode 100644 index 00000000000..42553cbe4e5 --- /dev/null +++ b/jdk/test/java/util/Spliterator/SpliteratorLateBindingTest.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.nio.CharBuffer; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.BitSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.PriorityQueue; +import java.util.Set; +import java.util.Spliterator; +import java.util.Stack; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.Vector; +import java.util.WeakHashMap; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import static org.testng.Assert.assertEquals; + +/** + * @test + * @bug 8148748 8170155 + * @summary Spliterator last-binding tests + * @run testng SpliteratorLateBindingTest + */ + +@Test +public class SpliteratorLateBindingTest extends SpliteratorLateBindingFailFastHelper { + + static Object[][] spliteratorDataProvider; + + @DataProvider(name = "Source") + public static Object[][] sourceDataProvider() { + if (spliteratorDataProvider != null) { + return spliteratorDataProvider; + } + + List data = new ArrayList<>(); + SpliteratorDataBuilder db = + new SpliteratorDataBuilder<>(data, 5, Arrays.asList(1, 2, 3, 4)); + + // Collections + + db.addList(ArrayList::new); + + db.addList(LinkedList::new); + + db.addList(Vector::new); + + db.addList(AbstractRandomAccessListImpl::new); + + db.addCollection(HashSet::new); + + db.addCollection(LinkedHashSet::new); + + db.addCollection(TreeSet::new); + + db.addCollection(c -> { + Stack s = new Stack<>(); + s.addAll(c); + return s; + }); + + db.addCollection(PriorityQueue::new); + + db.addCollection(ArrayDeque::new); + + // Maps + + db.addMap(HashMap::new); + + db.addMap(LinkedHashMap::new); + + db.addMap(IdentityHashMap::new); + + db.addMap(WeakHashMap::new); + + // @@@ Descending maps etc + db.addMap(TreeMap::new); + + // BitSet + + List bits = List.of(0, 1, 2); + Function bitsSource = bs -> bs.stream().spliterator(); + db.add("new BitSet.stream().spliterator() ADD", + () -> new IntSource<>(toBitSet(bits), bitsSource, bs -> bs.set(3))); + db.add("new BitSet.stream().spliterator() REMOVE", + () -> new IntSource<>(toBitSet(bits), bitsSource, bs -> bs.clear(2))); + + // CharSequence + + Function charsSource = sb -> sb.chars().spliterator(); + Function pointsSource = sb -> sb.codePoints().spliterator(); + + db.add("new StringBuilder.chars().spliterator() ADD", + () -> new IntSource<>(new StringBuilder("ABC"), charsSource, bs -> bs.append("D"), true)); + db.add("new StringBuilder.chars().spliterator() REMOVE", + () -> new IntSource<>(new StringBuilder("ABC"), charsSource, bs -> bs.deleteCharAt(2), true)); + db.add("new StringBuilder.codePoints().spliterator() ADD", + () -> new IntSource<>(new StringBuilder("ABC"), pointsSource, bs -> bs.append("D"), true)); + db.add("new StringBuilder.codePoints().spliterator() REMOVE", + () -> new IntSource<>(new StringBuilder("ABC"), pointsSource, bs -> bs.deleteCharAt(2), true)); + + db.add("new StringBuffer.chars().spliterator() ADD", + () -> new IntSource<>(new StringBuffer("ABC"), charsSource, bs -> bs.append("D"), true)); + db.add("new StringBuffer.chars().spliterator() REMOVE", + () -> new IntSource<>(new StringBuffer("ABC"), charsSource, bs -> bs.deleteCharAt(2), true)); + db.add("new StringBuffer.codePoints().spliterator() ADD", + () -> new IntSource<>(new StringBuffer("ABC"), pointsSource, bs -> bs.append("D"), true)); + db.add("new StringBuffer.codePoints().spliterator() REMOVE", + () -> new IntSource<>(new StringBuffer("ABC"), pointsSource, bs -> bs.deleteCharAt(2), true)); + + db.add("CharBuffer.wrap().chars().spliterator() ADD", + () -> new IntSource<>(CharBuffer.wrap("ABCD").limit(3), charsSource, bs -> bs.limit(4), true)); + db.add("CharBuffer.wrap().chars().spliterator() REMOVE", + () -> new IntSource<>(CharBuffer.wrap("ABCD"), charsSource, bs -> bs.limit(3), true)); + db.add("CharBuffer.wrap().codePoints().spliterator() ADD", + () -> new IntSource<>(CharBuffer.wrap("ABCD").limit(3), pointsSource, bs -> bs.limit(4), true)); + db.add("CharBuffer.wrap().codePoints().spliterator() REMOVE", + () -> new IntSource<>(CharBuffer.wrap("ABCD"), pointsSource, bs -> bs.limit(3), true)); + + return spliteratorDataProvider = data.toArray(new Object[0][]); + } + + + @DataProvider(name = "Source.Non.Binding.Characteristics") + public static Object[][] sourceCharacteristicsDataProvider() { + return Stream.of(sourceDataProvider()).filter(tc -> { + @SuppressWarnings("unchecked") + Supplier> s = (Supplier>) tc[1]; + return !s.get().bindOnCharacteristics(); + }).toArray(Object[][]::new); + } + + static BitSet toBitSet(List bits) { + BitSet bs = new BitSet(); + bits.forEach(bs::set); + return bs; + } + + + @Test(dataProvider = "Source") + public void testForEach(String description, Supplier> ss) { + Source source = ss.get(); + Spliterator s = source.spliterator(); + + source.update(); + + Set a = new HashSet<>(); + s.forEachRemaining(a::add); + + Set e = new HashSet<>(); + source.spliterator().forEachRemaining(e::add); + assertEquals(a, e); + } + + @Test(dataProvider = "Source") + public void testTryAdvance(String description, Supplier> ss) { + Source source = ss.get(); + Spliterator s = source.spliterator(); + + source.update(); + + Set a = new HashSet<>(); + while (s.tryAdvance(a::add)) { + } + + Set e = new HashSet<>(); + source.spliterator().forEachRemaining(e::add); + assertEquals(a, e); + } + + @Test(dataProvider = "Source.Non.Binding.Characteristics") + public void testCharacteristics(String description, Supplier> ss) { + Source source = ss.get(); + Spliterator s = source.spliterator(); + + s.characteristics(); + source.update(); + + Set a = new HashSet<>(); + s.forEachRemaining(a::add); + + Set e = new HashSet<>(); + source.spliterator().forEachRemaining(e::add); + assertEquals(a, e); + } +} diff --git a/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java b/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java index 474204384a8..a8338ca4e5f 100644 --- a/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java +++ b/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java @@ -31,6 +31,7 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import java.nio.CharBuffer; import java.util.AbstractCollection; import java.util.AbstractList; import java.util.AbstractSet; @@ -884,6 +885,7 @@ public class SpliteratorTraversingAndSplittingTest { cdb.add("new CharSequenceImpl(\"%s\")", CharSequenceImpl::new); cdb.add("new StringBuilder(\"%s\")", StringBuilder::new); cdb.add("new StringBuffer(\"%s\")", StringBuffer::new); + cdb.add("CharBuffer.wrap(\"%s\".toCharArray())", s -> CharBuffer.wrap(s.toCharArray())); } diff --git a/jdk/test/sun/security/ssl/X509TrustManagerImpl/PKIXExtendedTM.java b/jdk/test/sun/security/ssl/X509TrustManagerImpl/PKIXExtendedTM.java index 8a5db1064e0..1cf22f04293 100644 --- a/jdk/test/sun/security/ssl/X509TrustManagerImpl/PKIXExtendedTM.java +++ b/jdk/test/sun/security/ssl/X509TrustManagerImpl/PKIXExtendedTM.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,9 +28,12 @@ /* * @test - * @bug 6916074 + * @bug 6916074 8170131 * @summary Add support for TLS 1.2 - * @run main/othervm PKIXExtendedTM + * @run main/othervm PKIXExtendedTM 0 + * @run main/othervm PKIXExtendedTM 1 + * @run main/othervm PKIXExtendedTM 2 + * @run main/othervm PKIXExtendedTM 3 */ import java.net.*; @@ -42,6 +45,7 @@ import java.security.KeyStore; import java.security.KeyFactory; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; +import java.security.cert.CertPathValidatorException; import java.security.spec.*; import java.security.interfaces.*; import java.math.BigInteger; @@ -792,20 +796,85 @@ public class PKIXExtendedTM { volatile Exception serverException = null; volatile Exception clientException = null; - public static void main(String args[]) throws Exception { - // MD5 is used in this test case, don't disable MD5 algorithm. - Security.setProperty("jdk.certpath.disabledAlgorithms", - "MD2, RSA keySize < 1024"); - Security.setProperty("jdk.tls.disabledAlgorithms", - "SSLv3, RC4, DH keySize < 768"); + static class Test { + String tlsDisAlgs; + String certPathDisAlgs; + boolean fail; + Test(String tlsDisAlgs, String certPathDisAlgs, boolean fail) { + this.tlsDisAlgs = tlsDisAlgs; + this.certPathDisAlgs = certPathDisAlgs; + this.fail = fail; + } + } - if (debug) + static Test[] tests = { + // MD5 is used in this test case, don't disable MD5 algorithm. + new Test( + "SSLv3, RC4, DH keySize < 768", + "MD2, RSA keySize < 1024", + false), + // Disable MD5 but only if cert chains back to public root CA, should + // pass because the MD5 cert in this test case is issued by test CA + new Test( + "SSLv3, RC4, DH keySize < 768", + "MD2, MD5 jdkCA, RSA keySize < 1024", + false), + // Disable MD5 alg via TLS property and expect failure + new Test( + "SSLv3, MD5, RC4, DH keySize < 768", + "MD2, RSA keySize < 1024", + true), + // Disable MD5 alg via certpath property and expect failure + new Test( + "SSLv3, RC4, DH keySize < 768", + "MD2, MD5, RSA keySize < 1024", + true), + }; + + public static void main(String args[]) throws Exception { + if (args.length != 1) { + throw new Exception("Incorrect number of arguments"); + } + Test test = tests[Integer.parseInt(args[0])]; + Security.setProperty("jdk.tls.disabledAlgorithms", test.tlsDisAlgs); + Security.setProperty("jdk.certpath.disabledAlgorithms", + test.certPathDisAlgs); + + if (debug) { System.setProperty("javax.net.debug", "all"); + } /* * Start the tests. */ - new PKIXExtendedTM(); + try { + new PKIXExtendedTM(); + if (test.fail) { + throw new Exception("Expected MD5 certificate to be blocked"); + } + } catch (Exception e) { + if (test.fail) { + // find expected cause + boolean correctReason = false; + Throwable cause = e.getCause(); + while (cause != null) { + if (cause instanceof CertPathValidatorException) { + CertPathValidatorException cpve = + (CertPathValidatorException)cause; + if (cpve.getReason() == CertPathValidatorException.BasicReason.ALGORITHM_CONSTRAINED) { + correctReason = true; + break; + } + } + cause = cause.getCause(); + } + if (!correctReason) { + throw new Exception("Unexpected exception", e); + } + } else { + throw e; + } + } } Thread clientThread = null; diff --git a/jdk/test/tools/jar/modularJar/Basic.java b/jdk/test/tools/jar/modularJar/Basic.java index 45ef7897b43..df38b6cc584 100644 --- a/jdk/test/tools/jar/modularJar/Basic.java +++ b/jdk/test/tools/jar/modularJar/Basic.java @@ -46,6 +46,7 @@ import static java.lang.System.out; /* * @test + * @bug 8167328 * @library /lib/testlibrary * @modules jdk.compiler * jdk.jartool @@ -756,6 +757,14 @@ public class Basic { "Expected to find ", FOO.moduleName + "@" + FOO.version, " in [", r.output, "]") ); + + jar(option, + "--file=" + modularJar.toString(), + modularJar.toString()) + .assertFailure(); + + jar(option, modularJar.toString()) + .assertFailure(); } }