This commit is contained in:
J. Duke 2017-07-05 21:10:38 +02:00
commit 836693b338
256 changed files with 15092 additions and 1648 deletions

View File

@ -341,3 +341,4 @@ cf1dc4c035fb84693d4ae5ad818785cb4d1465d1 jdk9-b90
5582a79892596169ebddb3e2c2aa44939e4e3f40 jdk-9+96
75c3897541ecb52ee16d001ea605b12971df7303 jdk-9+97
48987460c7d49a29013963ee44d090194396bb61 jdk-9+98
7c0577bea4c65d69c5bef67023a89d2efa4fb2f7 jdk-9+99

View File

@ -32,7 +32,7 @@ installed_jib_script=${mydir}/../../.jib/jib
install_data=${mydir}/../../.jib/.data
setup_url() {
if [ -f "~/.config/jib/jib.conf" ]; then
if [ -f ~/.config/jib/jib.conf ]; then
source ~/.config/jib/jib.conf
fi
@ -50,6 +50,9 @@ setup_url() {
if [ -n "${JIB_SERVER}" ]; then
jib_server="${JIB_SERVER}"
fi
if [ -n "${JIB_SERVER_MIRRORS}" ]; then
jib_server_mirrors="${JIB_SERVER_MIRRORS}"
fi
if [ -n "${JIB_REPOSITORY}" ]; then
jib_repository="${JIB_REPOSITORY}"
fi
@ -70,8 +73,9 @@ setup_url() {
jib_url="${JIB_URL}"
data_string="${jib_url}"
else
data_string="${jib_repository}/${jib_organization}/${jib_module}/${jib_revision}/${jib_module}-${jib_revision}.${jib_ext}"
jib_url="${jib_server}/${data_string}"
jib_path="${jib_repository}/${jib_organization}/${jib_module}/${jib_revision}/${jib_module}-${jib_revision}.${jib_ext}"
data_string="${jib_path}"
jib_url="${jib_server}/${jib_path}"
fi
}
@ -104,7 +108,25 @@ install_jib() {
${getcmd} ${jib_url} > "${installed_jib_script}.gz"
if [ ! -s "${installed_jib_script}.gz" ]; then
echo "Failed to download ${jib_url}"
exit 1
if [ -n "${jib_path}" -a -n "${jib_server_mirrors}" ]; then
OLD_IFS="${IFS}"
IFS=" ,"
for mirror in ${jib_server_mirrors}; do
echo "Trying mirror ${mirror}"
jib_url="${mirror}/${jib_path}"
${getcmd} ${jib_url} > "${installed_jib_script}.gz"
if [ -s "${installed_jib_script}.gz" ]; then
echo "Download from mirror successful"
break
else
echo "Failed to download ${jib_url}"
fi
done
IFS="${OLD_IFS}"
fi
if [ ! -s "${installed_jib_script}.gz" ]; then
exit 1
fi
fi
echo "Extracting JIB bootstrap script"
rm -f "${installed_jib_script}"

View File

@ -341,3 +341,4 @@ fd038e8a16eec80d0d6b337d74a582790ed4b3ee jdk-9+95
feb1bd85d7990dcf5584ca9e53104269c01db006 jdk-9+96
10a482b863582376d4ca229090334b23b05159fc jdk-9+97
ea285530245cf4e0edf0479121a41347d3030eba jdk-9+98
180212ee1d8710691ba9944593dfc1ff3e4f1532 jdk-9+99

View File

@ -501,3 +501,4 @@ a22b7c80529f5f05c847e932e017456e83c46233 jdk9-b94
a94bb7203596dd632486f1e3655fa5f70541dc08 jdk-9+96
de592ea5f7ba0f8a8c5afc03bd169f7690c72b6f jdk-9+97
e5b1a23be1e105417ba1c4c576ab373eb3fa2c2b jdk-9+98
f008e8cc10d5b3212fb22d58c96fa01d38654f19 jdk-9+99

View File

@ -341,3 +341,4 @@ b433e4dfb830fea60e5187e4580791b62cc362d2 jdk9-b90
c021b855f51e572e63982654b17742cb1f814fb4 jdk-9+96
fdd84b2265ddce7f50e084b7c8635189bba6f012 jdk-9+97
f86ee68d1107dad41a27efc34306e0e56244a12e jdk-9+98
e1a789be1535741274c9779f4d4ca3495196b5c3 jdk-9+99

View File

@ -73,8 +73,9 @@ ifeq ($(OPENJDK_TARGET_OS), windows)
$$(eval $$(call SetupNativeCompilation, BUILD_JACCESSINSPECTOR$1, \
SRC := $(TOPDIR)/jaccessinspector $(TOPDIR)/common \
$(TOPDIR)/toolscommon $(TOPDIR)/include/bridge, \
CFLAGS := $$(CFLAGS_JDKEXE) $(TOOLS_CFLAGS) -DACCESSBRIDGE_ARCH_$2 /EHsc, \
LDFLAGS := $$(LDFLAGS_JDKEXE) /STACK:655360 Advapi32.lib User32.lib, \
CFLAGS := $$(CFLAGS_JDKEXE) $(TOOLS_CFLAGS) -DACCESSBRIDGE_ARCH_$2 -EHsc, \
LDFLAGS := $$(LDFLAGS_JDKEXE) -stack:655360, \
LIBS := advapi32.lib user32.lib, \
OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/native/jdk.accessibility/jaccessinspector$1, \
OUTPUT_DIR := $(SUPPORT_OUTPUTDIR)/modules_cmds/jdk.accessibility, \
PROGRAM := jaccessinspector$1, \
@ -100,8 +101,9 @@ ifeq ($(OPENJDK_TARGET_OS), windows)
$$(eval $$(call SetupNativeCompilation,BUILD_JACCESSWALKER$1, \
SRC := $(TOPDIR)/jaccesswalker $(TOPDIR)/common \
$(TOPDIR)/toolscommon $(TOPDIR)/include/bridge, \
CFLAGS :== $$(CFLAGS_JDKEXE) $(TOOLS_CFLAGS) -DACCESSBRIDGE_ARCH_$2 /EHsc, \
LDFLAGS := $$(LDFLAGS_JDKEXE) /STACK:655360 Advapi32.lib Comctl32.lib Gdi32.lib User32.lib, \
CFLAGS := $$(CFLAGS_JDKEXE) $(TOOLS_CFLAGS) -DACCESSBRIDGE_ARCH_$2 -EHsc, \
LDFLAGS := $$(LDFLAGS_JDKEXE) -stack:655360, \
LIBS := advapi32.lib comctl32.lib gdi32.lib user32.lib, \
OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/native/jdk.accessibility/jaccesswalker$1, \
OUTPUT_DIR := $(SUPPORT_OUTPUTDIR)/modules_cmds/jdk.accessibility, \
PROGRAM := jaccesswalker$1, \

View File

@ -29,7 +29,6 @@ import java.io.IOException;
import java.nio.channels.*;
import java.nio.channels.spi.*;
import java.util.*;
import sun.misc.*;
/**
* An implementation of Selector for Linux 2.6+ kernels that uses
@ -50,7 +49,7 @@ class EPollSelectorImpl
private Map<Integer,SelectionKeyImpl> fdToKey;
// True if this Selector has been closed
private volatile boolean closed = false;
private volatile boolean closed;
// Lock for interrupt triggering and clearing
private final Object interruptLock = new Object();

View File

@ -322,19 +322,6 @@ class LinuxWatchService
bytesRead = 0;
}
// process any pending requests
if ((nReady > 1) || (nReady == 1 && bytesRead == 0)) {
try {
read(socketpair[0], address, BUFFER_SIZE);
boolean shutdown = processRequests();
if (shutdown)
break;
} catch (UnixException x) {
if (x.errno() != UnixConstants.EAGAIN)
throw x;
}
}
// iterate over buffer to decode events
int offset = 0;
while (offset < bytesRead) {
@ -369,6 +356,19 @@ class LinuxWatchService
offset += (SIZEOF_INOTIFY_EVENT + len);
}
// process any pending requests
if ((nReady > 1) || (nReady == 1 && bytesRead == 0)) {
try {
read(socketpair[0], address, BUFFER_SIZE);
boolean shutdown = processRequests();
if (shutdown)
break;
} catch (UnixException x) {
if (x.errno() != UnixConstants.EAGAIN)
throw x;
}
}
}
} catch (UnixException x) {
x.printStackTrace();

View File

@ -93,7 +93,7 @@ public final class SunJCE extends Provider {
// Instance of this provider, so we don't have to call the provider list
// to find ourselves or run the risk of not being in the list.
private static volatile SunJCE instance = null;
private static volatile SunJCE instance;
// lazy initialize SecureRandom to avoid potential recursion if Sun
// provider has not been installed yet

View File

@ -420,11 +420,11 @@ public class File
String scheme = uri.getScheme();
if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
throw new IllegalArgumentException("URI scheme is not \"file\"");
if (uri.getAuthority() != null)
if (uri.getRawAuthority() != null)
throw new IllegalArgumentException("URI has an authority component");
if (uri.getFragment() != null)
if (uri.getRawFragment() != null)
throw new IllegalArgumentException("URI has a fragment component");
if (uri.getQuery() != null)
if (uri.getRawQuery() != null)
throw new IllegalArgumentException("URI has a query component");
String p = uri.getPath();
if (p.equals(""))

View File

@ -48,9 +48,9 @@ package java.io;
* @since 1.0
*/
public class PipedInputStream extends InputStream {
boolean closedByWriter = false;
volatile boolean closedByReader = false;
boolean connected = false;
boolean closedByWriter;
volatile boolean closedByReader;
boolean connected;
/* REMIND: identification of the read and write sides needs to be
more sophisticated. Either using thread groups (but what about

View File

@ -25,7 +25,7 @@
package java.lang;
import sun.misc.FloatingDecimal;
import jdk.internal.math.FloatingDecimal;
import java.util.Arrays;
import java.util.Spliterator;
import java.util.stream.IntStream;

View File

@ -2518,7 +2518,7 @@ public final class Class<T> implements java.io.Serializable,
// Incremented by the VM on each call to JVM TI RedefineClasses()
// that redefines this class or a superclass.
private transient volatile int classRedefinedCount = 0;
private transient volatile int classRedefinedCount;
// Lazily create and cache ReflectionData
private ReflectionData<T> reflectionData() {
@ -3331,7 +3331,8 @@ public final class Class<T> implements java.io.Serializable,
* uncloned, cached, and shared by all callers.
*/
T[] getEnumConstantsShared() {
if (enumConstants == null) {
T[] constants = enumConstants;
if (constants == null) {
if (!isEnum()) return null;
try {
final Method values = getMethod("values");
@ -3344,16 +3345,16 @@ public final class Class<T> implements java.io.Serializable,
});
@SuppressWarnings("unchecked")
T[] temporaryConstants = (T[])values.invoke(null);
enumConstants = temporaryConstants;
enumConstants = constants = temporaryConstants;
}
// These can happen when users concoct enum-like classes
// that don't comply with the enum spec.
catch (InvocationTargetException | NoSuchMethodException |
IllegalAccessException ex) { return null; }
}
return enumConstants;
return constants;
}
private transient volatile T[] enumConstants = null;
private transient volatile T[] enumConstants;
/**
* Returns a map from simple name to enum constant. This package-private
@ -3363,19 +3364,21 @@ public final class Class<T> implements java.io.Serializable,
* created lazily on first use. Typically it won't ever get created.
*/
Map<String, T> enumConstantDirectory() {
if (enumConstantDirectory == null) {
Map<String, T> directory = enumConstantDirectory;
if (directory == null) {
T[] universe = getEnumConstantsShared();
if (universe == null)
throw new IllegalArgumentException(
getName() + " is not an enum type");
Map<String, T> m = new HashMap<>(2 * universe.length);
for (T constant : universe)
m.put(((Enum<?>)constant).name(), constant);
enumConstantDirectory = m;
directory = new HashMap<>(2 * universe.length);
for (T constant : universe) {
directory.put(((Enum<?>)constant).name(), constant);
}
enumConstantDirectory = directory;
}
return enumConstantDirectory;
return directory;
}
private transient volatile Map<String, T> enumConstantDirectory = null;
private transient volatile Map<String, T> enumConstantDirectory;
/**
* Casts an object to the class or interface represented

View File

@ -45,11 +45,11 @@ import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Vector;
import java.util.Hashtable;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import sun.misc.CompoundEnumeration;
import sun.misc.Resource;
import sun.misc.URLClassPath;
import sun.reflect.CallerSensitive;
@ -2206,3 +2206,36 @@ class SystemClassLoaderAction
return sys;
}
}
/*
* A utility class that will enumerate over an array of enumerations.
*/
final class CompoundEnumeration<E> implements Enumeration<E> {
private final Enumeration<E>[] enums;
private int index;
public CompoundEnumeration(Enumeration<E>[] enums) {
this.enums = enums;
}
private boolean next() {
while (index < enums.length) {
if (enums[index] != null && enums[index].hasMoreElements()) {
return true;
}
index++;
}
return false;
}
public boolean hasMoreElements() {
return next();
}
public E nextElement() {
if (!next()) {
throw new NoSuchElementException();
}
return enums[index].nextElement();
}
}

View File

@ -25,8 +25,8 @@
package java.lang;
import sun.misc.FloatingDecimal;
import sun.misc.DoubleConsts;
import jdk.internal.math.FloatingDecimal;
import jdk.internal.math.DoubleConsts;
import jdk.internal.HotSpotIntrinsicCandidate;
/**

View File

@ -25,9 +25,9 @@
package java.lang;
import sun.misc.FloatingDecimal;
import sun.misc.FloatConsts;
import sun.misc.DoubleConsts;
import jdk.internal.math.FloatingDecimal;
import jdk.internal.math.FloatConsts;
import jdk.internal.math.DoubleConsts;
import jdk.internal.HotSpotIntrinsicCandidate;
/**

View File

@ -26,8 +26,8 @@
package java.lang;
import java.util.Random;
import sun.misc.FloatConsts;
import sun.misc.DoubleConsts;
import jdk.internal.math.FloatConsts;
import jdk.internal.math.DoubleConsts;
import jdk.internal.HotSpotIntrinsicCandidate;
/**

View File

@ -26,7 +26,7 @@
package java.lang;
import java.util.Random;
import sun.misc.DoubleConsts;
import jdk.internal.math.DoubleConsts;
import jdk.internal.HotSpotIntrinsicCandidate;
/**

View File

@ -132,7 +132,7 @@ public final class System {
/* The security manager for the system.
*/
private static volatile SecurityManager security = null;
private static volatile SecurityManager security;
/**
* Reassigns the "standard" input stream.
@ -206,7 +206,7 @@ public final class System {
setErr0(err);
}
private static volatile Console cons = null;
private static volatile Console cons;
/**
* Returns the unique {@link java.io.Console Console} object associated
* with the current Java virtual machine, if any.
@ -216,12 +216,13 @@ public final class System {
* @since 1.6
*/
public static Console console() {
if (cons == null) {
Console c = cons;
if (c == null) {
synchronized (System.class) {
cons = SharedSecrets.getJavaIOAccess().console();
cons = c = SharedSecrets.getJavaIOAccess().console();
}
}
return cons;
return c;
}
/**

View File

@ -207,12 +207,10 @@ class Thread implements Runnable {
/* For generating thread ID */
private static long threadSeqNumber;
/* Java thread status for tools,
* initialized to indicate thread 'not yet started'
/*
* Java thread status for tools, default indicates thread 'not yet started'
*/
private volatile int threadStatus = 0;
private volatile int threadStatus;
private static synchronized long nextThreadID() {
return ++threadSeqNumber;

View File

@ -53,7 +53,7 @@ public class ReferenceQueue<T> {
private static class Lock { };
private Lock lock = new Lock();
private volatile Reference<? extends T> head = null;
private volatile Reference<? extends T> head;
private long queueLength = 0;
boolean enqueue(Reference<? extends T> r) { /* Called only by Reference class */

View File

@ -205,7 +205,7 @@ public final class Parameter implements AnnotatedElement {
return tmp;
}
private transient volatile Type parameterTypeCache = null;
private transient volatile Type parameterTypeCache;
/**
* Returns a {@code Class} object that identifies the
@ -237,7 +237,7 @@ public final class Parameter implements AnnotatedElement {
return executable.getAnnotatedParameterTypes()[index];
}
private transient volatile Class<?> parameterClassCache = null;
private transient volatile Class<?> parameterClassCache;
/**
* Returns {@code true} if this parameter is implicitly declared

View File

@ -38,8 +38,8 @@ import java.util.Objects;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import sun.misc.DoubleConsts;
import sun.misc.FloatConsts;
import jdk.internal.math.DoubleConsts;
import jdk.internal.math.FloatConsts;
import jdk.internal.HotSpotIntrinsicCandidate;
/**

View File

@ -33,7 +33,6 @@ import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.CharacterCodingException;
@ -490,17 +489,17 @@ public final class URI
private transient String path; // null ==> opaque
private transient String query;
// The remaining fields may be computed on demand
// The remaining fields may be computed on demand, which is safe even in
// the face of multiple threads racing to initialize them
private transient String schemeSpecificPart;
private transient int hash; // Zero ==> undefined
private transient volatile String schemeSpecificPart;
private transient volatile int hash; // Zero ==> undefined
private transient volatile String decodedUserInfo = null;
private transient volatile String decodedAuthority = null;
private transient volatile String decodedPath = null;
private transient volatile String decodedQuery = null;
private transient volatile String decodedFragment = null;
private transient volatile String decodedSchemeSpecificPart = null;
private transient String decodedUserInfo;
private transient String decodedAuthority;
private transient String decodedPath;
private transient String decodedQuery;
private transient String decodedFragment;
private transient String decodedSchemeSpecificPart;
/**
* The string form of this URI.
@ -911,8 +910,7 @@ public final class URI
// either more fields or a more-obscure representation.
if ((host != null) || (authority == null))
return this;
defineString();
new Parser(string).parse(true);
new Parser(toString()).parse(true);
return this;
}
@ -1144,8 +1142,17 @@ public final class URI
* (never {@code null})
*/
public String getRawSchemeSpecificPart() {
defineSchemeSpecificPart();
return schemeSpecificPart;
String part = schemeSpecificPart;
if (part != null) {
return part;
}
StringBuilder sb = new StringBuilder();
appendSchemeSpecificPart(sb, null, getAuthority(), getUserInfo(),
host, port, getPath(), getQuery());
if (sb.length() == 0) {
return null;
}
return schemeSpecificPart = sb.toString();
}
/**
@ -1160,9 +1167,11 @@ public final class URI
* (never {@code null})
*/
public String getSchemeSpecificPart() {
if (decodedSchemeSpecificPart == null)
decodedSchemeSpecificPart = decode(getRawSchemeSpecificPart());
return decodedSchemeSpecificPart;
String part = decodedSchemeSpecificPart;
if (part == null) {
decodedSchemeSpecificPart = part = decode(getRawSchemeSpecificPart());
}
return part;
}
/**
@ -1193,9 +1202,11 @@ public final class URI
* or {@code null} if the authority is undefined
*/
public String getAuthority() {
if (decodedAuthority == null)
decodedAuthority = decode(authority);
return decodedAuthority;
String auth = decodedAuthority;
if ((auth == null) && (authority != null)) {
decodedAuthority = auth = decode(authority);
}
return auth;
}
/**
@ -1223,9 +1234,11 @@ public final class URI
* or {@code null} if the user information is undefined
*/
public String getUserInfo() {
if ((decodedUserInfo == null) && (userInfo != null))
decodedUserInfo = decode(userInfo);
return decodedUserInfo;
String user = decodedUserInfo;
if ((user == null) && (userInfo != null)) {
decodedUserInfo = user = decode(userInfo);
}
return user;
}
/**
@ -1307,9 +1320,11 @@ public final class URI
* or {@code null} if the path is undefined
*/
public String getPath() {
if ((decodedPath == null) && (path != null))
decodedPath = decode(path);
return decodedPath;
String decoded = decodedPath;
if ((decoded == null) && (path != null)) {
decodedPath = decoded = decode(path);
}
return decoded;
}
/**
@ -1336,9 +1351,11 @@ public final class URI
* or {@code null} if the query is undefined
*/
public String getQuery() {
if ((decodedQuery == null) && (query != null))
decodedQuery = decode(query, false);
return decodedQuery;
String decoded = decodedQuery;
if ((decoded == null) && (query != null)) {
decodedQuery = decoded = decode(query, false);
}
return decoded;
}
/**
@ -1365,9 +1382,11 @@ public final class URI
* or {@code null} if the fragment is undefined
*/
public String getFragment() {
if ((decodedFragment == null) && (fragment != null))
decodedFragment = decode(fragment, false);
return decodedFragment;
String decoded = decodedFragment;
if ((decoded == null) && (fragment != null)) {
decodedFragment = decoded = decode(fragment, false);
}
return decoded;
}
@ -1453,24 +1472,27 @@ public final class URI
* @return A hash-code value for this URI
*/
public int hashCode() {
if (hash != 0)
return hash;
int h = hashIgnoringCase(0, scheme);
h = hash(h, fragment);
if (isOpaque()) {
h = hash(h, schemeSpecificPart);
} else {
h = hash(h, path);
h = hash(h, query);
if (host != null) {
h = hash(h, userInfo);
h = hashIgnoringCase(h, host);
h += 1949 * port;
int h = hash;
if (h == 0) {
h = hashIgnoringCase(0, scheme);
h = hash(h, fragment);
if (isOpaque()) {
h = hash(h, schemeSpecificPart);
} else {
h = hash(h, authority);
h = hash(h, path);
h = hash(h, query);
if (host != null) {
h = hash(h, userInfo);
h = hashIgnoringCase(h, host);
h += 1949 * port;
} else {
h = hash(h, authority);
}
}
if (h != 0) {
hash = h;
}
}
hash = h;
return h;
}
@ -1600,8 +1622,59 @@ public final class URI
* @return The string form of this URI
*/
public String toString() {
defineString();
return string;
String s = string;
if (s == null) {
s = defineString();
}
return s;
}
private String defineString() {
String s = string;
if (s != null) {
return s;
}
StringBuilder sb = new StringBuilder();
if (scheme != null) {
sb.append(scheme);
sb.append(':');
}
if (isOpaque()) {
sb.append(schemeSpecificPart);
} else {
if (host != null) {
sb.append("//");
if (userInfo != null) {
sb.append(userInfo);
sb.append('@');
}
boolean needBrackets = ((host.indexOf(':') >= 0)
&& !host.startsWith("[")
&& !host.endsWith("]"));
if (needBrackets) sb.append('[');
sb.append(host);
if (needBrackets) sb.append(']');
if (port != -1) {
sb.append(':');
sb.append(port);
}
} else if (authority != null) {
sb.append("//");
sb.append(authority);
}
if (path != null)
sb.append(path);
if (query != null) {
sb.append('?');
sb.append(query);
}
}
if (fragment != null) {
sb.append('#');
sb.append(fragment);
}
return string = sb.toString();
}
/**
@ -1618,8 +1691,7 @@ public final class URI
* charset
*/
public String toASCIIString() {
defineString();
return encode(string);
return encode(toString());
}
@ -1825,7 +1897,7 @@ public final class URI
}
}
private void appendAuthority(StringBuffer sb,
private void appendAuthority(StringBuilder sb,
String authority,
String userInfo,
String host,
@ -1875,7 +1947,7 @@ public final class URI
}
}
private void appendSchemeSpecificPart(StringBuffer sb,
private void appendSchemeSpecificPart(StringBuilder sb,
String opaquePart,
String authority,
String userInfo,
@ -1916,7 +1988,7 @@ public final class URI
}
}
private void appendFragment(StringBuffer sb, String fragment) {
private void appendFragment(StringBuilder sb, String fragment) {
if (fragment != null) {
sb.append('#');
sb.append(quote(fragment, L_URIC, H_URIC));
@ -1933,7 +2005,7 @@ public final class URI
String query,
String fragment)
{
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
if (scheme != null) {
sb.append(scheme);
sb.append(':');
@ -1945,61 +2017,6 @@ public final class URI
return sb.toString();
}
private void defineSchemeSpecificPart() {
if (schemeSpecificPart != null) return;
StringBuffer sb = new StringBuffer();
appendSchemeSpecificPart(sb, null, getAuthority(), getUserInfo(),
host, port, getPath(), getQuery());
if (sb.length() == 0) return;
schemeSpecificPart = sb.toString();
}
private void defineString() {
if (string != null) return;
StringBuilder sb = new StringBuilder();
if (scheme != null) {
sb.append(scheme);
sb.append(':');
}
if (isOpaque()) {
sb.append(schemeSpecificPart);
} else {
if (host != null) {
sb.append("//");
if (userInfo != null) {
sb.append(userInfo);
sb.append('@');
}
boolean needBrackets = ((host.indexOf(':') >= 0)
&& !host.startsWith("[")
&& !host.endsWith("]"));
if (needBrackets) sb.append('[');
sb.append(host);
if (needBrackets) sb.append(']');
if (port != -1) {
sb.append(':');
sb.append(port);
}
} else if (authority != null) {
sb.append("//");
sb.append(authority);
}
if (path != null)
sb.append(path);
if (query != null) {
sb.append('?');
sb.append(query);
}
}
if (fragment != null) {
sb.append('#');
sb.append(fragment);
}
string = sb.toString();
}
// -- Normalization, resolution, and relativization --
// RFC2396 5.2 (6)
@ -2650,13 +2667,13 @@ public final class URI
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
private static void appendEscape(StringBuffer sb, byte b) {
private static void appendEscape(StringBuilder sb, byte b) {
sb.append('%');
sb.append(hexDigits[(b >> 4) & 0x0f]);
sb.append(hexDigits[(b >> 0) & 0x0f]);
}
private static void appendEncoded(StringBuffer sb, char c) {
private static void appendEncoded(StringBuilder sb, char c) {
ByteBuffer bb = null;
try {
bb = ThreadLocalCoders.encoderFor("UTF-8")
@ -2677,15 +2694,14 @@ public final class URI
// by the given mask pair
//
private static String quote(String s, long lowMask, long highMask) {
int n = s.length();
StringBuffer sb = null;
StringBuilder sb = null;
boolean allowNonASCII = ((lowMask & L_ESCAPED) != 0);
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c < '\u0080') {
if (!match(c, lowMask, highMask)) {
if (sb == null) {
sb = new StringBuffer();
sb = new StringBuilder();
sb.append(s, 0, i);
}
appendEscape(sb, (byte)c);
@ -2697,7 +2713,7 @@ public final class URI
&& (Character.isSpaceChar(c)
|| Character.isISOControl(c))) {
if (sb == null) {
sb = new StringBuffer();
sb = new StringBuilder();
sb.append(s, 0, i);
}
appendEncoded(sb, c);
@ -2734,7 +2750,7 @@ public final class URI
assert false;
}
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
while (bb.hasRemaining()) {
int b = bb.get() & 0xff;
if (b >= 0x80)
@ -2865,12 +2881,6 @@ public final class URI
fail("Expected " + expected, p);
}
private void failExpecting(String expected, String prior, int p)
throws URISyntaxException
{
fail("Expected " + expected + " following " + prior, p);
}
// -- Simple access to the input string --

View File

@ -310,7 +310,8 @@ public final class URL implements java.io.Serializable {
* @param host the name of the host.
* @param port the port number on the host.
* @param file the file on the host
* @exception MalformedURLException if an unknown protocol is specified.
* @exception MalformedURLException if an unknown protocol or the port
* is a negative number other than -1
* @see java.lang.System#getProperty(java.lang.String)
* @see java.net.URL#setURLStreamHandlerFactory(
* java.net.URLStreamHandlerFactory)
@ -329,9 +330,9 @@ public final class URL implements java.io.Serializable {
* name, {@code host} name, and {@code file} name. The
* default port for the specified protocol is used.
* <p>
* This method is equivalent to calling the four-argument
* constructor with the arguments being {@code protocol},
* {@code host}, {@code -1}, and {@code file}.
* This constructor is equivalent to the four-argument
* constructor with the only difference of using the
* default port for the specified protocol.
*
* No validation of the inputs is performed by this constructor.
*
@ -372,7 +373,8 @@ public final class URL implements java.io.Serializable {
* @param port the port number on the host.
* @param file the file on the host
* @param handler the stream handler for the URL.
* @exception MalformedURLException if an unknown protocol is specified.
* @exception MalformedURLException if an unknown protocol or the port
is a negative number other than -1
* @exception SecurityException
* if a security manager exists and its
* {@code checkPermission} method doesn't allow
@ -446,7 +448,9 @@ public final class URL implements java.io.Serializable {
*
* @param spec the {@code String} to parse as a URL.
* @exception MalformedURLException if no protocol is specified, or an
* unknown protocol is found, or {@code spec} is {@code null}.
* unknown protocol is found, or {@code spec} is {@code null},
* or the parsed URL fails to comply with the specific syntax
* of the associated protocol.
* @see java.net.URL#URL(java.net.URL, java.lang.String)
*/
public URL(String spec) throws MalformedURLException {
@ -493,7 +497,9 @@ public final class URL implements java.io.Serializable {
* @param context the context in which to parse the specification.
* @param spec the {@code String} to parse as a URL.
* @exception MalformedURLException if no protocol is specified, or an
* unknown protocol is found, or {@code spec} is {@code null}.
* unknown protocol is found, or {@code spec} is {@code null},
* or the parsed URL fails to comply with the specific syntax
* of the associated protocol.
* @see java.net.URL#URL(java.lang.String, java.lang.String,
* int, java.lang.String)
* @see java.net.URLStreamHandler
@ -513,7 +519,9 @@ public final class URL implements java.io.Serializable {
* @param spec the {@code String} to parse as a URL.
* @param handler the stream handler for the URL.
* @exception MalformedURLException if no protocol is specified, or an
* unknown protocol is found, or {@code spec} is {@code null}.
* unknown protocol is found, or {@code spec} is {@code null},
* or the parsed URL fails to comply with the specific syntax
* of the associated protocol.
* @exception SecurityException
* if a security manager exists and its
* {@code checkPermission} method doesn't allow

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -1550,7 +1550,7 @@ public abstract class URLConnection {
}
if (c1 == 0xFF && c2 == 0xD8 && c3 == 0xFF) {
if (c4 == 0xE0) {
if (c4 == 0xE0 || c4 == 0xEE) {
return "image/jpeg";
}
@ -1565,10 +1565,6 @@ public abstract class URLConnection {
c11 == 0)) {
return "image/jpeg";
}
if (c4 == 0xEE) {
return "image/jpg";
}
}
if (c1 == 0xD0 && c2 == 0xCF && c3 == 0x11 && c4 == 0xE0 &&

View File

@ -25,9 +25,7 @@
package java.nio;
import java.security.AccessController;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import jdk.internal.misc.JavaNioAccess;
import jdk.internal.misc.JavaLangRefAccess;
@ -603,7 +601,8 @@ class Bits { // package-private
private static final AtomicLong reservedMemory = new AtomicLong();
private static final AtomicLong totalCapacity = new AtomicLong();
private static final AtomicLong count = new AtomicLong();
private static volatile boolean memoryLimitSet = false;
private static volatile boolean memoryLimitSet;
// max. number of sleeps during try-reserving with exponentially
// increasing delay before throwing OutOfMemoryError:
// 1, 2, 4, 8, 16, 32, 64, 128, 256 (total 511 ms ~ 0.5 s)

View File

@ -26,8 +26,6 @@
package java.nio.channels;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.io.IOException;
/**
* A token representing the registration of a {@link SelectableChannel} with a
@ -363,7 +361,7 @@ public abstract class SelectionKey {
// -- Attachments --
private volatile Object attachment = null;
private volatile Object attachment;
private static final AtomicReferenceFieldUpdater<SelectionKey,Object>
attachmentUpdater = AtomicReferenceFieldUpdater.newUpdater(

View File

@ -29,11 +29,7 @@
package java.nio.channels.spi;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.nio.channels.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import jdk.internal.misc.SharedSecrets;
import sun.nio.ch.Interruptible;
@ -90,7 +86,7 @@ public abstract class AbstractInterruptibleChannel
{
private final Object closeLock = new Object();
private volatile boolean open = true;
private volatile boolean closed;
/**
* Initializes a new instance of this class.
@ -110,9 +106,9 @@ public abstract class AbstractInterruptibleChannel
*/
public final void close() throws IOException {
synchronized (closeLock) {
if (!open)
if (closed)
return;
open = false;
closed = true;
implCloseChannel();
}
}
@ -136,7 +132,7 @@ public abstract class AbstractInterruptibleChannel
protected abstract void implCloseChannel() throws IOException;
public final boolean isOpen() {
return open;
return !closed;
}
@ -158,9 +154,9 @@ public abstract class AbstractInterruptibleChannel
interruptor = new Interruptible() {
public void interrupt(Thread target) {
synchronized (closeLock) {
if (!open)
if (closed)
return;
open = false;
closed = true;
interrupted = target;
try {
AbstractInterruptibleChannel.this.implCloseChannel();
@ -202,7 +198,7 @@ public abstract class AbstractInterruptibleChannel
this.interrupted = null;
throw new ClosedByInterruptException();
}
if (!completed && !open)
if (!completed && closed)
throw new AsynchronousCloseException();
}

View File

@ -276,7 +276,7 @@ public abstract class Charset
/* -- Static methods -- */
private static volatile String bugLevel = null;
private static volatile String bugLevel;
static boolean atBugLevel(String bl) { // package-private
String level = bugLevel;
@ -324,8 +324,8 @@ public abstract class Charset
// Cache of the most-recently-returned charsets,
// along with the names that were used to find them
//
private static volatile Object[] cache1 = null; // "Level 1" cache
private static volatile Object[] cache2 = null; // "Level 2" cache
private static volatile Object[] cache1; // "Level 1" cache
private static volatile Object[] cache2; // "Level 2" cache
private static void cache(String charsetName, Charset cs) {
cache2 = cache1;

View File

@ -124,7 +124,7 @@ public class SecureRandom extends java.util.Random {
private String algorithm;
// Seed Generator
private static volatile SecureRandom seedGenerator = null;
private static volatile SecureRandom seedGenerator;
/**
* Constructs a secure random number generator (RNG) implementing the
@ -522,10 +522,12 @@ public class SecureRandom extends java.util.Random {
* @see #setSeed
*/
public static byte[] getSeed(int numBytes) {
if (seedGenerator == null) {
seedGenerator = new SecureRandom();
SecureRandom seedGen = seedGenerator;
if (seedGen == null) {
seedGen = new SecureRandom();
seedGenerator = seedGen;
}
return seedGenerator.generateSeed(numBytes);
return seedGen.generateSeed(numBytes);
}
/**

View File

@ -630,7 +630,9 @@ public class DateFormatSymbols implements Serializable, Cloneable {
hashCode = 11 * hashCode + Arrays.hashCode(ampms);
hashCode = 11 * hashCode + Arrays.deepHashCode(getZoneStringsWrapper());
hashCode = 11 * hashCode + Objects.hashCode(localPatternChars);
cachedHashCode = hashCode;
if (hashCode != 0) {
cachedHashCode = hashCode;
}
}
return hashCode;
@ -670,12 +672,12 @@ public class DateFormatSymbols implements Serializable, Cloneable {
private static final ConcurrentMap<Locale, SoftReference<DateFormatSymbols>> cachedInstances
= new ConcurrentHashMap<>(3);
private transient int lastZoneIndex = 0;
private transient int lastZoneIndex;
/**
* Cached hash code
*/
transient volatile int cachedHashCode = 0;
transient volatile int cachedHashCode;
private void initializeData(Locale desiredLocale) {
locale = desiredLocale;

View File

@ -42,14 +42,8 @@ import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.text.spi.DecimalFormatSymbolsProvider;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import sun.util.locale.provider.LocaleProviderAdapter;
import sun.util.locale.provider.LocaleServiceProviderPool;
import sun.util.locale.provider.ResourceBundleBasedAdapter;
@ -875,7 +869,7 @@ public class DecimalFormatSymbols implements Cloneable, Serializable {
// currency; only the ISO code is serialized.
private transient Currency currency;
private transient volatile boolean currencyInitialized = false;
private transient volatile boolean currencyInitialized;
// Proclaim JDK 1.1 FCS compatibility
static final long serialVersionUID = 5772796243397350300L;

View File

@ -41,7 +41,7 @@ package java.text;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import sun.misc.FloatingDecimal;
import jdk.internal.math.FloatingDecimal;
/**
* Digit List. Private to DecimalFormat.

View File

@ -147,6 +147,10 @@ public final class LocalDate
* This could be used by an application as a "far future" date.
*/
public static final LocalDate MAX = LocalDate.of(Year.MAX_VALUE, 12, 31);
/**
* The epoch year {@code LocalDate}, '1970-01-01'.
*/
public static final LocalDate EPOCH = LocalDate.of(1970, 1, 1);
/**
* Serialization version.
@ -1864,6 +1868,29 @@ public final class LocalDate
return total - DAYS_0000_TO_1970;
}
/**
* Converts this {@code LocalDate} to the number of seconds since the epoch
* of 1970-01-01T00:00:00Z.
* <p>
* This combines this local date with the specified time and
* offset to calculate the epoch-second value, which is the
* number of elapsed seconds from 1970-01-01T00:00:00Z.
* Instants on the time-line after the epoch are positive, earlier
* are negative.
*
* @param time the local time, not null
* @param offset the zone offset, not null
* @return the number of seconds since the epoch of 1970-01-01T00:00:00Z, may be negative
* @since 9
*/
public long toEpochSecond(LocalTime time, ZoneOffset offset) {
Objects.requireNonNull(time, "time");
Objects.requireNonNull(offset, "offset");
long secs = toEpochDay() * SECONDS_PER_DAY + time.toSecondOfDay();
secs -= offset.getTotalSeconds();
return secs;
}
//-----------------------------------------------------------------------
/**
* Compares this date to another date.

View File

@ -1490,6 +1490,30 @@ public final class LocalTime
return total;
}
/**
* Converts this {@code LocalTime} to the number of seconds since the epoch
* of 1970-01-01T00:00:00Z.
* <p>
* This combines this local time with the specified date and
* offset to calculate the epoch-second value, which is the
* number of elapsed seconds from 1970-01-01T00:00:00Z.
* Instants on the time-line after the epoch are positive, earlier
* are negative.
*
* @param date the local date, not null
* @param offset the zone offset, not null
* @return the number of seconds since the epoch of 1970-01-01T00:00:00Z, may be negative
* @since 9
*/
public long toEpochSecond(LocalDate date, ZoneOffset offset) {
Objects.requireNonNull(date, "date");
Objects.requireNonNull(offset, "offset");
long epochDay = date.toEpochDay();
long secs = epochDay * 86400 + toSecondOfDay();
secs -= offset.getTotalSeconds();
return secs;
}
//-----------------------------------------------------------------------
/**
* Compares this time to another time.

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -1232,6 +1232,28 @@ public final class OffsetTime
return nod - offsetNanos;
}
/**
* Converts this {@code OffsetTime} to the number of seconds since the epoch
* of 1970-01-01T00:00:00Z.
* <p>
* This combines this offset time with the specified date to calculate the
* epoch-second value, which is the number of elapsed seconds from
* 1970-01-01T00:00:00Z.
* Instants on the time-line after the epoch are positive, earlier
* are negative.
*
* @param date the localdate, not null
* @return the number of seconds since the epoch of 1970-01-01T00:00:00Z, may be negative
* @since 9
*/
public long toEpochSecond(LocalDate date) {
Objects.requireNonNull(date, "date");
long epochDay = date.toEpochDay();
long secs = epochDay * 86400 + time.toSecondOfDay();
secs -= offset.getTotalSeconds();
return secs;
}
//-----------------------------------------------------------------------
/**
* Compares this {@code OffsetTime} to another time.

View File

@ -80,6 +80,7 @@ import java.time.DateTimeException;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.chrono.ChronoLocalDateTime;
import java.time.chrono.Chronology;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatterBuilder.CompositePrinterParser;
@ -473,6 +474,17 @@ import java.util.Set;
* day-of-week was valid for the date.
* <li>If an {@linkplain #parsedExcessDays() excess number of days}
* was parsed then it is added to the date if a date is available.
* <li> If a second-based field is present, but {@code LocalTime} was not parsed,
* then the resolver ensures that milli, micro and nano second values are
* available to meet the contract of {@link ChronoField}.
* These will be set to zero if missing.
* <li>If both date and time were parsed and either an offset or zone is present,
* the field {@link ChronoField#INSTANT_SECONDS} is created.
* If an offset was parsed then the offset will be combined with the
* {@code LocalDateTime} to form the instant, with any zone ignored.
* If a {@code ZoneId} was parsed without an offset then the zone will be
* combined with the {@code LocalDateTime} to form the instant using the rules
* of {@link ChronoLocalDateTime#atZone(ZoneId)}.
* </ol>
*
* @implSpec

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -594,15 +594,16 @@ final class Parsed implements TemporalAccessor {
private void resolveInstant() {
// add instant seconds if we have date, time and zone
// Offset (if present) will be given priority over the zone.
if (date != null && time != null) {
if (zone != null) {
long instant = date.atTime(time).atZone(zone).getLong(ChronoField.INSTANT_SECONDS);
Long offsetSecs = fieldValues.get(OFFSET_SECONDS);
if (offsetSecs != null) {
ZoneOffset offset = ZoneOffset.ofTotalSeconds(offsetSecs.intValue());
long instant = date.atTime(time).atZone(offset).toEpochSecond();
fieldValues.put(INSTANT_SECONDS, instant);
} else {
Long offsetSecs = fieldValues.get(OFFSET_SECONDS);
if (offsetSecs != null) {
ZoneOffset offset = ZoneOffset.ofTotalSeconds(offsetSecs.intValue());
long instant = date.atTime(time).atZone(offset).getLong(ChronoField.INSTANT_SECONDS);
if (zone != null) {
long instant = date.atTime(time).atZone(zone).toEpochSecond();
fieldValues.put(INSTANT_SECONDS, instant);
}
}

View File

@ -60,8 +60,8 @@ import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQueries;
import java.time.temporal.UnsupportedTemporalTypeException;
import sun.misc.DoubleConsts;
import sun.misc.FormattedFloatingDecimal;
import jdk.internal.math.DoubleConsts;
import jdk.internal.math.FormattedFloatingDecimal;
/**
* An interpreter for printf-style format strings. This class provides support

View File

@ -62,7 +62,6 @@ import sun.util.locale.ParseStatus;
import sun.util.locale.provider.LocaleProviderAdapter;
import sun.util.locale.provider.LocaleResources;
import sun.util.locale.provider.LocaleServiceProviderPool;
import sun.util.locale.provider.ResourceBundleBasedAdapter;
/**
* A <code>Locale</code> object represents a specific geographical, political,
@ -2016,11 +2015,11 @@ public final class Locale implements Cloneable, Serializable {
/**
* Calculated hashcode
*/
private transient volatile int hashCodeValue = 0;
private transient volatile int hashCodeValue;
private static volatile Locale defaultLocale = initDefault();
private static volatile Locale defaultDisplayLocale = null;
private static volatile Locale defaultFormatLocale = null;
private static volatile Locale defaultDisplayLocale;
private static volatile Locale defaultFormatLocale;
private transient volatile String languageTag;
@ -2207,9 +2206,9 @@ public final class Locale implements Cloneable, Serializable {
baseLocale.getRegion(), baseLocale.getVariant(), localeExtensions);
}
private static volatile String[] isoLanguages = null;
private static volatile String[] isoLanguages;
private static volatile String[] isoCountries = null;
private static volatile String[] isoCountries;
private static String convertOldISOCodes(String language) {
// we accept both the old and the new ISO codes for the languages whose ISO
@ -2851,7 +2850,7 @@ public final class Locale implements Cloneable, Serializable {
private final String range;
private final double weight;
private volatile int hash = 0;
private volatile int hash;
/**
* Constructs a {@code LanguageRange} using the given {@code range}.
@ -3108,14 +3107,17 @@ public final class Locale implements Cloneable, Serializable {
*/
@Override
public int hashCode() {
if (hash == 0) {
int result = 17;
result = 37*result + range.hashCode();
int h = hash;
if (h == 0) {
h = 17;
h = 37*h + range.hashCode();
long bitsWeight = Double.doubleToLongBits(weight);
result = 37*result + (int)(bitsWeight ^ (bitsWeight >>> 32));
hash = result;
h = 37*h + (int)(bitsWeight ^ (bitsWeight >>> 32));
if (h != 0) {
hash = h;
}
}
return hash;
return h;
}
/**

View File

@ -950,7 +950,7 @@ public final class Pattern
* Boolean indicating this Pattern is compiled; this is necessary in order
* to lazily compile deserialized Patterns.
*/
private transient volatile boolean compiled = false;
private transient volatile boolean compiled;
/**
* The normalized pattern string.
@ -1332,7 +1332,6 @@ public final class Pattern
localCount = 0;
// if length > 0, the Pattern is lazily compiled
compiled = false;
if (pattern.length() == 0) {
root = new Start(lastAccept);
matchRoot = lastAccept;
@ -1377,7 +1376,6 @@ public final class Pattern
* equivalences of the characters.
*/
private void normalize() {
boolean inCharClass = false;
int lastCodePoint = -1;
// Convert pattern into normalized form
@ -1551,7 +1549,6 @@ public final class Pattern
// offset maintains the index in code units.
loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
len = countChars(input, offset, 1);
boolean skip = false;
for(int y=x-1; y>=0; y--) {
if (combClass[y] == combClass[x]) {
continue loop;
@ -1566,8 +1563,7 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
temp[index++] = prefix + sre;
}
String[] result = new String[index];
for (int x=0; x<index; x++)
result[x] = temp[x];
System.arraycopy(temp, 0, result, 0, index);
return result;
}
@ -1742,9 +1738,11 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
}
Map<String, Integer> namedGroups() {
if (namedGroups == null)
namedGroups = new HashMap<>(2);
return namedGroups;
Map<String, Integer> groups = namedGroups;
if (groups == null) {
namedGroups = groups = new HashMap<>(2);
}
return groups;
}
/**

View File

@ -72,7 +72,7 @@ public
class ZipFile implements ZipConstants, Closeable {
private final String name; // zip file name
private volatile boolean closeRequested = false;
private volatile boolean closeRequested;
private Source zsrc;
private ZipCoder zc;
@ -366,7 +366,7 @@ class ZipFile implements ZipConstants, Closeable {
}
private class ZipFileInflaterInputStream extends InflaterInputStream {
private volatile boolean closeRequested = false;
private volatile boolean closeRequested;
private boolean eof = false;
private final ZipFileInputStream zfin;
@ -653,7 +653,7 @@ class ZipFile implements ZipConstants, Closeable {
* (possibly compressed) zip file entry.
*/
private class ZipFileInputStream extends InputStream {
private volatile boolean closeRequested = false;
private volatile boolean closeRequested;
private long pos; // current position within entry data
protected long rem; // number of remaining bytes within entry
protected long size; // uncompressed size of this entry

View File

@ -326,20 +326,22 @@ public final class LazyLoggers {
}
// Do not expose this outside of this package.
private static volatile LoggerFinder provider = null;
private static volatile LoggerFinder provider;
private static LoggerFinder accessLoggerFinder() {
if (provider == null) {
LoggerFinder prov = provider;
if (prov == null) {
// no need to lock: it doesn't matter if we call
// getLoggerFinder() twice - since LoggerFinder already caches
// the result.
// This is just an optimization to avoid the cost of calling
// doPrivileged every time.
final SecurityManager sm = System.getSecurityManager();
provider = sm == null ? LoggerFinder.getLoggerFinder() :
prov = sm == null ? LoggerFinder.getLoggerFinder() :
AccessController.doPrivileged(
(PrivilegedAction<LoggerFinder>)LoggerFinder::getLoggerFinder);
provider = prov;
}
return provider;
return prov;
}
// Avoid using lambda here as lazy loggers could be created early

View File

@ -23,7 +23,7 @@
* questions.
*/
package sun.misc;
package jdk.internal.math;
/**
* This class contains additional constants documenting limits of the

View File

@ -22,7 +22,7 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.misc;
package jdk.internal.math;
import java.math.BigInteger;
import java.util.Arrays;

View File

@ -23,7 +23,7 @@
* questions.
*/
package sun.misc;
package jdk.internal.math;
/**
* This class contains additional constants documenting limits of the

View File

@ -23,7 +23,7 @@
* questions.
*/
package sun.misc;
package jdk.internal.math;
import java.util.Arrays;
import java.util.regex.*;

View File

@ -23,7 +23,7 @@
* questions.
*/
package sun.misc;
package jdk.internal.math;
import java.util.Arrays;

View File

@ -39,7 +39,6 @@ import java.util.concurrent.ThreadFactory;
import java.util.function.Function;
import sun.misc.InnocuousThread;
import sun.misc.ManagedLocalsThread;
/**
* CleanerImpl manages a set of object references and corresponding cleaning actions.
@ -130,8 +129,8 @@ public final class CleanerImpl implements Runnable {
*/
public void run() {
Thread t = Thread.currentThread();
ManagedLocalsThread mlThread = (t instanceof ManagedLocalsThread)
? (ManagedLocalsThread) t
InnocuousThread mlThread = (t instanceof InnocuousThread)
? (InnocuousThread) t
: null;
while (!phantomCleanableList.isListEmpty() ||
!weakCleanableList.isListEmpty() ||
@ -787,4 +786,3 @@ public final class CleanerImpl implements Runnable {
}
}

View File

@ -27,9 +27,6 @@ package sun.misc;
import static java.lang.Thread.State.*;
import java.util.Properties;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class VM {
@ -288,10 +285,10 @@ public class VM {
}
/* Current count of objects pending for finalization */
private static volatile int finalRefCount = 0;
private static volatile int finalRefCount;
/* Peak count of objects pending for finalization */
private static volatile int peakFinalRefCount = 0;
private static volatile int peakFinalRefCount;
/*
* Gets the number of objects pending for finalization.

View File

@ -54,12 +54,12 @@ import sun.util.logging.PlatformLogger;
* @author jccollet
*/
public class HttpCapture {
private File file = null;
private File file;
private boolean incoming = true;
private BufferedWriter out = null;
private static boolean initialized = false;
private static volatile ArrayList<Pattern> patterns = null;
private static volatile ArrayList<String> capFiles = null;
private BufferedWriter out;
private static boolean initialized;
private static volatile ArrayList<Pattern> patterns;
private static volatile ArrayList<String> capFiles;
private static synchronized void init() {
initialized = true;

View File

@ -98,7 +98,7 @@ public class HttpClient extends NetworkClient {
// from previous releases.
private static boolean retryPostProp = true;
volatile boolean keepingAlive = false; /* this is a keep-alive connection */
volatile boolean keepingAlive; /* this is a keep-alive connection */
int keepAliveConnections = -1; /* number of keep-alives left */
/**Idle timeout value, in milliseconds. Zero means infinity,

View File

@ -51,14 +51,14 @@ abstract class AsynchronousServerSocketChannelImpl
protected final FileDescriptor fd;
// the local address to which the channel's socket is bound
protected volatile InetSocketAddress localAddress = null;
protected volatile InetSocketAddress localAddress;
// need this lock to set local address
private final Object stateLock = new Object();
// close support
private ReadWriteLock closeLock = new ReentrantReadWriteLock();
private volatile boolean open = true;
private volatile boolean closed;
// set true when accept operation is cancelled
private volatile boolean acceptKilled;
@ -73,7 +73,7 @@ abstract class AsynchronousServerSocketChannelImpl
@Override
public final boolean isOpen() {
return open;
return !closed;
}
/**
@ -102,9 +102,9 @@ abstract class AsynchronousServerSocketChannelImpl
// synchronize with any threads using file descriptor/handle
closeLock.writeLock().lock();
try {
if (!open)
if (closed)
return; // already closed
open = false;
closed = true;
} finally {
closeLock.writeLock().unlock();
}

View File

@ -54,8 +54,8 @@ abstract class AsynchronousSocketChannelImpl
// protects state, localAddress, and remoteAddress
protected final Object stateLock = new Object();
protected volatile InetSocketAddress localAddress = null;
protected volatile InetSocketAddress remoteAddress = null;
protected volatile InetSocketAddress localAddress;
protected volatile InetSocketAddress remoteAddress;
// State, increases monotonically
static final int ST_UNINITIALIZED = -1;
@ -78,7 +78,7 @@ abstract class AsynchronousSocketChannelImpl
// close support
private final ReadWriteLock closeLock = new ReentrantReadWriteLock();
private volatile boolean open = true;
private volatile boolean closed;
// set true when exclusive binding is on and SO_REUSEADDR is emulated
private boolean isReuseAddress;
@ -106,7 +106,7 @@ abstract class AsynchronousSocketChannelImpl
@Override
public final boolean isOpen() {
return open;
return !closed;
}
/**
@ -135,9 +135,9 @@ abstract class AsynchronousSocketChannelImpl
// synchronize with any threads initiating asynchronous operations
closeLock.writeLock().lock();
try {
if (!open)
if (closed)
return; // already closed
open = false;
closed = true;
} finally {
closeLock.writeLock().unlock();
}

View File

@ -58,8 +58,8 @@ class DatagramChannelImpl
private final ProtocolFamily family;
// IDs of native threads doing reads and writes, for signalling
private volatile long readerThread = 0;
private volatile long writerThread = 0;
private volatile long readerThread;
private volatile long writerThread;
// Cached InetAddress and port for unconnected DatagramChannels
// used by receive0

View File

@ -46,7 +46,7 @@ public class DatagramSocketAdaptor
private final DatagramChannelImpl dc;
// Timeout "option" value for receives
private volatile int timeout = 0;
private volatile int timeout;
// ## super will create a useless impl
private DatagramSocketAdaptor(DatagramChannelImpl dc) throws IOException {

View File

@ -31,7 +31,7 @@ import java.nio.channels.*;
public class FileLockImpl
extends FileLock
{
private volatile boolean valid = true;
private volatile boolean invalid;
FileLockImpl(FileChannel channel, long position, long size, boolean shared)
{
@ -44,25 +44,25 @@ public class FileLockImpl
}
public boolean isValid() {
return valid;
return !invalid;
}
void invalidate() {
assert Thread.holdsLock(this);
valid = false;
invalid = true;
}
public synchronized void release() throws IOException {
Channel ch = acquiredBy();
if (!ch.isOpen())
throw new ClosedChannelException();
if (valid) {
if (isValid()) {
if (ch instanceof FileChannelImpl)
((FileChannelImpl)ch).release(this);
else if (ch instanceof AsynchronousFileChannelImpl)
((AsynchronousFileChannelImpl)ch).release(this);
else throw new AssertionError();
valid = false;
invalidate();
}
}
}

View File

@ -43,8 +43,7 @@ class MembershipKeyImpl
private final NetworkInterface interf;
private final InetAddress source;
// true when key is valid
private volatile boolean valid = true;
private volatile boolean invalid;
// lock used when creating or accessing blockedSet
private Object stateLock = new Object();
@ -134,12 +133,12 @@ class MembershipKeyImpl
}
public boolean isValid() {
return valid;
return !invalid;
}
// package-private
void invalidate() {
valid = false;
invalid = true;
}
public void drop() {

View File

@ -32,7 +32,6 @@ import java.nio.channels.*;
import java.util.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import sun.net.ExtendedOptionsImpl;
@ -55,7 +54,7 @@ public class Net {
// -- Miscellaneous utilities --
private static volatile boolean checkedIPv6 = false;
private static volatile boolean checkedIPv6;
private static volatile boolean isIPv6Available;
/**

View File

@ -45,7 +45,7 @@ public class ServerSocketAdaptor // package-private
private final ServerSocketChannelImpl ssc;
// Timeout "option" value for accepts
private volatile int timeout = 0;
private volatile int timeout;
public static ServerSocket create(ServerSocketChannelImpl ssc) {
try {

View File

@ -54,7 +54,7 @@ class ServerSocketChannelImpl
private int fdVal;
// ID of native thread currently blocked in this channel, for signalling
private volatile long thread = 0;
private volatile long thread;
// Lock held by thread currently blocked in this channel
private final Object lock = new Object();

View File

@ -26,13 +26,11 @@
package sun.nio.ch;
import java.io.*;
import java.lang.ref.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.*;
// Make a socket channel look like a socket.
@ -55,7 +53,7 @@ public class SocketAdaptor
private final SocketChannelImpl sc;
// Timeout "option" value for reads
private volatile int timeout = 0;
private volatile int timeout;
private SocketAdaptor(SocketChannelImpl sc) throws SocketException {
super((SocketImpl) null);

View File

@ -56,8 +56,8 @@ class SocketChannelImpl
private final int fdVal;
// IDs of native threads doing reads and writes, for signalling
private volatile long readerThread = 0;
private volatile long writerThread = 0;
private volatile long readerThread;
private volatile long writerThread;
// Lock held by current reading or connecting thread
private final Object readLock = new Object();

View File

@ -25,13 +25,10 @@
package sun.nio.ch;
import java.lang.ref.SoftReference;
import java.lang.reflect.*;
import java.io.IOException;
import java.io.FileDescriptor;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
@ -295,7 +292,7 @@ public class Util {
return pageSize;
}
private static volatile Constructor<?> directByteBufferConstructor = null;
private static volatile Constructor<?> directByteBufferConstructor;
private static void initDBBConstructor() {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@ -340,7 +337,7 @@ public class Util {
return dbb;
}
private static volatile Constructor<?> directByteBufferRConstructor = null;
private static volatile Constructor<?> directByteBufferRConstructor;
private static void initDBBRConstructor() {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@ -388,7 +385,7 @@ public class Util {
// -- Bug compatibility --
private static volatile String bugLevel = null;
private static volatile String bugLevel;
static boolean atBugLevel(String bl) { // package-private
if (bugLevel == null) {

View File

@ -39,10 +39,10 @@ public class StreamDecoder extends Reader
private static final int MIN_BYTE_BUFFER_SIZE = 32;
private static final int DEFAULT_BYTE_BUFFER_SIZE = 8192;
private volatile boolean isOpen = true;
private volatile boolean closed;
private void ensureOpen() throws IOException {
if (!isOpen)
if (closed)
throw new IOException("Stream closed");
}
@ -188,15 +188,15 @@ public class StreamDecoder extends Reader
public void close() throws IOException {
synchronized (lock) {
if (!isOpen)
if (closed)
return;
implClose();
isOpen = false;
closed = true;
}
}
private boolean isOpen() {
return isOpen;
return !closed;
}

View File

@ -38,10 +38,10 @@ public class StreamEncoder extends Writer
private static final int DEFAULT_BYTE_BUFFER_SIZE = 8192;
private volatile boolean isOpen = true;
private volatile boolean closed;
private void ensureOpen() throws IOException {
if (!isOpen)
if (closed)
throw new IOException("Stream closed");
}
@ -156,15 +156,15 @@ public class StreamEncoder extends Writer
public void close() throws IOException {
synchronized (lock) {
if (!isOpen)
if (closed)
return;
implClose();
isOpen = false;
closed = true;
}
}
private boolean isOpen() {
return isOpen;
return !closed;
}

View File

@ -44,9 +44,9 @@ class MethodAccessorGenerator extends AccessorGenerator {
// Only used if forSerialization is true
private static final short NUM_SERIALIZATION_CPOOL_ENTRIES = (short) 2;
private static volatile int methodSymnum = 0;
private static volatile int constructorSymnum = 0;
private static volatile int serializationConstructorSymnum = 0;
private static volatile int methodSymnum;
private static volatile int constructorSymnum;
private static volatile int serializationConstructorSymnum;
private Class<?> declaringClass;
private Class<?>[] parameterTypes;

View File

@ -299,7 +299,7 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
}});
}
private transient volatile Method[] memberMethods = null;
private transient volatile Method[] memberMethods;
/**
* Validates that a method is structurally appropriate for an

View File

@ -1105,41 +1105,6 @@ final class CipherBox {
return fragLen;
}
/*
* Is this cipher available?
*
* This method can only be called by CipherSuite.BulkCipher.isAvailable()
* to test the availability of a cipher suites. Please DON'T use it in
* other places, otherwise, the behavior may be unexpected because we may
* initialize AEAD cipher improperly in the method.
*/
Boolean isAvailable() {
// We won't know whether a cipher for a particular key size is
// available until the cipher is successfully initialized.
//
// We do not initialize AEAD cipher in the constructor. Need to
// initialize the cipher to ensure that the AEAD mode for a
// particular key size is supported.
if (cipherType == AEAD_CIPHER) {
try {
Authenticator authenticator =
new Authenticator(protocolVersion);
byte[] nonce = authenticator.sequenceNumber();
byte[] iv = Arrays.copyOf(fixedIv,
fixedIv.length + nonce.length);
System.arraycopy(nonce, 0, iv, fixedIv.length, nonce.length);
GCMParameterSpec spec = new GCMParameterSpec(tagSize * 8, iv);
cipher.init(mode, key, spec, random);
} catch (Exception e) {
return Boolean.FALSE;
}
} // Otherwise, we have initialized the cipher in the constructor.
return Boolean.TRUE;
}
/**
* Sanity check the length of a fragment before decryption.
*

View File

@ -77,12 +77,6 @@ final class CipherSuite implements Comparable<CipherSuite> {
// minimum priority for default enabled CipherSuites
static final int DEFAULT_SUITES_PRIORITY = 300;
// Flag indicating if CipherSuite availability can change dynamically.
// This is the case when we rely on a JCE cipher implementation that
// may not be available in the installed JCE providers.
// It is true because we might not have an ECC implementation.
static final boolean DYNAMIC_AVAILABILITY = true;
private static final boolean ALLOW_ECC = Debug.getBooleanProperty
("com.sun.net.ssl.enableECC", true);
@ -176,9 +170,6 @@ final class CipherSuite implements Comparable<CipherSuite> {
* Return whether this CipherSuite is available for use. A
* CipherSuite may be unavailable even if it is supported
* (i.e. allowed == true) if the required JCE cipher is not installed.
* In some configuration, this situation may change over time, call
* CipherSuiteList.clearAvailableCache() before this method to obtain
* the most current status.
*/
boolean isAvailable() {
return allowed && keyExchange.isAvailable() && cipher.isAvailable();
@ -471,10 +462,6 @@ final class CipherSuite implements Comparable<CipherSuite> {
B_AES_128_GCM(CIPHER_AES_GCM, AEAD_CIPHER, 16, 12, 4, true),
B_AES_256_GCM(CIPHER_AES_GCM, AEAD_CIPHER, 32, 12, 4, true);
// Map BulkCipher -> Boolean(available)
private static final Map<BulkCipher,Boolean> availableCache =
new HashMap<>(8);
// descriptive name including key size, e.g. AES/128
final String description;
@ -518,6 +505,9 @@ final class CipherSuite implements Comparable<CipherSuite> {
// The secure random used to detect the cipher availability.
private static final SecureRandom secureRandom;
// runtime availability
private final boolean isAvailable;
static {
try {
secureRandom = JsseJce.getSecureRandom();
@ -542,6 +532,17 @@ final class CipherSuite implements Comparable<CipherSuite> {
this.expandedKeySize = expandedKeySize;
this.exportable = true;
// availability of this bulk cipher
//
// Currently all supported ciphers except AES are always available
// via the JSSE internal implementations. We also assume AES/128 of
// CBC mode is always available since it is shipped with the SunJCE
// provider. However, AES/256 is unavailable when the default JCE
// policy jurisdiction files are installed because of key length
// restrictions.
this.isAvailable =
allowed ? isUnlimited(keySize, transformation) : false;
}
BulkCipher(String transformation, CipherType cipherType, int keySize,
@ -558,6 +559,17 @@ final class CipherSuite implements Comparable<CipherSuite> {
this.expandedKeySize = keySize;
this.exportable = false;
// availability of this bulk cipher
//
// Currently all supported ciphers except AES are always available
// via the JSSE internal implementations. We also assume AES/128 of
// CBC mode is always available since it is shipped with the SunJCE
// provider. However, AES/256 is unavailable when the default JCE
// policy jurisdiction files are installed because of key length
// restrictions.
this.isAvailable =
allowed ? isUnlimited(keySize, transformation) : false;
}
/**
@ -575,86 +587,29 @@ final class CipherSuite implements Comparable<CipherSuite> {
/**
* Test if this bulk cipher is available. For use by CipherSuite.
*
* Currently all supported ciphers except AES are always available
* via the JSSE internal implementations. We also assume AES/128 of
* CBC mode is always available since it is shipped with the SunJCE
* provider. However, AES/256 is unavailable when the default JCE
* policy jurisdiction files are installed because of key length
* restrictions, and AEAD is unavailable when the underlying providers
* do not support AEAD/GCM mode.
*/
boolean isAvailable() {
if (allowed == false) {
return false;
return this.isAvailable;
}
private static boolean isUnlimited(int keySize, String transformation) {
int keySizeInBits = keySize * 8;
if (keySizeInBits > 128) { // need the JCE unlimited
// strength jurisdiction policy
try {
if (Cipher.getMaxAllowedKeyLength(
transformation) < keySizeInBits) {
return false;
}
} catch (Exception e) {
return false;
}
}
if ((this == B_AES_256) ||
(this.cipherType == CipherType.AEAD_CIPHER)) {
return isAvailable(this);
}
// always available
return true;
}
// for use by CipherSuiteList.clearAvailableCache();
static synchronized void clearAvailableCache() {
if (DYNAMIC_AVAILABILITY) {
availableCache.clear();
}
}
private static synchronized boolean isAvailable(BulkCipher cipher) {
Boolean b = availableCache.get(cipher);
if (b == null) {
int keySizeInBits = cipher.keySize * 8;
if (keySizeInBits > 128) { // need the JCE unlimited
// strength jurisdiction policy
try {
if (Cipher.getMaxAllowedKeyLength(
cipher.transformation) < keySizeInBits) {
b = Boolean.FALSE;
}
} catch (Exception e) {
b = Boolean.FALSE;
}
}
if (b == null) {
b = Boolean.FALSE; // may be reset to TRUE if
// the cipher is available
CipherBox temporary = null;
try {
SecretKey key = new SecretKeySpec(
new byte[cipher.expandedKeySize],
cipher.algorithm);
IvParameterSpec iv;
if (cipher.cipherType == CipherType.AEAD_CIPHER) {
iv = new IvParameterSpec(
new byte[cipher.fixedIvSize]);
} else {
iv = new IvParameterSpec(new byte[cipher.ivSize]);
}
temporary = cipher.newCipher(
ProtocolVersion.DEFAULT_TLS,
key, iv, secureRandom, true);
b = temporary.isAvailable();
} catch (NoSuchAlgorithmException e) {
// not available
} finally {
if (temporary != null) {
temporary.dispose();
}
}
}
availableCache.put(cipher, b);
}
return b.booleanValue();
}
@Override
public String toString() {
return description;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -74,24 +74,12 @@ final class CipherSuiteList {
throw new IllegalArgumentException("CipherSuites may not be null");
}
cipherSuites = new ArrayList<CipherSuite>(names.length);
// refresh available cache once if a CipherSuite is not available
// (maybe new JCE providers have been installed)
boolean refreshed = false;
for (int i = 0; i < names.length; i++) {
String suiteName = names[i];
CipherSuite suite = CipherSuite.valueOf(suiteName);
if (suite.isAvailable() == false) {
if (refreshed == false) {
// clear the cache so that the isAvailable() call below
// does a full check
clearAvailableCache();
refreshed = true;
}
// still missing?
if (suite.isAvailable() == false) {
throw new IllegalArgumentException("Cannot support "
+ suiteName + " with currently installed providers");
}
throw new IllegalArgumentException("Cannot support "
+ suiteName + " with currently installed providers");
}
cipherSuites.add(suite);
}
@ -195,16 +183,4 @@ final class CipherSuiteList {
}
s.putBytes16(suiteBytes);
}
/**
* Clear cache of available ciphersuites. If we support all ciphers
* internally, there is no need to clear the cache and calling this
* method has no effect.
*/
static synchronized void clearAvailableCache() {
if (CipherSuite.DYNAMIC_AVAILABILITY) {
CipherSuite.BulkCipher.clearAvailableCache();
JsseJce.clearEcAvailable();
}
}
}

View File

@ -55,11 +55,6 @@ final class JsseJce {
private static final ProviderList fipsProviderList;
// Flag indicating whether EC crypto is available.
// If null, then we have not checked yet.
// If yes, then all the EC based crypto we need is available.
private static Boolean ecAvailable;
// Flag indicating whether Kerberos crypto is available.
// If true, then all the Kerberos-based crypto we need is available.
private static final boolean kerberosAvailable;
@ -180,24 +175,8 @@ final class JsseJce {
// no instantiation of this class
}
static synchronized boolean isEcAvailable() {
if (ecAvailable == null) {
try {
JsseJce.getSignature(SIGNATURE_ECDSA);
JsseJce.getSignature(SIGNATURE_RAWECDSA);
JsseJce.getKeyAgreement("ECDH");
JsseJce.getKeyFactory("EC");
JsseJce.getKeyPairGenerator("EC");
ecAvailable = true;
} catch (Exception e) {
ecAvailable = false;
}
}
return ecAvailable;
}
static synchronized void clearEcAvailable() {
ecAvailable = null;
static boolean isEcAvailable() {
return EcAvailability.isAvailable;
}
static boolean isKerberosAvailable() {
@ -399,4 +378,27 @@ final class JsseJce {
}
}
// lazy initialization holder class idiom for static default parameters
//
// See Effective Java Second Edition: Item 71.
private static class EcAvailability {
// Is EC crypto available?
private final static boolean isAvailable;
static {
boolean mediator = true;
try {
JsseJce.getSignature(SIGNATURE_ECDSA);
JsseJce.getSignature(SIGNATURE_RAWECDSA);
JsseJce.getKeyAgreement("ECDH");
JsseJce.getKeyFactory("EC");
JsseJce.getKeyPairGenerator("EC");
} catch (Exception e) {
mediator = false;
}
isAvailable = mediator;
}
}
}

View File

@ -52,18 +52,8 @@ public abstract class SSLContextImpl extends SSLContextSpi {
private X509TrustManager trustManager;
private SecureRandom secureRandom;
// supported and default protocols
private ProtocolList defaultServerProtocolList;
private ProtocolList defaultClientProtocolList;
private ProtocolList supportedProtocolList;
// supported and default cipher suites
private CipherSuiteList defaultServerCipherSuiteList;
private CipherSuiteList defaultClientCipherSuiteList;
private CipherSuiteList supportedCipherSuiteList;
// DTLS cookie exchange manager
private HelloCookieManager helloCookieManager;
private volatile HelloCookieManager helloCookieManager;
private StatusResponseManager statusResponseManager;
@ -117,6 +107,7 @@ public abstract class SSLContextImpl extends SSLContextSpi {
if (debug != null && Debug.isOn("sslctx")) {
System.out.println("done seeding SecureRandom");
}
isInitialized = true;
}
@ -242,13 +233,20 @@ public abstract class SSLContextImpl extends SSLContextSpi {
return ephemeralKeyManager;
}
// Used for DTLS in server mode only, see ServerHandshaker.
HelloCookieManager getHelloCookieManager() {
if (!isInitialized) {
throw new IllegalStateException("SSLContext is not initialized");
}
if (helloCookieManager == null) {
helloCookieManager = getHelloCookieManager(secureRandom);
if (helloCookieManager != null) {
return helloCookieManager;
}
synchronized (this) {
if (helloCookieManager == null) {
helloCookieManager = getHelloCookieManager(secureRandom);
}
}
return helloCookieManager;
@ -263,78 +261,34 @@ public abstract class SSLContextImpl extends SSLContextSpi {
return statusResponseManager;
}
abstract SSLParameters getDefaultServerSSLParams();
abstract SSLParameters getDefaultClientSSLParams();
abstract SSLParameters getSupportedSSLParams();
// Get supported ProtocolList.
ProtocolList getSuportedProtocolList() {
if (supportedProtocolList == null) {
supportedProtocolList =
new ProtocolList(getSupportedSSLParams().getProtocols());
}
abstract ProtocolList getSuportedProtocolList();
return supportedProtocolList;
}
// Get default ProtocolList for server mode.
abstract ProtocolList getServerDefaultProtocolList();
// Get default ProtocolList for client mode.
abstract ProtocolList getClientDefaultProtocolList();
// Get supported CipherSuiteList.
abstract CipherSuiteList getSupportedCipherSuiteList();
// Get default CipherSuiteList for server mode.
abstract CipherSuiteList getServerDefaultCipherSuiteList();
// Get default CipherSuiteList for client mode.
abstract CipherSuiteList getClientDefaultCipherSuiteList();
// Get default ProtocolList.
ProtocolList getDefaultProtocolList(boolean roleIsServer) {
if (roleIsServer) {
if (defaultServerProtocolList == null) {
defaultServerProtocolList = new ProtocolList(
getDefaultServerSSLParams().getProtocols());
}
return defaultServerProtocolList;
} else {
if (defaultClientProtocolList == null) {
defaultClientProtocolList = new ProtocolList(
getDefaultClientSSLParams().getProtocols());
}
return defaultClientProtocolList;
}
}
// Get supported CipherSuiteList.
CipherSuiteList getSupportedCipherSuiteList() {
// The maintenance of cipher suites needs to be synchronized.
synchronized (this) {
// Clear cache of available ciphersuites.
clearAvailableCache();
if (supportedCipherSuiteList == null) {
supportedCipherSuiteList = getApplicableCipherSuiteList(
getSuportedProtocolList(), false);
}
return supportedCipherSuiteList;
}
return roleIsServer ? getServerDefaultProtocolList()
: getClientDefaultProtocolList();
}
// Get default CipherSuiteList.
CipherSuiteList getDefaultCipherSuiteList(boolean roleIsServer) {
// The maintenance of cipher suites needs to be synchronized.
synchronized (this) {
// Clear cache of available ciphersuites.
clearAvailableCache();
if (roleIsServer) {
if (defaultServerCipherSuiteList == null) {
defaultServerCipherSuiteList = getApplicableCipherSuiteList(
getDefaultProtocolList(true), true);
}
return defaultServerCipherSuiteList;
} else {
if (defaultClientCipherSuiteList == null) {
defaultClientCipherSuiteList = getApplicableCipherSuiteList(
getDefaultProtocolList(false), true);
}
return defaultClientCipherSuiteList;
}
}
return roleIsServer ? getServerDefaultCipherSuiteList()
: getClientDefaultCipherSuiteList();
}
/**
@ -342,8 +296,8 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* protocols. See: SSLSocket/SSLEngine.setEnabledProtocols()
*/
boolean isDefaultProtocolList(ProtocolList protocols) {
return (protocols == defaultServerProtocolList) ||
(protocols == defaultClientProtocolList);
return (protocols == getServerDefaultProtocolList()) ||
(protocols == getClientDefaultProtocolList());
}
/**
@ -351,8 +305,8 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* protocols. See: SSLSocket/SSLEngine.setEnabledProtocols()
*/
boolean isDefaultCipherSuiteList(CipherSuiteList cipherSuites) {
return (cipherSuites == defaultClientCipherSuiteList) ||
(cipherSuites == defaultServerCipherSuiteList);
return (cipherSuites == getServerDefaultCipherSuiteList()) ||
(cipherSuites == getClientDefaultCipherSuiteList());
}
/*
@ -405,24 +359,6 @@ public abstract class SSLContextImpl extends SSLContextSpi {
return new CipherSuiteList(suites);
}
/**
* Clear cache of available ciphersuites. If we support all ciphers
* internally, there is no need to clear the cache and calling this
* method has no effect.
*
* Note that every call to clearAvailableCache() and the maintenance of
* cipher suites need to be synchronized with this instance.
*/
private void clearAvailableCache() {
if (CipherSuite.DYNAMIC_AVAILABILITY) {
supportedCipherSuiteList = null;
defaultServerCipherSuiteList = null;
defaultClientCipherSuiteList = null;
CipherSuite.BulkCipher.clearAvailableCache();
JsseJce.clearEcAvailable();
}
}
private static String[] getAvailableProtocols(
ProtocolVersion[] protocolCandidates) {
@ -479,31 +415,28 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* @see SSLContext
*/
private abstract static class AbstractTLSContext extends SSLContextImpl {
// parameters
private static final SSLParameters defaultServerSSLParams;
private static final SSLParameters supportedSSLParams;
private static final ProtocolList supportedProtocolList;
private static final ProtocolList serverDefaultProtocolList;
private static final CipherSuiteList supportedCipherSuiteList;
private static final CipherSuiteList serverDefaultCipherSuiteList;
static {
// supported SSL parameters
supportedSSLParams = new SSLParameters();
// candidates for available protocols
ProtocolVersion[] candidates;
if (SunJSSE.isFIPS()) {
supportedSSLParams.setProtocols(new String[] {
supportedProtocolList = new ProtocolList(new String[] {
ProtocolVersion.TLS10.name,
ProtocolVersion.TLS11.name,
ProtocolVersion.TLS12.name
});
candidates = new ProtocolVersion[] {
serverDefaultProtocolList = new ProtocolList(
getAvailableProtocols(new ProtocolVersion[] {
ProtocolVersion.TLS10,
ProtocolVersion.TLS11,
ProtocolVersion.TLS12
};
}));
} else {
supportedSSLParams.setProtocols(new String[] {
supportedProtocolList = new ProtocolList(new String[] {
ProtocolVersion.SSL20Hello.name,
ProtocolVersion.SSL30.name,
ProtocolVersion.TLS10.name,
@ -511,28 +444,40 @@ public abstract class SSLContextImpl extends SSLContextSpi {
ProtocolVersion.TLS12.name
});
candidates = new ProtocolVersion[] {
serverDefaultProtocolList = new ProtocolList(
getAvailableProtocols(new ProtocolVersion[] {
ProtocolVersion.SSL20Hello,
ProtocolVersion.SSL30,
ProtocolVersion.TLS10,
ProtocolVersion.TLS11,
ProtocolVersion.TLS12
};
}));
}
defaultServerSSLParams = new SSLParameters();
defaultServerSSLParams.setProtocols(
getAvailableProtocols(candidates));
supportedCipherSuiteList = getApplicableCipherSuiteList(
supportedProtocolList, false); // all supported
serverDefaultCipherSuiteList = getApplicableCipherSuiteList(
serverDefaultProtocolList, true); // enabled only
}
@Override
SSLParameters getDefaultServerSSLParams() {
return defaultServerSSLParams;
ProtocolList getSuportedProtocolList() {
return supportedProtocolList;
}
@Override
SSLParameters getSupportedSSLParams() {
return supportedSSLParams;
CipherSuiteList getSupportedCipherSuiteList() {
return supportedCipherSuiteList;
}
@Override
ProtocolList getServerDefaultProtocolList() {
return serverDefaultProtocolList;
}
@Override
CipherSuiteList getServerDefaultCipherSuiteList() {
return serverDefaultCipherSuiteList;
}
@Override
@ -552,30 +497,35 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* @see SSLContext
*/
public static final class TLS10Context extends AbstractTLSContext {
private static final SSLParameters defaultClientSSLParams;
private static final ProtocolList clientDefaultProtocolList;
private static final CipherSuiteList clientDefaultCipherSuiteList;
static {
// candidates for available protocols
ProtocolVersion[] candidates;
if (SunJSSE.isFIPS()) {
candidates = new ProtocolVersion[] {
clientDefaultProtocolList = new ProtocolList(
getAvailableProtocols(new ProtocolVersion[] {
ProtocolVersion.TLS10
};
}));
} else {
candidates = new ProtocolVersion[] {
clientDefaultProtocolList = new ProtocolList(
getAvailableProtocols(new ProtocolVersion[] {
ProtocolVersion.SSL30,
ProtocolVersion.TLS10
};
}));
}
defaultClientSSLParams = new SSLParameters();
defaultClientSSLParams.setProtocols(
getAvailableProtocols(candidates));
clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
clientDefaultProtocolList, true); // enabled only
}
@Override
SSLParameters getDefaultClientSSLParams() {
return defaultClientSSLParams;
ProtocolList getClientDefaultProtocolList() {
return clientDefaultProtocolList;
}
@Override
CipherSuiteList getClientDefaultCipherSuiteList() {
return clientDefaultCipherSuiteList;
}
}
@ -585,32 +535,37 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* @see SSLContext
*/
public static final class TLS11Context extends AbstractTLSContext {
private static final SSLParameters defaultClientSSLParams;
private static final ProtocolList clientDefaultProtocolList;
private static final CipherSuiteList clientDefaultCipherSuiteList;
static {
// candidates for available protocols
ProtocolVersion[] candidates;
if (SunJSSE.isFIPS()) {
candidates = new ProtocolVersion[] {
clientDefaultProtocolList = new ProtocolList(
getAvailableProtocols(new ProtocolVersion[] {
ProtocolVersion.TLS10,
ProtocolVersion.TLS11
};
}));
} else {
candidates = new ProtocolVersion[] {
clientDefaultProtocolList = new ProtocolList(
getAvailableProtocols(new ProtocolVersion[] {
ProtocolVersion.SSL30,
ProtocolVersion.TLS10,
ProtocolVersion.TLS11
};
}));
}
defaultClientSSLParams = new SSLParameters();
defaultClientSSLParams.setProtocols(
getAvailableProtocols(candidates));
clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
clientDefaultProtocolList, true); // enabled only
}
@Override
SSLParameters getDefaultClientSSLParams() {
return defaultClientSSLParams;
ProtocolList getClientDefaultProtocolList() {
return clientDefaultProtocolList;
}
@Override
CipherSuiteList getClientDefaultCipherSuiteList() {
return clientDefaultCipherSuiteList;
}
}
@ -620,34 +575,39 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* @see SSLContext
*/
public static final class TLS12Context extends AbstractTLSContext {
private static final SSLParameters defaultClientSSLParams;
private static final ProtocolList clientDefaultProtocolList;
private static final CipherSuiteList clientDefaultCipherSuiteList;
static {
// candidates for available protocols
ProtocolVersion[] candidates;
if (SunJSSE.isFIPS()) {
candidates = new ProtocolVersion[] {
clientDefaultProtocolList = new ProtocolList(
getAvailableProtocols(new ProtocolVersion[] {
ProtocolVersion.TLS10,
ProtocolVersion.TLS11,
ProtocolVersion.TLS12
};
}));
} else {
candidates = new ProtocolVersion[] {
clientDefaultProtocolList = new ProtocolList(
getAvailableProtocols(new ProtocolVersion[] {
ProtocolVersion.SSL30,
ProtocolVersion.TLS10,
ProtocolVersion.TLS11,
ProtocolVersion.TLS12
};
}));
}
defaultClientSSLParams = new SSLParameters();
defaultClientSSLParams.setProtocols(
getAvailableProtocols(candidates));
clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
clientDefaultProtocolList, true); // enabled only
}
@Override
SSLParameters getDefaultClientSSLParams() {
return defaultClientSSLParams;
ProtocolList getClientDefaultProtocolList() {
return clientDefaultProtocolList;
}
@Override
CipherSuiteList getClientDefaultCipherSuiteList() {
return clientDefaultCipherSuiteList;
}
}
@ -719,7 +679,9 @@ public abstract class SSLContextImpl extends SSLContextSpi {
*/
private static class CustomizedTLSContext extends AbstractTLSContext {
private static final SSLParameters defaultClientSSLParams;
private static final ProtocolList clientDefaultProtocolList;
private static final CipherSuiteList clientDefaultCipherSuiteList;
private static IllegalArgumentException reservedException = null;
// Don't want a java.lang.LinkageError for illegal system property.
@ -766,11 +728,13 @@ public abstract class SSLContextImpl extends SSLContextSpi {
candidates = customizedTLSProtocols.toArray(candidates);
}
defaultClientSSLParams = new SSLParameters();
defaultClientSSLParams.setProtocols(
clientDefaultProtocolList = new ProtocolList(
getAvailableProtocols(candidates));
clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
clientDefaultProtocolList, true); // enabled only
} else {
defaultClientSSLParams = null; // unlikely to be used
clientDefaultProtocolList = null; // unlikely to be used
clientDefaultCipherSuiteList = null; // unlikely to be used
}
}
@ -781,8 +745,13 @@ public abstract class SSLContextImpl extends SSLContextSpi {
}
@Override
SSLParameters getDefaultClientSSLParams() {
return defaultClientSSLParams;
ProtocolList getClientDefaultProtocolList() {
return clientDefaultProtocolList;
}
@Override
CipherSuiteList getClientDefaultCipherSuiteList() {
return clientDefaultCipherSuiteList;
}
}
@ -795,71 +764,53 @@ public abstract class SSLContextImpl extends SSLContextSpi {
// use the default constructor and methods
}
/*
* The SSLContext implementation for default "Default" algorithm
*
* @see SSLContext
*/
public static final class DefaultSSLContext extends CustomizedTLSContext {
// lazy initialization holder class idiom for static default parameters
//
// See Effective Java Second Edition: Item 71.
private static final class DefaultManagersHolder {
private static final String NONE = "NONE";
private static final String P11KEYSTORE = "PKCS11";
private static volatile SSLContextImpl defaultImpl;
private static final TrustManager[] trustManagers;
private static final KeyManager[] keyManagers;
private static TrustManager[] defaultTrustManagers;
private static KeyManager[] defaultKeyManagers;
static Exception reservedException = null;
public DefaultSSLContext() throws Exception {
static {
TrustManager[] tmMediator;
try {
super.engineInit(getDefaultKeyManager(),
getDefaultTrustManager(), null);
tmMediator = getTrustManagers();
} catch (Exception e) {
if (debug != null && Debug.isOn("defaultctx")) {
System.out.println("default context init failed: " + e);
reservedException = e;
tmMediator = new TrustManager[0];
}
trustManagers = tmMediator;
if (reservedException == null) {
KeyManager[] kmMediator;
try {
kmMediator = getKeyManagers();
} catch (Exception e) {
reservedException = e;
kmMediator = new KeyManager[0];
}
throw e;
}
if (defaultImpl == null) {
defaultImpl = this;
keyManagers = kmMediator;
} else {
keyManagers = new KeyManager[0];
}
}
@Override
protected void engineInit(KeyManager[] km, TrustManager[] tm,
SecureRandom sr) throws KeyManagementException {
throw new KeyManagementException
("Default SSLContext is initialized automatically");
}
static synchronized SSLContextImpl getDefaultImpl() throws Exception {
if (defaultImpl == null) {
new DefaultSSLContext();
}
return defaultImpl;
}
private static synchronized TrustManager[] getDefaultTrustManager()
throws Exception {
if (defaultTrustManagers != null) {
return defaultTrustManagers;
}
private static TrustManager[] getTrustManagers() throws Exception {
KeyStore ks =
TrustManagerFactoryImpl.getCacertsKeyStore("defaultctx");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
defaultTrustManagers = tmf.getTrustManagers();
return defaultTrustManagers;
return tmf.getTrustManagers();
}
private static synchronized KeyManager[] getDefaultKeyManager()
throws Exception {
if (defaultKeyManagers != null) {
return defaultKeyManagers;
}
private static KeyManager[] getKeyManagers() throws Exception {
final Map<String,String> props = new HashMap<>();
AccessController.doPrivileged(
@ -956,8 +907,71 @@ public abstract class SSLContextImpl extends SSLContextSpi {
kmf.init(ks, passwd);
}
defaultKeyManagers = kmf.getKeyManagers();
return defaultKeyManagers;
return kmf.getKeyManagers();
}
}
// lazy initialization holder class idiom for static default parameters
//
// See Effective Java Second Edition: Item 71.
private static final class DefaultSSLContextHolder {
private static final SSLContextImpl sslContext;
static Exception reservedException = null;
static {
SSLContextImpl mediator = null;
if (DefaultManagersHolder.reservedException != null) {
reservedException = DefaultManagersHolder.reservedException;
} else {
try {
mediator = new DefaultSSLContext();
} catch (Exception e) {
reservedException = e;
}
}
sslContext = mediator;
}
}
/*
* The SSLContext implementation for default "Default" algorithm
*
* @see SSLContext
*/
public static final class DefaultSSLContext extends CustomizedTLSContext {
// public constructor for SSLContext.getInstance("Default")
public DefaultSSLContext() throws Exception {
if (DefaultManagersHolder.reservedException != null) {
throw DefaultManagersHolder.reservedException;
}
try {
super.engineInit(DefaultManagersHolder.keyManagers,
DefaultManagersHolder.trustManagers, null);
} catch (Exception e) {
if (debug != null && Debug.isOn("defaultctx")) {
System.out.println("default context init failed: " + e);
}
throw e;
}
}
@Override
protected void engineInit(KeyManager[] km, TrustManager[] tm,
SecureRandom sr) throws KeyManagementException {
throw new KeyManagementException
("Default SSLContext is initialized automatically");
}
static SSLContextImpl getDefaultImpl() throws Exception {
if (DefaultSSLContextHolder.reservedException != null) {
throw DefaultSSLContextHolder.reservedException;
}
return DefaultSSLContextHolder.sslContext;
}
}
@ -971,39 +985,50 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* @see SSLContext
*/
private abstract static class AbstractDTLSContext extends SSLContextImpl {
// parameters
private static final SSLParameters defaultServerSSLParams;
private static final SSLParameters supportedSSLParams;
private static final ProtocolList supportedProtocolList;
private static final ProtocolList serverDefaultProtocolList;
private static final CipherSuiteList supportedCipherSuiteList;
private static final CipherSuiteList serverDefaultCipherSuiteList;
static {
// supported SSL parameters
supportedSSLParams = new SSLParameters();
// Both DTLSv1.0 and DTLSv1.2 can be used in FIPS mode.
supportedSSLParams.setProtocols(new String[] {
supportedProtocolList = new ProtocolList(new String[] {
ProtocolVersion.DTLS10.name,
ProtocolVersion.DTLS12.name
});
// candidates for available protocols
ProtocolVersion[] candidates = new ProtocolVersion[] {
// available protocols for server mode
serverDefaultProtocolList = new ProtocolList(
getAvailableProtocols(new ProtocolVersion[] {
ProtocolVersion.DTLS10,
ProtocolVersion.DTLS12
};
}));
defaultServerSSLParams = new SSLParameters();
defaultServerSSLParams.setProtocols(
getAvailableProtocols(candidates));
supportedCipherSuiteList = getApplicableCipherSuiteList(
supportedProtocolList, false); // all supported
serverDefaultCipherSuiteList = getApplicableCipherSuiteList(
serverDefaultProtocolList, true); // enabled only
}
@Override
SSLParameters getDefaultServerSSLParams() {
return defaultServerSSLParams;
ProtocolList getSuportedProtocolList() {
return supportedProtocolList;
}
@Override
SSLParameters getSupportedSSLParams() {
return supportedSSLParams;
CipherSuiteList getSupportedCipherSuiteList() {
return supportedCipherSuiteList;
}
@Override
ProtocolList getServerDefaultProtocolList() {
return serverDefaultProtocolList;
}
@Override
CipherSuiteList getServerDefaultCipherSuiteList() {
return serverDefaultCipherSuiteList;
}
@Override
@ -1028,22 +1053,28 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* @see SSLContext
*/
public static final class DTLS10Context extends AbstractDTLSContext {
private static final SSLParameters defaultClientSSLParams;
private static final ProtocolList clientDefaultProtocolList;
private static final CipherSuiteList clientDefaultCipherSuiteList;
static {
// candidates for available protocols
ProtocolVersion[] candidates = new ProtocolVersion[] {
// available protocols for client mode
clientDefaultProtocolList = new ProtocolList(
getAvailableProtocols(new ProtocolVersion[] {
ProtocolVersion.DTLS10
};
}));
defaultClientSSLParams = new SSLParameters();
defaultClientSSLParams.setProtocols(
getAvailableProtocols(candidates));
clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
clientDefaultProtocolList, true); // enabled only
}
@Override
SSLParameters getDefaultClientSSLParams() {
return defaultClientSSLParams;
ProtocolList getClientDefaultProtocolList() {
return clientDefaultProtocolList;
}
@Override
CipherSuiteList getClientDefaultCipherSuiteList() {
return clientDefaultCipherSuiteList;
}
}
@ -1053,23 +1084,29 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* @see SSLContext
*/
public static final class DTLS12Context extends AbstractDTLSContext {
private static final SSLParameters defaultClientSSLParams;
private static final ProtocolList clientDefaultProtocolList;
private static final CipherSuiteList clientDefaultCipherSuiteList;
static {
// candidates for available protocols
ProtocolVersion[] candidates = new ProtocolVersion[] {
// available protocols for client mode
clientDefaultProtocolList = new ProtocolList(
getAvailableProtocols(new ProtocolVersion[] {
ProtocolVersion.DTLS10,
ProtocolVersion.DTLS12
};
}));
defaultClientSSLParams = new SSLParameters();
defaultClientSSLParams.setProtocols(
getAvailableProtocols(candidates));
clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
clientDefaultProtocolList, true); // enabled only
}
@Override
SSLParameters getDefaultClientSSLParams() {
return defaultClientSSLParams;
ProtocolList getClientDefaultProtocolList() {
return clientDefaultProtocolList;
}
@Override
CipherSuiteList getClientDefaultCipherSuiteList() {
return clientDefaultCipherSuiteList;
}
}
@ -1079,7 +1116,9 @@ public abstract class SSLContextImpl extends SSLContextSpi {
* @see SSLContext
*/
private static class CustomizedDTLSContext extends AbstractDTLSContext {
private static final SSLParameters defaultClientSSLParams;
private static final ProtocolList clientDefaultProtocolList;
private static final CipherSuiteList clientDefaultCipherSuiteList;
private static IllegalArgumentException reservedException = null;
// Don't want a java.lang.LinkageError for illegal system property.
@ -1119,11 +1158,13 @@ public abstract class SSLContextImpl extends SSLContextSpi {
candidates = customizedDTLSProtocols.toArray(candidates);
}
defaultClientSSLParams = new SSLParameters();
defaultClientSSLParams.setProtocols(
clientDefaultProtocolList = new ProtocolList(
getAvailableProtocols(candidates));
clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
clientDefaultProtocolList, true); // enabled only
} else {
defaultClientSSLParams = null; // unlikely to be used
clientDefaultProtocolList = null; // unlikely to be used
clientDefaultCipherSuiteList = null; // unlikely to be used
}
}
@ -1134,8 +1175,13 @@ public abstract class SSLContextImpl extends SSLContextSpi {
}
@Override
SSLParameters getDefaultClientSSLParams() {
return defaultClientSSLParams;
ProtocolList getClientDefaultProtocolList() {
return clientDefaultProtocolList;
}
@Override
CipherSuiteList getClientDefaultCipherSuiteList() {
return clientDefaultCipherSuiteList;
}
}

View File

@ -130,7 +130,7 @@ final class SSLSessionImpl extends ExtendedSSLSession {
* also since counters make shorter debugging IDs than the big ones
* we use in the protocol for uniqueness-over-time.
*/
private static volatile int counter = 0;
private static volatile int counter;
/*
* Use of session caches is globally enabled/disabled.

View File

@ -1290,7 +1290,7 @@ public class X509CRLImpl extends X509CRL implements DerEncoder {
implements Comparable<X509IssuerSerial> {
final X500Principal issuer;
final BigInteger serial;
volatile int hashcode = 0;
volatile int hashcode;
/**
* Create an X509IssuerSerial.
@ -1358,13 +1358,16 @@ public class X509CRLImpl extends X509CRL implements DerEncoder {
* @return the hash code value
*/
public int hashCode() {
if (hashcode == 0) {
int result = 17;
result = 37*result + issuer.hashCode();
result = 37*result + serial.hashCode();
hashcode = result;
int h = hashcode;
if (h == 0) {
h = 17;
h = 37*h + issuer.hashCode();
h = 37*h + serial.hashCode();
if (h != 0) {
hashcode = h;
}
}
return hashcode;
return h;
}
@Override

View File

@ -25,13 +25,6 @@
package sun.util.calendar;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Properties;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@ -76,7 +69,7 @@ public abstract class CalendarSystem {
/////////////////////// Calendar Factory Methods /////////////////////////
private static volatile boolean initialized = false;
private static volatile boolean initialized;
// Map of calendar names and calendar class names
private static ConcurrentMap<String, String> names;

View File

@ -46,7 +46,7 @@ public final class BaseLocale {
private final String region;
private final String variant;
private volatile int hash = 0;
private volatile int hash;
// This method must be called only when creating the Locale.* constants.
private BaseLocale(String language, String region) {
@ -147,7 +147,9 @@ public final class BaseLocale {
h = 31 * h + script.hashCode();
h = 31 * h + region.hashCode();
h = 31 * h + variant.hashCode();
hash = h;
if (h != 0) {
hash = h;
}
}
return h;
}

View File

@ -114,20 +114,20 @@ public class JRELocaleProviderAdapter extends LocaleProviderAdapter implements R
}
}
private volatile BreakIteratorProvider breakIteratorProvider = null;
private volatile CollatorProvider collatorProvider = null;
private volatile DateFormatProvider dateFormatProvider = null;
private volatile DateFormatSymbolsProvider dateFormatSymbolsProvider = null;
private volatile DecimalFormatSymbolsProvider decimalFormatSymbolsProvider = null;
private volatile NumberFormatProvider numberFormatProvider = null;
private volatile BreakIteratorProvider breakIteratorProvider;
private volatile CollatorProvider collatorProvider;
private volatile DateFormatProvider dateFormatProvider;
private volatile DateFormatSymbolsProvider dateFormatSymbolsProvider;
private volatile DecimalFormatSymbolsProvider decimalFormatSymbolsProvider;
private volatile NumberFormatProvider numberFormatProvider;
private volatile CurrencyNameProvider currencyNameProvider = null;
private volatile LocaleNameProvider localeNameProvider = null;
private volatile TimeZoneNameProvider timeZoneNameProvider = null;
private volatile CalendarDataProvider calendarDataProvider = null;
private volatile CalendarNameProvider calendarNameProvider = null;
private volatile CurrencyNameProvider currencyNameProvider;
private volatile LocaleNameProvider localeNameProvider;
private volatile TimeZoneNameProvider timeZoneNameProvider;
private volatile CalendarDataProvider calendarDataProvider;
private volatile CalendarNameProvider calendarNameProvider;
private volatile CalendarProvider calendarProvider = null;
private volatile CalendarProvider calendarProvider;
/*
* Getter methods for java.text.spi.* providers

View File

@ -107,7 +107,7 @@ public abstract class LocaleProviderAdapter {
* Default fallback adapter type, which should return something meaningful in any case.
* This is either CLDR or FALLBACK.
*/
static volatile LocaleProviderAdapter.Type defaultLocaleProviderAdapter = null;
static volatile LocaleProviderAdapter.Type defaultLocaleProviderAdapter;
/**
* Adapter lookup cache.

View File

@ -164,6 +164,6 @@ public abstract class OpenListResourceBundle extends ResourceBundle {
return new HashSet<>();
}
private volatile Map<String, Object> lookup = null;
private volatile Map<String, Object> lookup;
private volatile Set<String> keyset;
}

View File

@ -47,7 +47,7 @@ class SinkChannelImpl
int fdVal;
// ID of native thread doing write, for signalling
private volatile long thread = 0;
private volatile long thread;
// Lock held by current reading thread
private final Object lock = new Object();

View File

@ -47,7 +47,7 @@ class SourceChannelImpl
int fdVal;
// ID of native thread doing read, for signalling
private volatile long thread = 0;
private volatile long thread;
// Lock held by current reading thread
private final Object lock = new Object();

View File

@ -52,7 +52,7 @@ class MimeTypesFileTypeDetector extends AbstractFileTypeDetector {
private Map<String,String> mimeTypeMap;
// set to true when file loaded
private volatile boolean loaded = false;
private volatile boolean loaded;
public MimeTypesFileTypeDetector(Path filePath) {
mimeTypesFile = filePath;

View File

@ -69,15 +69,16 @@ public abstract class UnixFileSystemProvider
private void checkUri(URI uri) {
if (!uri.getScheme().equalsIgnoreCase(getScheme()))
throw new IllegalArgumentException("URI does not match this provider");
if (uri.getAuthority() != null)
if (uri.getRawAuthority() != null)
throw new IllegalArgumentException("Authority component present");
if (uri.getPath() == null)
String path = uri.getPath();
if (path == null)
throw new IllegalArgumentException("Path component is undefined");
if (!uri.getPath().equals("/"))
if (!path.equals("/"))
throw new IllegalArgumentException("Path component should be '/'");
if (uri.getQuery() != null)
if (uri.getRawQuery() != null)
throw new IllegalArgumentException("Query component present");
if (uri.getFragment() != null)
if (uri.getRawFragment() != null)
throw new IllegalArgumentException("Fragment component present");
}

View File

@ -49,11 +49,11 @@ class UnixUriUtils {
String scheme = uri.getScheme();
if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
throw new IllegalArgumentException("URI scheme is not \"file\"");
if (uri.getAuthority() != null)
if (uri.getRawAuthority() != null)
throw new IllegalArgumentException("URI has an authority component");
if (uri.getFragment() != null)
if (uri.getRawFragment() != null)
throw new IllegalArgumentException("URI has a fragment component");
if (uri.getQuery() != null)
if (uri.getRawQuery() != null)
throw new IllegalArgumentException("URI has a query component");
// compatibility with java.io.File

View File

@ -119,7 +119,7 @@ final class WindowsSelectorImpl extends SelectorImpl {
// Lock for interrupt triggering and clearing
private final Object interruptLock = new Object();
private volatile boolean interruptTriggered = false;
private volatile boolean interruptTriggered;
WindowsSelectorImpl(SelectorProvider sp) throws IOException {
super(sp);

View File

@ -61,15 +61,16 @@ public class WindowsFileSystemProvider
private void checkUri(URI uri) {
if (!uri.getScheme().equalsIgnoreCase(getScheme()))
throw new IllegalArgumentException("URI does not match this provider");
if (uri.getAuthority() != null)
if (uri.getRawAuthority() != null)
throw new IllegalArgumentException("Authority component present");
if (uri.getPath() == null)
String path = uri.getPath();
if (path == null)
throw new IllegalArgumentException("Path component is undefined");
if (!uri.getPath().equals("/"))
if (!path.equals("/"))
throw new IllegalArgumentException("Path component should be '/'");
if (uri.getQuery() != null)
if (uri.getRawQuery() != null)
throw new IllegalArgumentException("Query component present");
if (uri.getFragment() != null)
if (uri.getRawFragment() != null)
throw new IllegalArgumentException("Fragment component present");
}

View File

@ -123,16 +123,16 @@ class WindowsUriSupport {
String scheme = uri.getScheme();
if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
throw new IllegalArgumentException("URI scheme is not \"file\"");
if (uri.getFragment() != null)
if (uri.getRawFragment() != null)
throw new IllegalArgumentException("URI has a fragment component");
if (uri.getQuery() != null)
if (uri.getRawQuery() != null)
throw new IllegalArgumentException("URI has a query component");
String path = uri.getPath();
if (path.equals(""))
throw new IllegalArgumentException("URI path component is empty");
// UNC
String auth = uri.getAuthority();
String auth = uri.getRawAuthority();
if (auth != null && !auth.equals("")) {
String host = uri.getHost();
if (host == null)

View File

@ -289,6 +289,8 @@ public class DataFlavor implements Externalizable, Cloneable {
* representationClass = String
* mimeType = "text/html"
* </pre>
*
* @since 1.8
*/
public static DataFlavor selectionHtmlFlavor = initHtmlDataFlavor("selection");
@ -301,6 +303,8 @@ public class DataFlavor implements Externalizable, Cloneable {
* representationClass = String
* mimeType = "text/html"
* </pre>
*
* @since 1.8
*/
public static DataFlavor fragmentHtmlFlavor = initHtmlDataFlavor("fragment");
@ -314,6 +318,8 @@ public class DataFlavor implements Externalizable, Cloneable {
* representationClass = String
* mimeType = "text/html"
* </pre>
*
* @since 1.8
*/
public static DataFlavor allHtmlFlavor = initHtmlDataFlavor("all");

View File

@ -24,6 +24,7 @@
*/
#import <JavaNativeFoundation/JavaNativeFoundation.h>
#include <Carbon/Carbon.h>
#import "CMenuItem.h"
#import "CMenu.h"
@ -40,7 +41,7 @@
@implementation CMenuItem
- (id) initWithPeer:(jobject)peer asSeparator: (NSNumber *) asSeparator{
AWT_ASSERT_APPKIT_THREAD;
AWT_ASSERT_APPKIT_THREAD;
self = [super initWithPeer:peer];
if (self) {
if ([asSeparator boolValue]) {
@ -63,13 +64,48 @@ AWT_ASSERT_APPKIT_THREAD;
- (BOOL) worksWhenModal {
return YES;
}
// This is a method written using Carbon framework methods to remove
// All modifiers including "Shift" modifier.
// Example 1: Shortcut set is "Command Shift m" returns "m"
// Example 2: Shortcut set is "Command m" returns "m"
// Example 3: Shortcut set is "Alt Shift ," returns ","
CFStringRef createStringForKey(CGKeyCode keyCode)
{
TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
// currentKeyboard now contains the current input source
CFDataRef layoutData =
TISGetInputSourceProperty(currentKeyboard,
kTISPropertyUnicodeKeyLayoutData);
// the UNICODE keyLayout is fetched from currentKeyboard in layoutData
const UCKeyboardLayout *keyboardLayout =
(const UCKeyboardLayout *)CFDataGetBytePtr(layoutData);
// A read-only data pointer is fetched from layoutData
UInt32 keysDown = 0;
UniChar chars[4];
UniCharCount realLength;
UCKeyTranslate(keyboardLayout,
keyCode,
kUCKeyActionDisplay,
0,
LMGetKbdType(),
kUCKeyTranslateNoDeadKeysBit,
&keysDown,
sizeof(chars) / sizeof(chars[0]),
&realLength,
chars);
CFRelease(currentKeyboard);
// Converts keyCode, modifier and dead-key state into UNICODE characters
return CFStringCreateWithCharacters(kCFAllocatorDefault, chars, 1);
}
// Events
- (void)handleAction:(NSMenuItem *)sender {
AWT_ASSERT_APPKIT_THREAD;
AWT_ASSERT_APPKIT_THREAD;
JNIEnv *env = [ThreadUtilities getJNIEnv];
JNF_COCOA_ENTER(env);
JNF_COCOA_ENTER(env);
// If we are called as a result of user pressing a shortcut, do nothing,
// because AVTView has already sent corresponding key event to the Java
// layer from performKeyEquivalent.
@ -82,31 +118,37 @@ JNF_COCOA_ENTER(env);
NSEvent *currEvent = [[NSApplication sharedApplication] currentEvent];
if ([currEvent type] == NSKeyDown) {
NSString *menuKey = [sender keyEquivalent];
NSString *eventKey = [currEvent charactersIgnoringModifiers];
// Apple uses characters from private Unicode range for some of the
// keys, so we need to do the same translation here that we do
// for the regular key down events
if ([eventKey length] == 1) {
unichar origChar = [eventKey characterAtIndex:0];
unichar newChar = NsCharToJavaChar(origChar, 0);
if (newChar == java_awt_event_KeyEvent_CHAR_UNDEFINED) {
newChar = origChar;
}
eventKey = [NSString stringWithCharacters: &newChar length: 1];
}
// If shortcut is "Command Shift ," the menuKey gets the value ","
// But [currEvent charactersIgnoringModifiers]; returns "<" and not ","
// because the charactersIgnoreingModifiers does not ignore "Shift"
// So a shortcut like "Command Shift m" will return "M" where as the
// MenuKey will have the value "m". To remove this issue the below
// createStringForKey is used.
NSString *eventKey = createStringForKey([currEvent keyCode]);
// Apple uses characters from private Unicode range for some of the
// keys, so we need to do the same translation here that we do
// for the regular key down events
if ([eventKey length] == 1) {
unichar origChar = [eventKey characterAtIndex:0];
unichar newChar = NsCharToJavaChar(origChar, 0);
if (newChar == java_awt_event_KeyEvent_CHAR_UNDEFINED) {
newChar = origChar;
}
eventKey = [NSString stringWithCharacters: &newChar length: 1];
}
NSWindow *keyWindow = [NSApp keyWindow];
if ([menuKey isEqualToString:eventKey] && keyWindow != nil) {
return;
}
}
if (fIsCheckbox) {
static JNF_CLASS_CACHE(jc_CCheckboxMenuItem, "sun/lwawt/macosx/CCheckboxMenuItem");
static JNF_MEMBER_CACHE(jm_ckHandleAction, jc_CCheckboxMenuItem, "handleAction", "(Z)V");
// Send the opposite of what's currently checked -- the action
// indicates what state we're going to.
NSInteger state = [sender state];
@ -115,26 +157,26 @@ JNF_COCOA_ENTER(env);
} else {
static JNF_CLASS_CACHE(jc_CMenuItem, "sun/lwawt/macosx/CMenuItem");
static JNF_MEMBER_CACHE(jm_handleAction, jc_CMenuItem, "handleAction", "(JI)V"); // AWT_THREADING Safe (event)
NSUInteger modifiers = [currEvent modifierFlags];
jint javaModifiers = NsKeyModifiersToJavaModifiers(modifiers, NO);
JNFCallVoidMethod(env, fPeer, jm_handleAction, UTC(currEvent), javaModifiers); // AWT_THREADING Safe (event)
}
JNF_COCOA_EXIT(env);
JNF_COCOA_EXIT(env);
}
- (void) setJavaLabel:(NSString *)theLabel shortcut:(NSString *)theKeyEquivalent modifierMask:(jint)modifiers {
NSUInteger modifierMask = 0;
if (![theKeyEquivalent isEqualToString:@""]) {
// Force the key equivalent to lower case if not using the shift key.
// Otherwise AppKit will draw a Shift glyph in the menu.
if ((modifiers & java_awt_event_KeyEvent_SHIFT_MASK) == 0) {
theKeyEquivalent = [theKeyEquivalent lowercaseString];
}
// Hack for the question mark -- SHIFT and / means use the question mark.
if ((modifiers & java_awt_event_KeyEvent_SHIFT_MASK) != 0 &&
[theKeyEquivalent isEqualToString:@"/"])
@ -142,10 +184,10 @@ JNF_COCOA_EXIT(env);
theKeyEquivalent = @"?";
modifiers &= ~java_awt_event_KeyEvent_SHIFT_MASK;
}
modifierMask = JavaModifiersToNsKeyModifiers(modifiers, NO);
}
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
[fMenuItem setKeyEquivalent:theKeyEquivalent];
[fMenuItem setKeyEquivalentModifierMask:modifierMask];
@ -154,14 +196,14 @@ JNF_COCOA_EXIT(env);
}
- (void) setJavaImage:(NSImage *)theImage {
[ThreadUtilities performOnMainThreadWaiting:NO block:^(){
[fMenuItem setImage:theImage];
}];
}
- (void) setJavaToolTipText:(NSString *)theText {
[ThreadUtilities performOnMainThreadWaiting:NO block:^(){
[fMenuItem setToolTip:theText];
}];
@ -169,11 +211,11 @@ JNF_COCOA_EXIT(env);
- (void)setJavaEnabled:(BOOL) enabled {
[ThreadUtilities performOnMainThreadWaiting:NO block:^(){
@synchronized(self) {
fIsEnabled = enabled;
// Warning: This won't work if the parent menu is disabled.
// See [CMenu syncFromJava]. We still need to call it here so
// the NSMenuItem itself gets properly updated.
@ -183,7 +225,7 @@ JNF_COCOA_EXIT(env);
}
- (BOOL)isEnabled {
BOOL enabled = NO;
@synchronized(self) {
enabled = fIsEnabled;
@ -193,7 +235,7 @@ JNF_COCOA_EXIT(env);
- (void)setJavaState:(BOOL)newState {
[ThreadUtilities performOnMainThreadWaiting:NO block:^(){
[fMenuItem setState:(newState ? NSOnState : NSOffState)];
}];
@ -207,7 +249,7 @@ JNF_COCOA_EXIT(env);
- (void)dealloc {
[fMenuItem release];
fMenuItem = nil;
[super dealloc];
}
@ -240,7 +282,7 @@ JNF_COCOA_EXIT(env);
/** Convert a Java keycode for SetMenuItemCmd */
static unichar AWTKeyToMacShortcut(jint awtKey, BOOL doShift) {
unichar macKey = 0;
if ((awtKey >= java_awt_event_KeyEvent_VK_0 && awtKey <= java_awt_event_KeyEvent_VK_9) ||
(awtKey >= java_awt_event_KeyEvent_VK_A && awtKey <= java_awt_event_KeyEvent_VK_Z))
{
@ -255,68 +297,68 @@ static unichar AWTKeyToMacShortcut(jint awtKey, BOOL doShift) {
} else {
// Special characters
switch (awtKey) {
case java_awt_event_KeyEvent_VK_BACK_QUOTE : macKey = '`'; break;
case java_awt_event_KeyEvent_VK_QUOTE : macKey = '\''; break;
case java_awt_event_KeyEvent_VK_ESCAPE : macKey = 0x1B; break;
case java_awt_event_KeyEvent_VK_SPACE : macKey = ' '; break;
case java_awt_event_KeyEvent_VK_PAGE_UP : macKey = NSPageUpFunctionKey; break;
case java_awt_event_KeyEvent_VK_PAGE_DOWN : macKey = NSPageDownFunctionKey; break;
case java_awt_event_KeyEvent_VK_END : macKey = NSEndFunctionKey; break;
case java_awt_event_KeyEvent_VK_HOME : macKey = NSHomeFunctionKey; break;
case java_awt_event_KeyEvent_VK_LEFT : macKey = NSLeftArrowFunctionKey; break;
case java_awt_event_KeyEvent_VK_UP : macKey = NSUpArrowFunctionKey; break;
case java_awt_event_KeyEvent_VK_RIGHT : macKey = NSRightArrowFunctionKey; break;
case java_awt_event_KeyEvent_VK_DOWN : macKey = NSDownArrowFunctionKey; break;
case java_awt_event_KeyEvent_VK_COMMA : macKey = ','; break;
// Mac OS doesn't distinguish between the two '-' keys...
case java_awt_event_KeyEvent_VK_MINUS :
case java_awt_event_KeyEvent_VK_SUBTRACT : macKey = '-'; break;
// or the two '.' keys...
case java_awt_event_KeyEvent_VK_DECIMAL :
case java_awt_event_KeyEvent_VK_PERIOD : macKey = '.'; break;
// or the two '/' keys.
case java_awt_event_KeyEvent_VK_DIVIDE :
case java_awt_event_KeyEvent_VK_SLASH : macKey = '/'; break;
case java_awt_event_KeyEvent_VK_SEMICOLON : macKey = ';'; break;
case java_awt_event_KeyEvent_VK_EQUALS : macKey = '='; break;
case java_awt_event_KeyEvent_VK_OPEN_BRACKET : macKey = '['; break;
case java_awt_event_KeyEvent_VK_BACK_SLASH : macKey = '\\'; break;
case java_awt_event_KeyEvent_VK_CLOSE_BRACKET : macKey = ']'; break;
case java_awt_event_KeyEvent_VK_MULTIPLY : macKey = '*'; break;
case java_awt_event_KeyEvent_VK_ADD : macKey = '+'; break;
case java_awt_event_KeyEvent_VK_HELP : macKey = NSHelpFunctionKey; break;
case java_awt_event_KeyEvent_VK_TAB : macKey = NSTabCharacter; break;
case java_awt_event_KeyEvent_VK_ENTER : macKey = NSNewlineCharacter; break;
case java_awt_event_KeyEvent_VK_BACK_SPACE : macKey = NSBackspaceCharacter; break;
case java_awt_event_KeyEvent_VK_DELETE : macKey = NSDeleteCharacter; break;
case java_awt_event_KeyEvent_VK_CLEAR : macKey = NSClearDisplayFunctionKey; break;
case java_awt_event_KeyEvent_VK_AMPERSAND : macKey = '&'; break;
case java_awt_event_KeyEvent_VK_ASTERISK : macKey = '*'; break;
case java_awt_event_KeyEvent_VK_QUOTEDBL : macKey = '\"'; break;
case java_awt_event_KeyEvent_VK_LESS : macKey = '<'; break;
case java_awt_event_KeyEvent_VK_GREATER : macKey = '>'; break;
case java_awt_event_KeyEvent_VK_BRACELEFT : macKey = '{'; break;
case java_awt_event_KeyEvent_VK_BRACERIGHT : macKey = '}'; break;
case java_awt_event_KeyEvent_VK_AT : macKey = '@'; break;
case java_awt_event_KeyEvent_VK_COLON : macKey = ':'; break;
case java_awt_event_KeyEvent_VK_CIRCUMFLEX : macKey = '^'; break;
case java_awt_event_KeyEvent_VK_DOLLAR : macKey = '$'; break;
case java_awt_event_KeyEvent_VK_EXCLAMATION_MARK : macKey = '!'; break;
case java_awt_event_KeyEvent_VK_LEFT_PARENTHESIS : macKey = '('; break;
case java_awt_event_KeyEvent_VK_NUMBER_SIGN : macKey = '#'; break;
case java_awt_event_KeyEvent_VK_PLUS : macKey = '+'; break;
case java_awt_event_KeyEvent_VK_RIGHT_PARENTHESIS: macKey = ')'; break;
case java_awt_event_KeyEvent_VK_UNDERSCORE : macKey = '_'; break;
case java_awt_event_KeyEvent_VK_BACK_QUOTE : macKey = '`'; break;
case java_awt_event_KeyEvent_VK_QUOTE : macKey = '\''; break;
case java_awt_event_KeyEvent_VK_ESCAPE : macKey = 0x1B; break;
case java_awt_event_KeyEvent_VK_SPACE : macKey = ' '; break;
case java_awt_event_KeyEvent_VK_PAGE_UP : macKey = NSPageUpFunctionKey; break;
case java_awt_event_KeyEvent_VK_PAGE_DOWN : macKey = NSPageDownFunctionKey; break;
case java_awt_event_KeyEvent_VK_END : macKey = NSEndFunctionKey; break;
case java_awt_event_KeyEvent_VK_HOME : macKey = NSHomeFunctionKey; break;
case java_awt_event_KeyEvent_VK_LEFT : macKey = NSLeftArrowFunctionKey; break;
case java_awt_event_KeyEvent_VK_UP : macKey = NSUpArrowFunctionKey; break;
case java_awt_event_KeyEvent_VK_RIGHT : macKey = NSRightArrowFunctionKey; break;
case java_awt_event_KeyEvent_VK_DOWN : macKey = NSDownArrowFunctionKey; break;
case java_awt_event_KeyEvent_VK_COMMA : macKey = ','; break;
// Mac OS doesn't distinguish between the two '-' keys...
case java_awt_event_KeyEvent_VK_MINUS :
case java_awt_event_KeyEvent_VK_SUBTRACT : macKey = '-'; break;
// or the two '.' keys...
case java_awt_event_KeyEvent_VK_DECIMAL :
case java_awt_event_KeyEvent_VK_PERIOD : macKey = '.'; break;
// or the two '/' keys.
case java_awt_event_KeyEvent_VK_DIVIDE :
case java_awt_event_KeyEvent_VK_SLASH : macKey = '/'; break;
case java_awt_event_KeyEvent_VK_SEMICOLON : macKey = ';'; break;
case java_awt_event_KeyEvent_VK_EQUALS : macKey = '='; break;
case java_awt_event_KeyEvent_VK_OPEN_BRACKET : macKey = '['; break;
case java_awt_event_KeyEvent_VK_BACK_SLASH : macKey = '\\'; break;
case java_awt_event_KeyEvent_VK_CLOSE_BRACKET : macKey = ']'; break;
case java_awt_event_KeyEvent_VK_MULTIPLY : macKey = '*'; break;
case java_awt_event_KeyEvent_VK_ADD : macKey = '+'; break;
case java_awt_event_KeyEvent_VK_HELP : macKey = NSHelpFunctionKey; break;
case java_awt_event_KeyEvent_VK_TAB : macKey = NSTabCharacter; break;
case java_awt_event_KeyEvent_VK_ENTER : macKey = NSNewlineCharacter; break;
case java_awt_event_KeyEvent_VK_BACK_SPACE : macKey = NSBackspaceCharacter; break;
case java_awt_event_KeyEvent_VK_DELETE : macKey = NSDeleteCharacter; break;
case java_awt_event_KeyEvent_VK_CLEAR : macKey = NSClearDisplayFunctionKey; break;
case java_awt_event_KeyEvent_VK_AMPERSAND : macKey = '&'; break;
case java_awt_event_KeyEvent_VK_ASTERISK : macKey = '*'; break;
case java_awt_event_KeyEvent_VK_QUOTEDBL : macKey = '\"'; break;
case java_awt_event_KeyEvent_VK_LESS : macKey = '<'; break;
case java_awt_event_KeyEvent_VK_GREATER : macKey = '>'; break;
case java_awt_event_KeyEvent_VK_BRACELEFT : macKey = '{'; break;
case java_awt_event_KeyEvent_VK_BRACERIGHT : macKey = '}'; break;
case java_awt_event_KeyEvent_VK_AT : macKey = '@'; break;
case java_awt_event_KeyEvent_VK_COLON : macKey = ':'; break;
case java_awt_event_KeyEvent_VK_CIRCUMFLEX : macKey = '^'; break;
case java_awt_event_KeyEvent_VK_DOLLAR : macKey = '$'; break;
case java_awt_event_KeyEvent_VK_EXCLAMATION_MARK : macKey = '!'; break;
case java_awt_event_KeyEvent_VK_LEFT_PARENTHESIS : macKey = '('; break;
case java_awt_event_KeyEvent_VK_NUMBER_SIGN : macKey = '#'; break;
case java_awt_event_KeyEvent_VK_PLUS : macKey = '+'; break;
case java_awt_event_KeyEvent_VK_RIGHT_PARENTHESIS: macKey = ')'; break;
case java_awt_event_KeyEvent_VK_UNDERSCORE : macKey = '_'; break;
}
}
return macKey;
@ -330,27 +372,27 @@ static unichar AWTKeyToMacShortcut(jint awtKey, BOOL doShift) {
JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CMenuItem_nativeSetLabel
(JNIEnv *env, jobject peer,
jlong menuItemObj, jstring label,
jchar shortcutKey, jint shortcutKeyCode, jint mods)
jlong menuItemObj, jstring label,
jchar shortcutKey, jint shortcutKeyCode, jint mods)
{
JNF_COCOA_ENTER(env);
JNF_COCOA_ENTER(env);
NSString *theLabel = JNFJavaToNSString(env, label);
NSString *theKeyEquivalent = nil;
unichar macKey = shortcutKey;
if (macKey == 0) {
macKey = AWTKeyToMacShortcut(shortcutKeyCode, (mods & java_awt_event_KeyEvent_SHIFT_MASK) != 0);
}
if (macKey != 0) {
unichar equivalent[1] = {macKey};
theKeyEquivalent = [NSString stringWithCharacters:equivalent length:1];
} else {
theKeyEquivalent = @"";
}
[((CMenuItem *)jlong_to_ptr(menuItemObj)) setJavaLabel:theLabel shortcut:theKeyEquivalent modifierMask:mods];
JNF_COCOA_EXIT(env);
JNF_COCOA_EXIT(env);
}
/*
@ -362,10 +404,10 @@ JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CMenuItem_nativeSetTooltip
(JNIEnv *env, jobject peer, jlong menuItemObj, jstring tooltip)
{
JNF_COCOA_ENTER(env);
JNF_COCOA_ENTER(env);
NSString *theTooltip = JNFJavaToNSString(env, tooltip);
[((CMenuItem *)jlong_to_ptr(menuItemObj)) setJavaToolTipText:theTooltip];
JNF_COCOA_EXIT(env);
JNF_COCOA_EXIT(env);
}
/*
@ -377,9 +419,9 @@ JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CMenuItem_nativeSetImage
(JNIEnv *env, jobject peer, jlong menuItemObj, jlong image)
{
JNF_COCOA_ENTER(env);
JNF_COCOA_ENTER(env);
[((CMenuItem *)jlong_to_ptr(menuItemObj)) setJavaImage:(NSImage*)jlong_to_ptr(image)];
JNF_COCOA_EXIT(env);
JNF_COCOA_EXIT(env);
}
/*
@ -389,38 +431,38 @@ JNF_COCOA_EXIT(env);
*/
JNIEXPORT jlong JNICALL
Java_sun_lwawt_macosx_CMenuItem_nativeCreate
(JNIEnv *env, jobject peer, jlong parentCMenuObj, jboolean isSeparator)
(JNIEnv *env, jobject peer, jlong parentCMenuObj, jboolean isSeparator)
{
CMenuItem *aCMenuItem = nil;
CMenu *parentCMenu = (CMenu *)jlong_to_ptr(parentCMenuObj);
JNF_COCOA_ENTER(env);
JNF_COCOA_ENTER(env);
jobject cPeerObjGlobal = (*env)->NewGlobalRef(env, peer);
NSMutableArray *args = nil;
// Create a new item....
if (isSeparator == JNI_TRUE) {
args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], [NSNumber numberWithBool:YES], nil];
} else {
args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], [NSNumber numberWithBool:NO], nil];
}
[ThreadUtilities performOnMainThread:@selector(_createMenuItem_OnAppKitThread:) on:[CMenuItem alloc] withObject:args waitUntilDone:YES];
aCMenuItem = (CMenuItem *)[args objectAtIndex: 0];
if (aCMenuItem == nil) {
return 0L;
}
// and add it to the parent item.
[parentCMenu addJavaMenuItem: aCMenuItem];
// setLabel will be called after creation completes.
JNF_COCOA_EXIT(env);
JNF_COCOA_EXIT(env);
return ptr_to_jlong(aCMenuItem);
}
@ -433,10 +475,10 @@ JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CMenuItem_nativeSetEnabled
(JNIEnv *env, jobject peer, jlong menuItemObj, jboolean enable)
{
JNF_COCOA_ENTER(env);
JNF_COCOA_ENTER(env);
CMenuItem *item = (CMenuItem *)jlong_to_ptr(menuItemObj);
[item setJavaEnabled: (enable == JNI_TRUE)];
JNF_COCOA_EXIT(env);
JNF_COCOA_EXIT(env);
}
/*
@ -448,10 +490,10 @@ JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CCheckboxMenuItem_nativeSetState
(JNIEnv *env, jobject peer, jlong menuItemObj, jboolean state)
{
JNF_COCOA_ENTER(env);
JNF_COCOA_ENTER(env);
CMenuItem *item = (CMenuItem *)jlong_to_ptr(menuItemObj);
[item setJavaState: (state == JNI_TRUE)];
JNF_COCOA_EXIT(env);
JNF_COCOA_EXIT(env);
}
/*
@ -463,8 +505,8 @@ JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CCheckboxMenuItem_nativeSetIsCheckbox
(JNIEnv *env, jobject peer, jlong menuItemObj)
{
JNF_COCOA_ENTER(env);
JNF_COCOA_ENTER(env);
CMenuItem *item = (CMenuItem *)jlong_to_ptr(menuItemObj);
[item setIsCheckbox];
JNF_COCOA_EXIT(env);
JNF_COCOA_EXIT(env);
}

View File

@ -874,13 +874,13 @@ public class JPEGMetadata extends IIOMetadata implements Cloneable {
return chroma;
}
boolean idsAreJFIF = true;
boolean idsAreJFIF = false;
for (int i = 0; i < sof.componentSpecs.length; i++) {
int id = sof.componentSpecs[i].componentId;
if ((id < 1) || (id >= sof.componentSpecs.length)) {
idsAreJFIF = false;
}
int cid0 = sof.componentSpecs[0].componentId;
int cid1 = sof.componentSpecs[1].componentId;
int cid2 = sof.componentSpecs[2].componentId;
if ((cid0 == 1) && (cid1 == 2) && (cid2 == 3)) {
idsAreJFIF = true;
}
if (idsAreJFIF) {

View File

@ -193,7 +193,17 @@ final class IDATOutputStream extends ImageOutputStreamImpl {
// Return to end of chunk and flush to minimize buffering
stream.seek(pos);
stream.flushBefore(pos);
try {
stream.flushBefore(pos);
} catch (IOException e) {
/*
* If flushBefore() fails we try to access startPos in finally
* block of write_IDAT(). We should update startPos to avoid
* IndexOutOfBoundException while seek() is happening.
*/
this.startPos = stream.getStreamPosition();
throw e;
}
}
public int read() throws IOException {

View File

@ -472,6 +472,14 @@ public class TIFFIFD extends TIFFDirectory {
// Read tag number, value type, and value count.
int tagNumber = stream.readUnsignedShort();
int type = stream.readUnsignedShort();
int sizeOfType;
try {
sizeOfType = TIFFTag.getSizeOfType(type);
} catch (IllegalArgumentException ignored) {
// Continue with the next IFD entry.
stream.skipBytes(4);
continue;
}
int count = (int)stream.readUnsignedInt();
// Get the associated TIFFTag.
@ -510,14 +518,14 @@ public class TIFFIFD extends TIFFDirectory {
}
}
int size = count*TIFFTag.getSizeOfType(type);
int size = count*sizeOfType;
if (size > 4 || tag.isIFDPointer()) {
// The IFD entry value is a pointer to the actual field value.
long offset = stream.readUnsignedInt();
// Check whether the the field value is within the stream.
if (haveStreamLength && offset + size > streamLength) {
throw new IIOException("Field data is past end-of-stream");
continue;
}
// Add a TIFFIFDEntry as a placeholder. This avoids a mark,

View File

@ -205,6 +205,10 @@ public class TIFFImageWriter extends ImageWriter {
// Next available space.
private long nextSpace = 0L;
private long prevStreamPosition;
private long prevHeaderPosition;
private long prevNextSpace;
// Whether a sequence is being written.
private boolean isWritingSequence = false;
private boolean isInsertingEmpty = false;
@ -2300,7 +2304,14 @@ public class TIFFImageWriter extends ImageWriter {
public void write(IIOMetadata sm,
IIOImage iioimage,
ImageWriteParam p) throws IOException {
if (stream == null) {
throw new IllegalStateException("output == null!");
}
markPositions();
write(sm, iioimage, p, true, true);
if (abortRequested()) {
resetPositions();
}
}
private void writeHeader() throws IOException {
@ -2333,7 +2344,7 @@ public class TIFFImageWriter extends ImageWriter {
throw new IllegalStateException("output == null!");
}
if (iioimage == null) {
throw new NullPointerException("image == null!");
throw new IllegalArgumentException("image == null!");
}
if(iioimage.hasRaster() && !canWriteRasters()) {
throw new UnsupportedOperationException
@ -2767,7 +2778,7 @@ public class TIFFImageWriter extends ImageWriter {
throw new IllegalStateException("Output not set!");
}
if (image == null) {
throw new NullPointerException("image == null!");
throw new IllegalArgumentException("image == null!");
}
// Locate the position of the old IFD (ifd) and the location
@ -2779,9 +2790,16 @@ public class TIFFImageWriter extends ImageWriter {
// imageIndex is < -1 or is too big thereby satisfying the spec.
locateIFD(imageIndex, ifdpos, ifd);
markPositions();
// Seek to the position containing the pointer to the old IFD.
stream.seek(ifdpos[0]);
// Save the previous pointer value in case of abort.
stream.mark();
long prevPointerValue = stream.readUnsignedInt();
stream.reset();
// Update next space pointer in anticipation of next write.
if(ifdpos[0] + 4 > nextSpace) {
nextSpace = ifdpos[0] + 4;
@ -2805,6 +2823,12 @@ public class TIFFImageWriter extends ImageWriter {
// Update the new IFD to point to the old IFD.
stream.writeInt((int)ifd[0]);
// Don't need to update nextSpace here as already done in write().
if (abortRequested()) {
stream.seek(ifdpos[0]);
stream.writeInt((int)prevPointerValue);
resetPositions();
}
}
// ----- BEGIN insert/writeEmpty methods -----
@ -2834,7 +2858,7 @@ public class TIFFImageWriter extends ImageWriter {
}
if(imageType == null) {
throw new NullPointerException("imageType == null!");
throw new IllegalArgumentException("imageType == null!");
}
if(width < 1 || height < 1) {
@ -2891,6 +2915,10 @@ public class TIFFImageWriter extends ImageWriter {
IIOMetadata imageMetadata,
List<? extends BufferedImage> thumbnails,
ImageWriteParam param) throws IOException {
if (stream == null) {
throw new IllegalStateException("output == null!");
}
checkParamsEmpty(imageType, width, height, thumbnails);
this.isWritingEmpty = true;
@ -2901,8 +2929,12 @@ public class TIFFImageWriter extends ImageWriter {
0, 0, emptySM.getWidth(), emptySM.getHeight(),
emptySM, imageType.getColorModel());
markPositions();
write(streamMetadata, new IIOImage(emptyImage, null, imageMetadata),
param, true, false);
if (abortRequested()) {
resetPositions();
}
}
public void endInsertEmpty() throws IOException {
@ -3015,7 +3047,7 @@ public class TIFFImageWriter extends ImageWriter {
throw new IllegalStateException("Output not set!");
}
if (region == null) {
throw new NullPointerException("region == null!");
throw new IllegalArgumentException("region == null!");
}
if (region.getWidth() < 1) {
throw new IllegalArgumentException("region.getWidth() < 1!");
@ -3200,7 +3232,7 @@ public class TIFFImageWriter extends ImageWriter {
}
if (image == null) {
throw new NullPointerException("image == null!");
throw new IllegalArgumentException("image == null!");
}
if (!inReplacePixelsNest) {
@ -3559,6 +3591,20 @@ public class TIFFImageWriter extends ImageWriter {
// ----- END replacePixels methods -----
// Save stream positions for use when aborted.
private void markPositions() throws IOException {
prevStreamPosition = stream.getStreamPosition();
prevHeaderPosition = headerPosition;
prevNextSpace = nextSpace;
}
// Reset to positions saved by markPositions().
private void resetPositions() throws IOException {
stream.seek(prevStreamPosition);
headerPosition = prevHeaderPosition;
nextSpace = prevNextSpace;
}
public void reset() {
super.reset();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,10 +25,11 @@
package com.sun.media.sound;
import java.util.Objects;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.spi.MidiDeviceProvider;
/**
* Super class for MIDI input or output device provider.
*
@ -127,7 +128,8 @@ public abstract class AbstractMidiDeviceProvider extends MidiDeviceProvider {
}
@Override
public final MidiDevice getDevice(MidiDevice.Info info) {
public final MidiDevice getDevice(final MidiDevice.Info info) {
Objects.requireNonNull(info);
if (info instanceof Info) {
readDeviceInfos();
MidiDevice[] devices = getDeviceCache();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -22,6 +22,7 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.media.sound;
import java.io.BufferedReader;
@ -32,6 +33,8 @@ import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Objects;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.Soundbank;
import javax.sound.midi.spi.SoundbankReader;
@ -112,6 +115,7 @@ public final class JARSoundbankReader extends SoundbankReader {
public Soundbank getSoundbank(InputStream stream)
throws InvalidMidiDataException, IOException {
Objects.requireNonNull(stream);
return null;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,6 +25,8 @@
package com.sun.media.sound;
import java.util.Objects;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.spi.MidiDeviceProvider;
@ -42,6 +44,7 @@ public final class RealTimeSequencerProvider extends MidiDeviceProvider {
@Override
public MidiDevice getDevice(final MidiDevice.Info info) {
Objects.requireNonNull(info);
if (RealTimeSequencer.info.equals(info)) {
return new RealTimeSequencer();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,6 +25,8 @@
package com.sun.media.sound;
import java.util.Objects;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.spi.MidiDeviceProvider;
@ -42,6 +44,7 @@ public final class SoftProvider extends MidiDeviceProvider {
@Override
public MidiDevice getDevice(final MidiDevice.Info info) {
Objects.requireNonNull(info);
if (SoftSynthesizer.info.equals(info)) {
return new SoftSynthesizer();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -25,21 +25,22 @@
package com.sun.media.sound;
import java.io.DataOutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.SequenceInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.SequenceInputStream;
import java.util.Objects;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.MetaMessage;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.Sequence;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.SysexMessage;
@ -115,24 +116,16 @@ public final class StandardMidiFileWriter extends MidiFileWriter {
return typesArray;
}
public boolean isFileTypeSupported(int type) {
for(int i=0; i<types.length; i++) {
if( type == types[i] ) {
return true;
}
}
return false;
}
public int write(Sequence in, int type, OutputStream out) throws IOException {
Objects.requireNonNull(out);
if (!isFileTypeSupported(type, in)) {
throw new IllegalArgumentException("Could not write MIDI file");
}
byte [] buffer = null;
int bytesRead = 0;
long bytesWritten = 0;
if( !isFileTypeSupported(type,in) ) {
throw new IllegalArgumentException("Could not write MIDI file");
}
// First get the fileStream from this sequence
InputStream fileStream = getFileStream(type,in);
if (fileStream == null) {
@ -149,6 +142,7 @@ public final class StandardMidiFileWriter extends MidiFileWriter {
}
public int write(Sequence in, int type, File out) throws IOException {
Objects.requireNonNull(in);
FileOutputStream fos = new FileOutputStream(out); // throws IOException
int bytesWritten = write( in, type, fos );
fos.close();

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