提交 03f2447b 编写于 作者: L lana

Merge

......@@ -179,3 +179,6 @@ e8569a473cee7f4955bd9e76a9bdf6c6a07ced27 jdk8-b52
1f3f4b333341873f00da3dee85e4879f0e89c9bb jdk8-b55
2e9eeef2909b33c9224a024afddb61ccb0b77f14 jdk8-b56
51594d095a4bcffac4a314bf6e148214501399e0 jdk8-b57
d94613ac03d8de375ef60493e2bb76dbd30d875d jdk8-b58
abad1f417bd3df4296631fc943cd3b7f5062c88a jdk8-b59
cec8fa02f15634acd7d02d04b0b2d8c044cdbaaa jdk8-b60
......@@ -213,6 +213,7 @@ JAVA_JAVA_java = \
sun/util/locale/provider/DateFormatSymbolsProviderImpl.java \
sun/util/locale/provider/DecimalFormatSymbolsProviderImpl.java \
sun/util/locale/provider/DictionaryBasedBreakIterator.java \
sun/util/locale/provider/FallbackLocaleProviderAdapter.java \
sun/util/locale/provider/HostLocaleProviderAdapter.java \
sun/util/locale/provider/HostLocaleProviderAdapterImpl.java \
sun/util/locale/provider/JRELocaleConstants.java \
......@@ -235,6 +236,7 @@ JAVA_JAVA_java = \
java/util/Observer.java \
java/util/Properties.java \
java/util/InvalidPropertiesFormatException.java \
sun/util/spi/XmlPropertiesProvider.java \
java/util/PropertyPermission.java \
java/util/PropertyResourceBundle.java \
java/util/Random.java \
......
......@@ -108,6 +108,7 @@ SUNWprivate_1.1 {
Java_sun_nio_ch_Net_setInterface6;
Java_sun_nio_ch_Net_getInterface6;
Java_sun_nio_ch_Net_shutdown;
Java_sun_nio_ch_Net_poll;
Java_sun_nio_ch_PollArrayWrapper_interrupt;
Java_sun_nio_ch_PollArrayWrapper_poll0;
Java_sun_nio_ch_ServerSocketChannelImpl_accept0;
......
......@@ -116,6 +116,7 @@ SUNWprivate_1.1 {
Java_sun_nio_ch_Net_setInterface6;
Java_sun_nio_ch_Net_getInterface6;
Java_sun_nio_ch_Net_shutdown;
Java_sun_nio_ch_Net_poll;
Java_sun_nio_ch_PollArrayWrapper_interrupt;
Java_sun_nio_ch_PollArrayWrapper_poll0;
Java_sun_nio_ch_ServerSocketChannelImpl_accept0;
......
......@@ -104,6 +104,7 @@ SUNWprivate_1.1 {
Java_sun_nio_ch_Net_setInterface6;
Java_sun_nio_ch_Net_getInterface6;
Java_sun_nio_ch_Net_shutdown;
Java_sun_nio_ch_Net_poll;
Java_sun_nio_ch_PollArrayWrapper_interrupt;
Java_sun_nio_ch_PollArrayWrapper_poll0;
Java_sun_nio_ch_ServerSocketChannelImpl_accept0;
......
......@@ -158,7 +158,12 @@ include $(BUILDDIR)/common/Classes.gmk
#
ifdef OPENJDK
all: build-jar install-jar build-policy install-limited
ifdef UNLIMITED_CRYPTO
POLICY = install-unlimited
else
POLICY = install-limited
endif
all: build-jar install-jar build-policy $(POLICY)
else # OPENJDK
ifeq ($(strip $(FILES_java)),)
all:
......
......@@ -41,3 +41,20 @@ AUTO_FILES_JAVA_DIRS = sun/util/xml
#
include $(BUILDDIR)/common/Classes.gmk
#
# Rules for XML properties provider configuration file
#
SERVICEDIR = $(CLASSBINDIR)/META-INF/services
FILES_copy = $(SERVICEDIR)/sun.util.spi.XmlPropertiesProvider
copy-files: $(FILES_copy)
$(SERVICEDIR)/%: $(SHARE_SRC)/classes/sun/util/xml/META-INF/services/%
$(install-file)
build: copy-files
clean::
$(RM) $(FILES_copy)
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2012, 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
......@@ -337,7 +337,6 @@ static void addIdentitiesToKeystore(JNIEnv *env, jobject keyStore)
// Call back to the Java object to create Java objects corresponding to this security object.
jlong nativeKeyRef = ptr_to_jlong(privateKeyRef);
JNFCallVoidMethod(env, keyStore, jm_createKeyEntry, alias, creationDate, nativeKeyRef, certRefArray, javaCertArray);
break;
}
} while (searchResult == noErr);
......
......@@ -142,8 +142,11 @@ void JavaCT_DrawGlyphVector
// get our baseline transform and font
CGContextRef cgRef = qsdo->cgRef;
CGAffineTransform ctmText = CGContextGetTextMatrix(cgRef);
//CGFontRef cgFont = CGContextGetFont(cgRef);
/* Save and restore of graphics context is done before the iteration.
This seems to work using our test case (see bug ID 7158350) so we are restoring it at
the end of the for loop. If we find out that save/restore outside the loop
doesn't work on all cases then we will move the Save/Restore inside the loop.*/
CGContextSaveGState(cgRef);
CGAffineTransform invTx = CGAffineTransformInvert(strike->fTx);
......@@ -210,13 +213,9 @@ void JavaCT_DrawGlyphVector
pt.x += advances[i].width;
pt.y += advances[i].height;
// reset the font on the context after striking a unicode with CoreText
if (uniChar != 0)
{
// CGContextSetFont(cgRef, cgFont);
CGContextSaveGState(cgRef);
}
}
// reset the font on the context after striking a unicode with CoreText
CGContextRestoreGState(cgRef);
}
// Using the Quartz Surface Data context, draw a hot-substituted character run
......
......@@ -1064,12 +1064,17 @@ public class Krb5LoginModule implements LoginModule {
if (storeKey) {
if (encKeys == null) {
if (!privCredSet.contains(ktab)) {
privCredSet.add(ktab);
// Compatibility; also add keys to privCredSet
for (KerberosKey key: ktab.getKeys(kerbClientPrinc)) {
privCredSet.add(new Krb5Util.KeysFromKeyTab(key));
if (ktab != null) {
if (!privCredSet.contains(ktab)) {
privCredSet.add(ktab);
// Compatibility; also add keys to privCredSet
for (KerberosKey key: ktab.getKeys(kerbClientPrinc)) {
privCredSet.add(new Krb5Util.KeysFromKeyTab(key));
}
}
} else {
succeeded = false;
throw new LoginException("No key to store");
}
} else {
for (int i = 0; i < kerbKeys.length; i ++) {
......
......@@ -76,7 +76,7 @@ import sun.security.util.SecurityConstants;
* <P>
* Be careful when granting FilePermissions. Think about the implications
* of granting read and especially write access to various files and
* directories. The "&lt;&lt;ALL FILES>>" permission with write action is
* directories. The "&lt;&lt;ALL FILES&gt;&gt;" permission with write action is
* especially dangerous. This grants permission to write to the entire
* file system. One thing this effectively allows is replacement of the
* system binary, including the JVM runtime environment.
......@@ -180,9 +180,7 @@ public final class FilePermission extends Permission implements Serializable {
* @param mask the actions mask to use.
*
*/
private void init(int mask)
{
private void init(int mask) {
if ((mask & ALL) != mask)
throw new IllegalArgumentException("invalid actions mask");
......@@ -274,9 +272,7 @@ public final class FilePermission extends Permission implements Serializable {
* If actions is <code>null</code>, empty or contains an action
* other than the specified possible actions.
*/
public FilePermission(String path, String actions)
{
public FilePermission(String path, String actions) {
super(path);
init(getMask(actions));
}
......@@ -293,8 +289,7 @@ public final class FilePermission extends Permission implements Serializable {
*/
// package private for use by the FilePermissionCollection add method
FilePermission(String path, int mask)
{
FilePermission(String path, int mask) {
super(path);
init(mask);
}
......@@ -337,7 +332,6 @@ public final class FilePermission extends Permission implements Serializable {
* this FilePermission's path also implies that FilePermission's path.
*
* @param that the FilePermission to check against.
* @param exact return immediately if the masks are not equal
* @return the effective mask
*/
boolean impliesIgnoreMask(FilePermission that) {
......@@ -412,7 +406,6 @@ public final class FilePermission extends Permission implements Serializable {
*
* @return a hash code value for this object.
*/
public int hashCode() {
return this.cpath.hashCode();
}
......@@ -424,7 +417,6 @@ public final class FilePermission extends Permission implements Serializable {
* @return the actions mask.
*/
private static int getMask(String actions) {
int mask = NONE;
// Null action valid?
......@@ -552,7 +544,6 @@ public final class FilePermission extends Permission implements Serializable {
*
* @return the actions mask.
*/
int getMask() {
return mask;
}
......@@ -564,8 +555,7 @@ public final class FilePermission extends Permission implements Serializable {
*
* @return the canonical string representation of the actions.
*/
private static String getActions(int mask)
{
private static String getActions(int mask) {
StringBuilder sb = new StringBuilder();
boolean comma = false;
......@@ -610,15 +600,13 @@ public final class FilePermission extends Permission implements Serializable {
*
* @return the canonical string representation of the actions.
*/
public String getActions()
{
public String getActions() {
if (actions == null)
actions = getActions(this.mask);
return actions;
}
/**
* Returns a new PermissionCollection object for storing FilePermission
* objects.
......@@ -650,7 +638,6 @@ public final class FilePermission extends Permission implements Serializable {
* @return a new PermissionCollection object suitable for storing
* FilePermissions.
*/
public PermissionCollection newPermissionCollection() {
return new FilePermissionCollection();
}
......@@ -712,22 +699,20 @@ public final class FilePermission extends Permission implements Serializable {
*/
final class FilePermissionCollection extends PermissionCollection
implements Serializable {
implements Serializable
{
// Not serialized; see serialization section at end of class
private transient List<Permission> perms;
/**
* Create an empty FilePermissions object.
*
* Create an empty FilePermissionCollection object.
*/
public FilePermissionCollection() {
perms = new ArrayList<>();
}
/**
* Adds a permission to the FilePermissions. The key for the hash is
* Adds a permission to the FilePermissionCollection. The key for the hash is
* permission.path.
*
* @param permission the Permission object to add.
......@@ -738,9 +723,7 @@ implements Serializable {
* @exception SecurityException - if this FilePermissionCollection object
* has been marked readonly
*/
public void add(Permission permission)
{
public void add(Permission permission) {
if (! (permission instanceof FilePermission))
throw new IllegalArgumentException("invalid permission: "+
permission);
......@@ -757,16 +740,14 @@ implements Serializable {
* Check and see if this set of permissions implies the permissions
* expressed in "permission".
*
* @param p the Permission object to compare
* @param permission the Permission object to compare
*
* @return true if "permission" is a proper subset of a permission in
* the set, false if not.
*/
public boolean implies(Permission permission)
{
public boolean implies(Permission permission) {
if (! (permission instanceof FilePermission))
return false;
return false;
FilePermission fp = (FilePermission) permission;
......@@ -795,7 +776,6 @@ implements Serializable {
*
* @return an enumeration of all the FilePermission objects.
*/
public Enumeration<Permission> elements() {
// Convert Iterator into Enumeration
synchronized (this) {
......@@ -841,8 +821,9 @@ implements Serializable {
/*
* Reads in a Vector of FilePermissions and saves them in the perms field.
*/
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
// Don't call defaultReadObject()
// Read in serialized fields
......
/*
* Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2012, 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
......@@ -484,7 +484,7 @@ public class ObjectOutputStream
* stream. The state is reset to be the same as a new ObjectOutputStream.
* The current point in the stream is marked as reset so the corresponding
* ObjectInputStream will be reset at the same point. Objects previously
* written to the stream will not be refered to as already being in the
* written to the stream will not be referred to as already being in the
* stream. They will be written to the stream again.
*
* @throws IOException if reset() is invoked while serializing an object.
......
......@@ -784,7 +784,7 @@ public class PrintWriter extends Writer {
* <tt>null</tt> argument depends on the <a
* href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws IllegalFormatException
* @throws java.util.IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
......@@ -835,7 +835,7 @@ public class PrintWriter extends Writer {
* <tt>null</tt> argument depends on the <a
* href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws IllegalFormatException
* @throws java.util.IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
......@@ -879,7 +879,7 @@ public class PrintWriter extends Writer {
* <tt>null</tt> argument depends on the <a
* href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws IllegalFormatException
* @throws java.util.IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
......@@ -939,7 +939,7 @@ public class PrintWriter extends Writer {
* <tt>null</tt> argument depends on the <a
* href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws IllegalFormatException
* @throws java.util.IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
......
......@@ -91,7 +91,7 @@ public abstract class Reader implements Readable, Closeable {
* -1 if this source of characters is at its end
* @throws IOException if an I/O error occurs
* @throws NullPointerException if target is null
* @throws ReadOnlyBufferException if target is a read only buffer
* @throws java.nio.ReadOnlyBufferException if target is a read only buffer
* @since 1.5
*/
public int read(java.nio.CharBuffer target) throws IOException {
......
......@@ -2970,7 +2970,7 @@ public final
/**
* Returns a map from simple name to enum constant. This package-private
* method is used internally by Enum to implement
* public static <T extends Enum<T>> T valueOf(Class<T>, String)
* {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
* efficiently. Note that the map is returned by this method is
* created lazily on first use. Typically it won't ever get created.
*/
......
......@@ -76,7 +76,6 @@ public class InheritableThreadLocal<T> extends ThreadLocal<T> {
*
* @param t the current thread
* @param firstValue value for the initial entry of the table.
* @param map the map to store.
*/
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
......
......@@ -752,7 +752,7 @@ public final class Integer extends Number implements Comparable<Integer> {
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the -XX:AutoBoxCacheMax=<size> option.
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
......
......@@ -316,7 +316,7 @@ public class Package implements java.lang.reflect.AnnotatedElement {
* attributes are defined in the manifests that accompany
* the classes.
*
* @param class the class to get the package of.
* @param c the class to get the package of.
* @return the package of the class. It may be null if no package
* information is available from the archive or codebase. */
static Package getPackage(Class<?> c) {
......@@ -411,14 +411,13 @@ public class Package implements java.lang.reflect.AnnotatedElement {
/**
* Construct a package instance with the specified version
* information.
* @param pkgName the name of the package
* @param name the name of the package
* @param spectitle the title of the specification
* @param specversion the version of the specification
* @param specvendor the organization that maintains the specification
* @param impltitle the title of the implementation
* @param implversion the version of the implementation
* @param implvendor the organization that maintains the implementation
* @return a new package for containing the specified information.
*/
Package(String name,
String spectitle, String specversion, String specvendor,
......
......@@ -365,7 +365,7 @@ public final class StrictMath {
* @param a the value to be floored or ceiled
* @param negativeBoundary result for values in (-1, 0)
* @param positiveBoundary result for values in (0, 1)
* @param increment value to add when the argument is non-integral
* @param sign the sign of the result
*/
private static double floorOrCeil(double a,
double negativeBoundary,
......@@ -811,7 +811,7 @@ public final class StrictMath {
* @param value the long value
* @return the argument as an int
* @throws ArithmeticException if the {@code argument} overflows an int
* @see Math#toIntExact(int)
* @see Math#toIntExact(long)
* @since 1.8
*/
public static int toIntExact(long value) {
......
......@@ -2782,7 +2782,7 @@ public final class String
* <tt>null</tt> argument depends on the <a
* href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws IllegalFormatException
* @throws java.util.IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
......@@ -2826,7 +2826,7 @@ public final class String
* <tt>null</tt> argument depends on the <a
* href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws IllegalFormatException
* @throws java.util.IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
......
......@@ -545,7 +545,7 @@ public final class System {
* <tr><td><code>java.version</code></td>
* <td>Java Runtime Environment version</td></tr>
* <tr><td><code>java.vendor</code></td>
* <td>Java Runtime Environment vendor</td></tr
* <td>Java Runtime Environment vendor</td></tr>
* <tr><td><code>java.vendor.url</code></td>
* <td>Java vendor URL</td></tr>
* <tr><td><code>java.home</code></td>
......
......@@ -918,9 +918,6 @@ class ThreadGroup implements Thread.UncaughtExceptionHandler {
*
* @param t
* the Thread whose start method was invoked
*
* @param failed
* true if the thread could not be started successfully
*/
void threadStartFailed(Thread t) {
synchronized(this) {
......
......@@ -47,8 +47,8 @@ import java.util.concurrent.atomic.AtomicInteger;
* private static final AtomicInteger nextId = new AtomicInteger(0);
*
* // Thread local variable containing each thread's ID
* private static final ThreadLocal&lt;Integer> threadId =
* new ThreadLocal&lt;Integer>() {
* private static final ThreadLocal&lt;Integer&gt; threadId =
* new ThreadLocal&lt;Integer&gt;() {
* &#64;Override protected Integer initialValue() {
* return nextId.getAndIncrement();
* }
......@@ -222,7 +222,6 @@ public class ThreadLocal<T> {
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
* @param map the map to store.
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
......
......@@ -147,8 +147,9 @@ public class ThreadInfo {
* @param waitedCount Number of times waited on a lock
* @param waitedTime Approx time waited on a lock
* @param stackTrace Thread stack trace
* @param lockedMonitors List of locked monitors
* @param lockedSynchronizers List of locked synchronizers
* @param monitors List of locked monitors
* @param stackDepths List of stack depths
* @param synchronizers List of locked synchronizers
*/
private ThreadInfo(Thread t, int state, Object lockObj, Thread lockOwner,
long blockedCount, long blockedTime,
......
......@@ -48,11 +48,6 @@ abstract class AbstractPlainDatagramSocketImpl extends DatagramSocketImpl
protected InetAddress connectedAddress = null;
private int connectedPort = -1;
/* cached socket options */
private int multicastInterface = 0;
private boolean loopbackMode = true;
private int ttl = -1;
private static final String os = AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("os.name")
);
......@@ -104,7 +99,7 @@ abstract class AbstractPlainDatagramSocketImpl extends DatagramSocketImpl
/**
* Sends a datagram packet. The packet contains the data and the
* destination address to send the packet to.
* @param packet to be sent.
* @param p the packet to be sent.
*/
protected abstract void send(DatagramPacket p) throws IOException;
......@@ -135,13 +130,13 @@ abstract class AbstractPlainDatagramSocketImpl extends DatagramSocketImpl
/**
* Peek at the packet to see who it is from.
* @param return the address which the packet came from.
* @param i the address to populate with the sender address
*/
protected abstract int peek(InetAddress i) throws IOException;
protected abstract int peekData(DatagramPacket p) throws IOException;
/**
* Receive the datagram packet.
* @param Packet Received.
* @param p the packet to receive into
*/
protected synchronized void receive(DatagramPacket p)
throws IOException {
......@@ -153,7 +148,7 @@ abstract class AbstractPlainDatagramSocketImpl extends DatagramSocketImpl
/**
* Set the TTL (time-to-live) option.
* @param TTL to be set.
* @param ttl TTL to be set.
*/
protected abstract void setTimeToLive(int ttl) throws IOException;
......@@ -164,7 +159,7 @@ abstract class AbstractPlainDatagramSocketImpl extends DatagramSocketImpl
/**
* Set the TTL (time-to-live) option.
* @param TTL to be set.
* @param ttl TTL to be set.
*/
@Deprecated
protected abstract void setTTL(byte ttl) throws IOException;
......@@ -177,7 +172,7 @@ abstract class AbstractPlainDatagramSocketImpl extends DatagramSocketImpl
/**
* Join the multicast group.
* @param multicast address to join.
* @param inetaddr multicast address to join.
*/
protected void join(InetAddress inetaddr) throws IOException {
join(inetaddr, null);
......@@ -185,14 +180,14 @@ abstract class AbstractPlainDatagramSocketImpl extends DatagramSocketImpl
/**
* Leave the multicast group.
* @param multicast address to leave.
* @param inetaddr multicast address to leave.
*/
protected void leave(InetAddress inetaddr) throws IOException {
leave(inetaddr, null);
}
/**
* Join the multicast group.
* @param multicast address to join.
* @param mcastaddr multicast address to join.
* @param netIf specifies the local interface to receive multicast
* datagram packets
* @throws IllegalArgumentException if mcastaddr is null or is a
......@@ -212,7 +207,7 @@ abstract class AbstractPlainDatagramSocketImpl extends DatagramSocketImpl
/**
* Leave the multicast group.
* @param multicast address to leave.
* @param mcastaddr multicast address to leave.
* @param netIf specified the local interface to leave the group at
* @throws IllegalArgumentException if mcastaddr is null or is a
* SocketAddress subclass not supported by this socket
......
......@@ -368,7 +368,7 @@ abstract class AbstractPlainSocketImpl extends SocketImpl
/**
* Binds the socket to the specified address of the specified local port.
* @param address the address
* @param port the port
* @param lport the port
*/
protected synchronized void bind(InetAddress address, int lport)
throws IOException
......
......@@ -105,7 +105,7 @@ class DatagramSocket implements java.io.Closeable {
* Connects this socket to a remote socket address (IP address + port number).
* Binds socket if not already bound.
* <p>
* @param addr The remote address.
* @param address The remote address.
* @param port The remote port
* @throws SocketException if binding the socket fails.
*/
......
......@@ -177,7 +177,6 @@ class Inet4Address extends InetAddress {
* a loopback address; or false otherwise.
* @since 1.4
*/
private static final int loopback = 2130706433; /* 127.0.0.1 */
public boolean isLoopbackAddress() {
/* 127.x.x.x */
byte[] byteAddr = getAddress();
......
......@@ -112,7 +112,7 @@ class SocketInputStream extends FileInputStream
* <i>length</i> bytes of data.
* @param b the buffer into which the data is read
* @param off the start offset of the data
* @param len the maximum number of bytes read
* @param length the maximum number of bytes read
* @return the actual number of bytes read, -1 is
* returned when the end of the stream is reached.
* @exception IOException If an I/O error has occurred.
......@@ -209,7 +209,7 @@ class SocketInputStream extends FileInputStream
/**
* Skips n bytes of input.
* @param n the number of bytes to skip
* @param numbytes the number of bytes to skip
* @return the actual number of bytes skipped.
* @exception IOException If an I/O error has occurred.
*/
......
......@@ -138,7 +138,7 @@ import sun.security.util.Debug;
*/
public final class SocketPermission extends Permission
implements java.io.Serializable
implements java.io.Serializable
{
private static final long serialVersionUID = -7204263841984476862L;
......@@ -232,8 +232,7 @@ implements java.io.Serializable
trustNameService = tmp.booleanValue();
}
private static synchronized Debug getDebug()
{
private static synchronized Debug getDebug() {
if (!debugInit) {
debug = Debug.getInstance("access");
debugInit = true;
......@@ -288,8 +287,7 @@ implements java.io.Serializable
defaultDeny = true;
}
private static String getHost(String host)
{
private static String getHost(String host) {
if (host.equals("")) {
return "localhost";
} else {
......@@ -679,8 +677,8 @@ implements java.io.Serializable
}
private boolean authorizedIPv4(String cname, byte[] addr) {
String authHost = "";
InetAddress auth;
String authHost = "";
InetAddress auth;
try {
authHost = "auth." +
......@@ -708,8 +706,8 @@ implements java.io.Serializable
}
private boolean authorizedIPv6(String cname, byte[] addr) {
String authHost = "";
InetAddress auth;
String authHost = "";
InetAddress auth;
try {
StringBuffer sb = new StringBuffer(39);
......@@ -810,7 +808,6 @@ implements java.io.Serializable
* @return true if the specified permission is implied by this object,
* false if not.
*/
public boolean implies(Permission p) {
int i,j;
......@@ -844,12 +841,11 @@ implements java.io.Serializable
* to find a match based on the IP addresses in both objects.
* <li> Attempt to match on the canonical hostnames of both objects.
* </ul>
* @param p the incoming permission request
* @param that the incoming permission request
*
* @return true if "permission" is a proper subset of the current object,
* false if not.
*/
boolean impliesIgnoreMask(SocketPermission that) {
int i,j;
......@@ -1229,7 +1225,7 @@ else its the cname?
*/
final class SocketPermissionCollection extends PermissionCollection
implements Serializable
implements Serializable
{
// Not serialized; see serialization section at end of class
private transient List<SocketPermission> perms;
......@@ -1255,9 +1251,7 @@ implements Serializable
* @exception SecurityException - if this SocketPermissionCollection object
* has been marked readonly
*/
public void add(Permission permission)
{
public void add(Permission permission) {
if (! (permission instanceof SocketPermission))
throw new IllegalArgumentException("invalid permission: "+
permission);
......@@ -1276,7 +1270,7 @@ implements Serializable
* Check and see if this collection of permissions implies the permissions
* expressed in "permission".
*
* @param p the Permission object to compare
* @param permission the Permission object to compare
*
* @return true if "permission" is a proper subset of a permission in
* the collection, false if not.
......@@ -1369,8 +1363,9 @@ implements Serializable
/*
* Reads in a Vector of SocketPermissions and saves them in the perms field.
*/
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
// Don't call in.defaultReadObject()
// Read in serialized fields
......
......@@ -644,7 +644,7 @@ class SocksSocketImpl extends PlainSocketImpl implements SocksConsts {
* means "accept incoming connection from", so the SocketAddress is the
* the one of the host we do accept connection from.
*
* @param addr the Socket address of the remote host.
* @param saddr the Socket address of the remote host.
* @exception IOException if an I/O error occurs when binding this socket.
*/
protected synchronized void socksBind(InetSocketAddress saddr) throws IOException {
......
......@@ -1241,10 +1241,9 @@ public abstract class URLConnection {
/**
* Gets the Content Handler appropriate for this connection.
* @param connection the connection to use.
*/
synchronized ContentHandler getContentHandler()
throws UnknownServiceException
throws UnknownServiceException
{
String contentType = stripOffParameters(getContentType());
ContentHandler handler = null;
......
......@@ -741,6 +741,8 @@ public abstract class $Type$Buffer
public $Type$Buffer put($Type$Buffer src) {
if (src == this)
throw new IllegalArgumentException();
if (isReadOnly())
throw new ReadOnlyBufferException();
int n = src.remaining();
if (n > remaining())
throw new BufferOverflowException();
......@@ -888,6 +890,8 @@ public abstract class $Type$Buffer
*/
public $Type$Buffer put(String src, int start, int end) {
checkBounds(start, end - start, src.length());
if (isReadOnly())
throw new ReadOnlyBufferException();
if (end - start > remaining())
throw new BufferOverflowException();
for (int i = start; i < end; i++)
......
......@@ -84,7 +84,7 @@ public final class Channels {
/**
* Write all remaining bytes in buffer to the given channel.
*
* @throws IllegalBlockingException
* @throws IllegalBlockingModeException
* If the channel is selectable and configured non-blocking.
*/
private static void writeFully(WritableByteChannel ch, ByteBuffer bb)
......
......@@ -347,7 +347,7 @@ public abstract class FileSystem
* <td><tt>C:&#92;&#92;*</tt>
* <td>Matches <tt>C:&#92;foo</tt> and <tt>C:&#92;bar</tt> on the Windows
* platform (note that the backslash is escaped; as a string literal in the
* Java Language the pattern would be <tt>"C:&#92;&#92;&#92;&#92*"</tt>) </td>
* Java Language the pattern would be <tt>"C:&#92;&#92;&#92;&#92;*"</tt>) </td>
* </tr>
*
* </table>
......
......@@ -510,7 +510,7 @@ public final class Files {
* <pre>
* DirectoryStream.Filter&lt;Path&gt; filter = new DirectoryStream.Filter&lt;Path&gt;() {
* public boolean accept(Path file) throws IOException {
* return (Files.size(file) > 8192L);
* return (Files.size(file) &gt; 8192L);
* }
* };
* Path dir = ...
......@@ -1592,7 +1592,7 @@ public final class Files {
* Path path = ...
* AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);
* if (view != null) {
* List&lt;AclEntry&gt acl = view.getAcl();
* List&lt;AclEntry&gt; acl = view.getAcl();
* :
* }
* </pre>
......
......@@ -522,7 +522,7 @@ public interface Path
*
* @return a {@code Path} object representing the absolute path
*
* @throws IOError
* @throws java.io.IOError
* if an I/O error occurs
* @throws SecurityException
* In the case of the default provider, a security manager
......
......@@ -85,7 +85,7 @@ import java.io.IOException;
* .build();
*
* // read ACL, insert ACE, re-write ACL
* List&lt;AclEntry&gt acl = view.getAcl();
* List&lt;AclEntry&gt; acl = view.getAcl();
* acl.add(0, entry); // insert before any DENY entries
* view.setAcl(acl);
* </pre>
......
......@@ -310,7 +310,7 @@ public final class FileTime
private final long days;
/**
* The excess (in nanoseconds); can be negative if days <= 0.
* The excess (in nanoseconds); can be negative if days &lt;= 0.
*/
private final long excessNanos;
......
......@@ -62,9 +62,7 @@ public final class AllPermission extends Permission {
/**
* Creates a new AllPermission object.
*/
public AllPermission()
{
public AllPermission() {
super("<all permissions>");
}
......@@ -77,8 +75,7 @@ public final class AllPermission extends Permission {
* @param name ignored
* @param actions ignored.
*/
public AllPermission(String name, String actions)
{
public AllPermission(String name, String actions) {
this();
}
......@@ -120,8 +117,7 @@ public final class AllPermission extends Permission {
*
* @return the actions.
*/
public String getActions()
{
public String getActions() {
return "<all actions>";
}
......@@ -133,7 +129,6 @@ public final class AllPermission extends Permission {
* @return a new PermissionCollection object suitable for
* storing AllPermissions.
*/
public PermissionCollection newPermissionCollection() {
return new AllPermissionCollection();
}
......@@ -157,8 +152,8 @@ public final class AllPermission extends Permission {
*/
final class AllPermissionCollection
extends PermissionCollection
implements java.io.Serializable
extends PermissionCollection
implements java.io.Serializable
{
// use serialVersionUID from JDK 1.2.2 for interoperability
......@@ -188,8 +183,7 @@ implements java.io.Serializable
* has been marked readonly
*/
public void add(Permission permission)
{
public void add(Permission permission) {
if (! (permission instanceof AllPermission))
throw new IllegalArgumentException("invalid permission: "+
permission);
......@@ -203,13 +197,12 @@ implements java.io.Serializable
* Check and see if this set of permissions implies the permissions
* expressed in "permission".
*
* @param p the Permission object to compare
* @param permission the Permission object to compare
*
* @return always returns true.
*/
public boolean implies(Permission permission)
{
public boolean implies(Permission permission) {
return all_allowed; // No sync; staleness OK
}
......@@ -219,8 +212,7 @@ implements java.io.Serializable
*
* @return an enumeration of all the AllPermission objects.
*/
public Enumeration<Permission> elements()
{
public Enumeration<Permission> elements() {
return new Enumeration<Permission>() {
private boolean hasMore = all_allowed;
......
......@@ -68,7 +68,7 @@ import java.io.IOException;
*/
public abstract class BasicPermission extends Permission
implements java.io.Serializable
implements java.io.Serializable
{
private static final long serialVersionUID = 6279438298436773498L;
......@@ -84,10 +84,8 @@ implements java.io.Serializable
/**
* initialize a BasicPermission object. Common to all constructors.
*
*/
private void init(String name)
{
private void init(String name) {
if (name == null)
throw new NullPointerException("name can't be null");
......@@ -129,9 +127,7 @@ implements java.io.Serializable
* @throws NullPointerException if <code>name</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>name</code> is empty.
*/
public BasicPermission(String name)
{
public BasicPermission(String name) {
super(name);
init(name);
}
......@@ -148,8 +144,7 @@ implements java.io.Serializable
* @throws NullPointerException if <code>name</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>name</code> is empty.
*/
public BasicPermission(String name, String actions)
{
public BasicPermission(String name, String actions) {
super(name);
init(name);
}
......@@ -238,8 +233,7 @@ implements java.io.Serializable
*
* @return the empty string "".
*/
public String getActions()
{
public String getActions() {
return "";
}
......@@ -296,7 +290,6 @@ implements java.io.Serializable
*
* @see java.security.Permission
* @see java.security.Permissions
* @see java.security.PermissionsImpl
*
*
* @author Roland Schemers
......@@ -305,8 +298,8 @@ implements java.io.Serializable
*/
final class BasicPermissionCollection
extends PermissionCollection
implements java.io.Serializable
extends PermissionCollection
implements java.io.Serializable
{
private static final long serialVersionUID = 739301742472979399L;
......@@ -360,9 +353,7 @@ implements java.io.Serializable
* @exception SecurityException - if this BasicPermissionCollection object
* has been marked readonly
*/
public void add(Permission permission)
{
public void add(Permission permission) {
if (! (permission instanceof BasicPermission))
throw new IllegalArgumentException("invalid permission: "+
permission);
......@@ -398,16 +389,14 @@ implements java.io.Serializable
* Check and see if this set of permissions implies the permissions
* expressed in "permission".
*
* @param p the Permission object to compare
* @param permission the Permission object to compare
*
* @return true if "permission" is a proper subset of a permission in
* the set, false if not.
*/
public boolean implies(Permission permission)
{
public boolean implies(Permission permission) {
if (! (permission instanceof BasicPermission))
return false;
return false;
BasicPermission bp = (BasicPermission) permission;
......@@ -468,7 +457,6 @@ implements java.io.Serializable
*
* @return an enumeration of all the BasicPermission objects.
*/
public Enumeration<Permission> elements() {
// Convert Iterator of Map values into an Enumeration
synchronized (this) {
......
......@@ -207,7 +207,7 @@ public class CodeSource implements java.io.Serializable {
* Returns the code signers associated with this CodeSource.
* <p>
* If this CodeSource object was created using the
* {@link #CodeSource(URL url, Certificate[] certs)}
* {@link #CodeSource(URL url, java.security.cert.Certificate[] certs)}
* constructor then its certificate chains are extracted and used to
* create an array of CodeSigner objects. Note that only X.509 certificates
* are examined - all other certificate types are ignored.
......
......@@ -32,6 +32,7 @@ import java.security.cert.CertificateException;
import java.util.*;
import javax.crypto.SecretKey;
import javax.security.auth.DestroyFailedException;
import javax.security.auth.callback.*;
/**
......@@ -278,8 +279,7 @@ public class KeyStore {
* @exception DestroyFailedException if this method was unable
* to clear the password
*/
public synchronized void destroy()
throws javax.security.auth.DestroyFailedException {
public synchronized void destroy() throws DestroyFailedException {
destroyed = true;
if (password != null) {
Arrays.fill(password, ' ');
......
......@@ -50,7 +50,7 @@ import java.util.Set;
* status of certificates with OCSP and CRLs. By default, OCSP is the
* preferred mechanism for checking revocation status, with CRLs as the
* fallback mechanism. However, this preference can be switched to CRLs with
* the {@link Option.PREFER_CRLS} option.
* the {@link Option#PREFER_CRLS PREFER_CRLS} option.
*
* <p>A {@code PKIXRevocationChecker} is obtained by calling the
* {@link CertPathValidator#getRevocationChecker getRevocationChecker} method
......
......@@ -1562,7 +1562,7 @@ public interface CallableStatement extends PreparedStatement {
* @param parameterName the name of the parameter
* @return the parameter value in full precision. If the value is
* SQL <code>NULL</code>, the result is <code>null</code>.
* @exception SQLExceptionif parameterName does not correspond to a named
* @exception SQLException if parameterName does not correspond to a named
* parameter; if a database access error occurs or
* this method is called on a closed <code>CallableStatement</code>
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
......
......@@ -119,7 +119,7 @@ public final class CollationElementIterator
* on the predefined collation rules. If the source string is empty,
* NULLORDER will be returned on the calls to next().
* @param sourceText the source string.
* @param order the collation object.
* @param owner the collation object.
*/
CollationElementIterator(String sourceText, RuleBasedCollator owner) {
this.owner = owner;
......@@ -137,7 +137,7 @@ public final class CollationElementIterator
* on the predefined collation rules. If the source string is empty,
* NULLORDER will be returned on the calls to next().
* @param sourceText the source string.
* @param order the collation object.
* @param owner the collation object.
*/
CollationElementIterator(CharacterIterator sourceText, RuleBasedCollator owner) {
this.owner = owner;
......
......@@ -62,7 +62,7 @@ import java.math.RoundingMode;
* derived by placing all the digits of the list to the right of the
* decimal point, by 10^exponent.
*
* @see Locale
* @see java.util.Locale
* @see Format
* @see NumberFormat
* @see DecimalFormat
......
......@@ -370,7 +370,7 @@ public abstract class Format implements Serializable, Cloneable {
* Delegates should NOT assume that the <code>Format</code> will notify
* the delegate of fields in any particular order.
*
* @see FieldPosition.Delegate
* @see FieldPosition#getFieldDelegate
* @see CharacterIteratorFieldDelegate
*/
interface FieldDelegate {
......
/*
* Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2012, 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
......@@ -286,10 +286,21 @@ public abstract class NumberFormat extends Format {
* @see java.text.Format#format
*/
public final String format(double number) {
// Use fast-path for double result if that works
String result = fastFormat(number);
if (result != null)
return result;
return format(number, new StringBuffer(),
DontCareFieldPosition.INSTANCE).toString();
}
/*
* fastFormat() is supposed to be implemented in concrete subclasses only.
* Default implem always returns null.
*/
String fastFormat(double number) { return null; }
/**
* Specialization of format.
* @exception ArithmeticException if rounding is needed with rounding
......
......@@ -192,13 +192,12 @@ final class RBCollationTables {
*
* @see CollationElementIterator#getMaxExpansion
*/
int getMaxExpansion(int order)
{
int getMaxExpansion(int order) {
int result = 1;
if (expandTable != null) {
// Right now this does a linear search through the entire
// expandsion table. If a collator had a large number of expansions,
// expansion table. If a collator had a large number of expansions,
// this could cause a performance problem, but in practise that
// rarely happens
for (int i = 0; i < expandTable.size(); i++) {
......@@ -215,20 +214,19 @@ final class RBCollationTables {
}
/**
* Get the entry of hash table of the expanding string in the collation
* table.
* @param idx the index of the expanding string value list
* Get the entry of hash table of the expanding string in the collation
* table.
* @param idx the index of the expanding string value list
*/
final int[] getExpandValueList(int order) {
return expandTable.elementAt(order - EXPANDCHARINDEX);
final int[] getExpandValueList(int idx) {
return expandTable.elementAt(idx - EXPANDCHARINDEX);
}
/**
* Get the comarison order of a character from the collation table.
* @return the comparison order of a character.
* Get the comarison order of a character from the collation table.
* @return the comparison order of a character.
*/
int getUnicodeOrder(int ch)
{
int getUnicodeOrder(int ch) {
return mapping.elementAt(ch);
}
......
......@@ -71,7 +71,7 @@ final class RBTableBuilder {
* This is the main function that actually builds the tables and
* stores them back in the RBCollationTables object. It is called
* ONLY by the RBCollationTables constructor.
* @see java.util.RuleBasedCollator#RuleBasedCollator
* @see RuleBasedCollator#RuleBasedCollator
* @exception ParseException If the rules format is incorrect.
*/
......
......@@ -1787,7 +1787,7 @@ public class SimpleDateFormat extends DateFormat {
* timeFields. Returns -start (for ParsePosition) if failed.
* @param text the time text to be parsed.
* @param start where to start parsing.
* @param ch the pattern character for the date field text to be parsed.
* @param patternCharIndex the index of the pattern character.
* @param count the count of a pattern character.
* @param obeyCount if true, then the next field directly abuts this one,
* and we should use the count to know when to stop parsing.
......
......@@ -1788,7 +1788,6 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca
*
* @return a bit mask of selected fields
* @see #isExternallySet(int)
* @see #setInternallySetState(int)
*/
final int selectFields() {
// This implementation has been taken from the GregorianCalendar class.
......
......@@ -665,7 +665,7 @@ public final class Currency implements Serializable {
*
* @param pattern regex pattern for the properties
* @param ctry country code
* @param data currency data. This is a comma separated string that
* @param curdata currency data. This is a comma separated string that
* consists of "three-letter alphabet code", "three-digit numeric code",
* and "one-digit (0,1,2, or 3) default fraction digit".
* For example, "JPZ,392,0".
......
......@@ -918,7 +918,7 @@ import sun.misc.FormattedFloatingDecimal;
* <p> If the {@code '0'} flag is given then the output will be padded
* with leading zeros to the field width following any indication of sign.
*
* <p> If {@code '('}, {@code '+'}, '&nbsp&nbsp;', or {@code ','} flags
* <p> If {@code '('}, {@code '+'}, '&nbsp;&nbsp;', or {@code ','} flags
* are given then a {@link FormatFlagsConversionMismatchException} will be
* thrown.
*
......
......@@ -1932,7 +1932,7 @@ class JapaneseImperialCalendar extends Calendar {
* Computes the fixed date under either the Gregorian or the
* Julian calendar, using the given year and the specified calendar fields.
*
* @param cal the CalendarSystem to be used for the date calculation
* @param era era index
* @param year the normalized year number, with 0 indicating the
* year 1 BCE, -1 indicating 2 BCE, etc.
* @param fieldMask the calendar fields to be used for the date calculation
......@@ -2141,7 +2141,7 @@ class JapaneseImperialCalendar extends Calendar {
* Returns the length of the specified month in the specified
* Gregorian year. The year number must be normalized.
*
* @see #isLeapYear(int)
* @see GregorianCalendar#isLeapYear(int)
*/
private int monthLength(int month, int gregorianYear) {
return CalendarUtils.isGregorianLeapYear(gregorianYear) ?
......@@ -2152,7 +2152,7 @@ class JapaneseImperialCalendar extends Calendar {
* Returns the length of the specified month in the year provided
* by internalGet(YEAR).
*
* @see #isLeapYear(int)
* @see GregorianCalendar#isLeapYear(int)
*/
private int monthLength(int month) {
assert jdate.isNormalized();
......
......@@ -345,7 +345,7 @@ class JumboEnumSet<E extends Enum<E>> extends EnumSet<E> {
* the same size, and every member of the given set is contained in
* this set.
*
* @param e object to be compared for equality with this set
* @param o object to be compared for equality with this set
* @return <tt>true</tt> if the specified object is equal to this set
*/
public boolean equals(Object o) {
......
......@@ -34,7 +34,10 @@ import java.io.Reader;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.lang.reflect.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import sun.util.spi.XmlPropertiesProvider;
/**
* The {@code Properties} class represents a persistent set of
......@@ -866,7 +869,7 @@ class Properties extends Hashtable<Object,Object> {
{
if (in == null)
throw new NullPointerException();
XMLUtils.load(this, in);
XmlSupport.load(this, in);
in.close();
}
......@@ -934,7 +937,7 @@ class Properties extends Hashtable<Object,Object> {
{
if (os == null)
throw new NullPointerException();
XMLUtils.save(this, os, comment, encoding);
XmlSupport.save(this, os, comment, encoding);
}
/**
......@@ -1113,59 +1116,82 @@ class Properties extends Hashtable<Object,Object> {
'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
};
/**
* Supporting class for loading/storing properties in XML format.
*
* <p> The {@code load} and {@code store} methods defined here delegate to a
* system-wide {@code XmlPropertiesProvider}. On first invocation of either
* method then the system-wide provider is located as follows: </p>
*
* <ol>
* <li> If the system property {@code sun.util.spi.XmlPropertiesProvider}
* is defined then it is taken to be the full-qualified name of a concrete
* provider class. The class is loaded with the system class loader as the
* initiating loader. If it cannot be loaded or instantiated using a zero
* argument constructor then an unspecified error is thrown. </li>
*
* <li> If the system property is not defined then the service-provider
* loading facility defined by the {@link ServiceLoader} class is used to
* locate a provider with the system class loader as the initiating
* loader and {@code sun.util.spi.XmlPropertiesProvider} as the service
* type. If this process fails then an unspecified error is thrown. If
* there is more than one service provider installed then it is
* not specified as to which provider will be used. </li>
*
* <li> If the provider is not found by the above means then a system
* default provider will be instantiated and used. </li>
* </ol>
*/
private static class XmlSupport {
private static class XMLUtils {
private static Method load = null;
private static Method save = null;
static {
private static XmlPropertiesProvider loadProviderFromProperty(ClassLoader cl) {
String cn = System.getProperty("sun.util.spi.XmlPropertiesProvider");
if (cn == null)
return null;
try {
// reference sun.util.xml.Utils reflectively
// to allow the Properties class be compiled in
// the absence of XML
Class<?> c = Class.forName("sun.util.xml.XMLUtils", true, null);
load = c.getMethod("load", Properties.class, InputStream.class);
save = c.getMethod("save", Properties.class, OutputStream.class,
String.class, String.class);
} catch (ClassNotFoundException cnf) {
throw new AssertionError(cnf);
} catch (NoSuchMethodException e) {
throw new AssertionError(e);
Class<?> c = Class.forName(cn, true, cl);
return (XmlPropertiesProvider)c.newInstance();
} catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException x) {
throw new ServiceConfigurationError(null, x);
}
}
static void invoke(Method m, Object... args) throws IOException {
try {
m.invoke(null, args);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException)
throw (RuntimeException)t;
private static XmlPropertiesProvider loadProviderAsService(ClassLoader cl) {
Iterator<XmlPropertiesProvider> iterator =
ServiceLoader.load(XmlPropertiesProvider.class, cl).iterator();
return iterator.hasNext() ? iterator.next() : null;
}
if (t instanceof IOException) {
throw (IOException)t;
} else {
throw new AssertionError(t);
}
}
private static XmlPropertiesProvider loadProvider() {
return AccessController.doPrivileged(
new PrivilegedAction<XmlPropertiesProvider>() {
public XmlPropertiesProvider run() {
ClassLoader cl = ClassLoader.getSystemClassLoader();
XmlPropertiesProvider provider = loadProviderFromProperty(cl);
if (provider != null)
return provider;
provider = loadProviderAsService(cl);
if (provider != null)
return provider;
throw new InternalError("No fallback");
}});
}
private static final XmlPropertiesProvider PROVIDER = loadProvider();
static void load(Properties props, InputStream in)
throws IOException, InvalidPropertiesFormatException
{
if (load == null)
throw new InternalError("sun.util.xml.XMLUtils not found");
invoke(load, props, in);
PROVIDER.load(props, in);
}
static void save(Properties props, OutputStream os, String comment,
String encoding)
throws IOException
{
if (save == null)
throw new InternalError("sun.util.xml.XMLUtils not found");
invoke(save, props, os, comment, encoding);
PROVIDER.store(props, os, comment, encoding);
}
}
}
......@@ -130,18 +130,15 @@ public final class PropertyPermission extends BasicPermission {
* @param mask the actions mask to use.
*
*/
private void init(int mask)
{
private void init(int mask) {
if ((mask & ALL) != mask)
throw new IllegalArgumentException("invalid actions mask");
throw new IllegalArgumentException("invalid actions mask");
if (mask == NONE)
throw new IllegalArgumentException("invalid actions mask");
throw new IllegalArgumentException("invalid actions mask");
if (getName() == null)
throw new NullPointerException("name can't be null");
throw new NullPointerException("name can't be null");
this.mask = mask;
}
......@@ -160,9 +157,7 @@ public final class PropertyPermission extends BasicPermission {
* @throws IllegalArgumentException if <code>name</code> is empty or if
* <code>actions</code> is invalid.
*/
public PropertyPermission(String name, String actions)
{
public PropertyPermission(String name, String actions) {
super(name,actions);
init(getMask(actions));
}
......@@ -196,7 +191,6 @@ public final class PropertyPermission extends BasicPermission {
return ((this.mask & that.mask) == that.mask) && super.implies(that);
}
/**
* Checks two PropertyPermission objects for equality. Checks that <i>obj</i> is
* a PropertyPermission, and has the same name and actions as this object.
......@@ -226,16 +220,14 @@ public final class PropertyPermission extends BasicPermission {
*
* @return a hash code value for this object.
*/
public int hashCode() {
return this.getName().hashCode();
}
/**
* Converts an actions String to an actions mask.
*
* @param action the action string.
* @param actions the action string.
* @return the actions mask.
*/
private static int getMask(String actions) {
......@@ -332,8 +324,7 @@ public final class PropertyPermission extends BasicPermission {
*
* @return the canonical string representation of the actions.
*/
static String getActions(int mask)
{
static String getActions(int mask) {
StringBuilder sb = new StringBuilder();
boolean comma = false;
......@@ -359,8 +350,7 @@ public final class PropertyPermission extends BasicPermission {
*
* @return the canonical string representation of the actions.
*/
public String getActions()
{
public String getActions() {
if (actions == null)
actions = getActions(this.mask);
......@@ -373,7 +363,6 @@ public final class PropertyPermission extends BasicPermission {
*
* @return the actions mask.
*/
int getMask() {
return mask;
}
......@@ -386,7 +375,6 @@ public final class PropertyPermission extends BasicPermission {
* @return a new PermissionCollection object suitable for storing
* PropertyPermissions.
*/
public PermissionCollection newPermissionCollection() {
return new PropertyPermissionCollection();
}
......@@ -436,7 +424,7 @@ public final class PropertyPermission extends BasicPermission {
* @serial include
*/
final class PropertyPermissionCollection extends PermissionCollection
implements Serializable
implements Serializable
{
/**
......@@ -454,10 +442,8 @@ implements Serializable
private boolean all_allowed;
/**
* Create an empty PropertyPermissions object.
*
* Create an empty PropertyPermissionCollection object.
*/
public PropertyPermissionCollection() {
perms = new HashMap<>(32); // Capacity for default policy
all_allowed = false;
......@@ -475,9 +461,7 @@ implements Serializable
* @exception SecurityException - if this PropertyPermissionCollection
* object has been marked readonly
*/
public void add(Permission permission)
{
public void add(Permission permission) {
if (! (permission instanceof PropertyPermission))
throw new IllegalArgumentException("invalid permission: "+
permission);
......@@ -514,14 +498,12 @@ implements Serializable
* Check and see if this set of permissions implies the permissions
* expressed in "permission".
*
* @param p the Permission object to compare
* @param permission the Permission object to compare
*
* @return true if "permission" is a proper subset of a permission in
* the set, false if not.
*/
public boolean implies(Permission permission)
{
public boolean implies(Permission permission) {
if (! (permission instanceof PropertyPermission))
return false;
......@@ -655,8 +637,9 @@ implements Serializable
* Reads in a Hashtable of PropertyPermissions and saves them in the
* perms field. Reads in all_allowed.
*/
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
// Don't call defaultReadObject()
// Read in serialized fields
......
......@@ -289,7 +289,7 @@ class RegularEnumSet<E extends Enum<E>> extends EnumSet<E> {
* the same size, and every member of the given set is contained in
* this set.
*
* @param e object to be compared for equality with this set
* @param o object to be compared for equality with this set
* @return <tt>true</tt> if the specified object is equal to this set
*/
public boolean equals(Object o) {
......
......@@ -568,9 +568,8 @@ public final class Scanner implements Iterator<String>, Closeable {
* Constructs a <code>Scanner</code> that returns values scanned
* from the specified source delimited by the specified pattern.
*
* @param source A character source implementing the Readable interface
* @param source A character source implementing the Readable interface
* @param pattern A delimiting pattern
* @return A scanner with the specified source and pattern
*/
private Scanner(Readable source, Pattern pattern) {
assert source != null : "source should not be null";
......
......@@ -213,7 +213,7 @@ public final class ServiceLoader<S>
}
private ServiceLoader(Class<S> svc, ClassLoader cl) {
service = svc;
service = Objects.requireNonNull(svc, "Service interface cannot be null");
loader = cl;
reload();
}
......
......@@ -221,7 +221,7 @@ abstract public class TimeZone implements Serializable, Cloneable {
* @param date the milliseconds (since January 1, 1970,
* 00:00:00.000 GMT) at which the time zone offset and daylight
* saving amount are found
* @param offset an array of int where the raw GMT offset
* @param offsets an array of int where the raw GMT offset
* (offset[0]) and daylight saving amount (offset[1]) are stored,
* or null if those values are not needed. The method assumes that
* the length of the given array is two or larger.
......
......@@ -41,8 +41,8 @@ import java.util.ArrayList;
* @since 1.5
*
* @see javax.management
* @see java.util.Logger
* @see java.util.LogManager
* @see Logger
* @see LogManager
*/
class Logging implements LoggingMXBean {
......
......@@ -92,7 +92,7 @@ class XmlSupport {
* @throws BackingStoreException if preference data cannot be read from
* backing store.
* @throws IllegalStateException if this node (or an ancestor) has been
* removed with the {@link #removeNode()} method.
* removed with the {@link Preferences#removeNode()} method.
*/
static void export(OutputStream os, final Preferences p, boolean subTree)
throws IOException, BackingStoreException {
......
......@@ -136,8 +136,7 @@ final class CryptoAllPermissionCollection extends PermissionCollection
* @exception SecurityException - if this CryptoAllPermissionCollection
* object has been marked readonly
*/
public void add(Permission permission)
{
public void add(Permission permission) {
if (isReadOnly())
throw new SecurityException("attempt to add a Permission to " +
"a readonly PermissionCollection");
......@@ -152,13 +151,12 @@ final class CryptoAllPermissionCollection extends PermissionCollection
* Check and see if this set of permissions implies the permissions
* expressed in "permission".
*
* @param p the Permission object to compare
* @param permission the Permission object to compare
*
* @return true if the given permission is implied by this
* CryptoAllPermissionCollection.
*/
public boolean implies(Permission permission)
{
public boolean implies(Permission permission) {
if (!(permission instanceof CryptoPermission)) {
return false;
}
......
......@@ -471,8 +471,8 @@ class CryptoPermission extends java.security.Permission {
* @author Sharon Liu
*/
final class CryptoPermissionCollection extends PermissionCollection
implements Serializable {
implements Serializable
{
private static final long serialVersionUID = -511215555898802763L;
private Vector<Permission> permissions;
......@@ -493,8 +493,7 @@ implements Serializable {
* @exception SecurityException - if this CryptoPermissionCollection
* object has been marked <i>readOnly</i>.
*/
public void add(Permission permission)
{
public void add(Permission permission) {
if (isReadOnly())
throw new SecurityException("attempt to add a Permission " +
"to a readonly PermissionCollection");
......@@ -506,10 +505,10 @@ implements Serializable {
}
/**
* Check and see if this CryptoPermission object implies
* the given Permission object.
* Check and see if this CryptoPermission object implies
* the given Permission object.
*
* @param p the Permission object to compare
* @param permission the Permission object to compare
*
* @return true if the given permission is implied by this
* CryptoPermissionCollection, false if not.
......@@ -538,8 +537,7 @@ implements Serializable {
* @return an enumeration of all the CryptoPermission objects.
*/
public Enumeration<Permission> elements()
{
public Enumeration<Permission> elements() {
return permissions.elements();
}
}
......@@ -54,7 +54,7 @@ import java.lang.reflect.*;
* @author Sharon Liu
*
* @see java.security.Permissions
* @see java.security.spec.AlgrithomParameterSpec
* @see java.security.spec.AlgorithmParameterSpec
* @see javax.crypto.CryptoPermission
* @see javax.crypto.CryptoAllPermission
* @see javax.crypto.CryptoPermissions
......
......@@ -33,7 +33,7 @@ import java.security.spec.*;
* tranform the plaintext.
*
* @author Li Gong
* @see Nullcipher
* @see NullCipher
*
* @since 1.4
*/
......
......@@ -798,7 +798,7 @@ public class MLet extends java.net.URLClassLoader
* Allows the m-let to perform any operations it needs before being unregistered
* by the MBean server.
*
* @exception java.langException This exception should be caught
* @exception java.lang.Exception This exception should be caught
* by the MBean server and re-thrown as an
* MBeanRegistrationException.
*/
......
......@@ -189,7 +189,7 @@ public class ModelMBeanAttributeInfo
* May be null if the property is write-only.
* @param setter The method used for writing the attribute value.
* May be null if the attribute is read-only.
* @exception IntrospectionException There is a consistency
* @exception javax.management.IntrospectionException There is a consistency
* problem in the definition of this attribute.
*
*/
......@@ -233,7 +233,7 @@ public class ModelMBeanAttributeInfo
* it is null, then a default descriptor will be created. If
* the descriptor does not contain the field "displayName" this field is added
* in the descriptor with its default value.
* @exception IntrospectionException There is a consistency
* @exception javax.management.IntrospectionException There is a consistency
* problem in the definition of this attribute.
* @exception RuntimeOperationsException Wraps an
* IllegalArgumentException. The descriptor is invalid, or descriptor
......
......@@ -124,11 +124,6 @@ public class CompositeDataInvocationHandler implements InvocationHandler {
<p>Construct a handler backed by the given {@code
CompositeData}.</p>
@param mbsc the {@code MBeanServerConnection} related to this
{@code CompositeData}. This is only relevant if a method in
the interface for which this is an invocation handler returns
a type that is an MXBean interface. Otherwise, it can be null.
@param compositeData the {@code CompositeData} that will supply
information to getters.
......
......@@ -416,7 +416,7 @@ public class NamingManager {
* specified.
* See the <code>getObjectInstance</code> method for
* details.
* @param ctx The context relative to which <code>name</code> is
* @param nameCtx The context relative to which <code>name</code> is
* specified, or null for the default initial context.
* See the <code>getObjectInstance</code> method for
* details.
......
......@@ -178,7 +178,6 @@ public final class DelegationPermission extends BasicPermission
*
* @return a hash code value for this object.
*/
public int hashCode() {
return getName().hashCode();
}
......@@ -278,12 +277,11 @@ final class KrbDelegationPermissionCollection extends PermissionCollection
* Check and see if this collection of permissions implies the permissions
* expressed in "permission".
*
* @param p the Permission object to compare
* @param permission the Permission object to compare
*
* @return true if "permission" is a proper subset of a permission in
* the collection, false if not.
*/
public boolean implies(Permission permission) {
if (! (permission instanceof DelegationPermission))
return false;
......@@ -310,7 +308,6 @@ final class KrbDelegationPermissionCollection extends PermissionCollection
* @exception SecurityException - if this PermissionCollection object
* has been marked readonly
*/
public void add(Permission permission) {
if (! (permission instanceof DelegationPermission))
throw new IllegalArgumentException("invalid permission: "+
......@@ -329,7 +326,6 @@ final class KrbDelegationPermissionCollection extends PermissionCollection
*
* @return an enumeration of all the DelegationPermission objects.
*/
public Enumeration<Permission> elements() {
// Convert Iterator into Enumeration
synchronized (this) {
......@@ -376,8 +372,9 @@ final class KrbDelegationPermissionCollection extends PermissionCollection
* Reads in a Vector of DelegationPermissions and saves them in the perms field.
*/
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
// Don't call defaultReadObject()
// Read in serialized fields
......
......@@ -259,7 +259,6 @@ public final class ServicePermission extends Permission
* Always returns present actions in the following order:
* initiate, accept.
*/
public String getActions() {
if (actions == null)
actions = getActions(this.mask);
......@@ -280,7 +279,6 @@ public final class ServicePermission extends Permission
* @return a new PermissionCollection object suitable for storing
* ServicePermissions.
*/
public PermissionCollection newPermissionCollection() {
return new KrbServicePermissionCollection();
}
......@@ -290,7 +288,6 @@ public final class ServicePermission extends Permission
*
* @return the actions mask.
*/
int getMask() {
return mask;
}
......@@ -301,7 +298,6 @@ public final class ServicePermission extends Permission
* @param action the action string
* @return the action mask
*/
private static int getMask(String action) {
if (action == null) {
......@@ -468,12 +464,11 @@ final class KrbServicePermissionCollection extends PermissionCollection
* Check and see if this collection of permissions implies the permissions
* expressed in "permission".
*
* @param p the Permission object to compare
* @param permission the Permission object to compare
*
* @return true if "permission" is a proper subset of a permission in
* the collection, false if not.
*/
public boolean implies(Permission permission) {
if (! (permission instanceof ServicePermission))
return false;
......@@ -517,7 +512,6 @@ final class KrbServicePermissionCollection extends PermissionCollection
* @exception SecurityException - if this PermissionCollection object
* has been marked readonly
*/
public void add(Permission permission) {
if (! (permission instanceof ServicePermission))
throw new IllegalArgumentException("invalid permission: "+
......@@ -584,8 +578,9 @@ final class KrbServicePermissionCollection extends PermissionCollection
* Reads in a Vector of ServicePermissions and saves them in the perms field.
*/
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
// Don't call defaultReadObject()
// Read in serialized fields
......
......@@ -48,7 +48,7 @@ public interface ConnectionPoolDataSource extends CommonDataSource {
* connection to the database that this
* <code>ConnectionPoolDataSource</code> object represents
* @exception SQLException if a database access error occurs
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* @exception java.sql.SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.4
*/
......@@ -64,7 +64,7 @@ public interface ConnectionPoolDataSource extends CommonDataSource {
* connection to the database that this
* <code>ConnectionPoolDataSource</code> object represents
* @exception SQLException if a database access error occurs
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* @exception java.sql.SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.4
*/
......
......@@ -102,7 +102,7 @@ public interface PooledConnection {
* @return a <code>Connection</code> object that is a handle to
* this <code>PooledConnection</code> object
* @exception SQLException if a database access error occurs
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* @exception java.sql.SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.4
*/
......@@ -117,7 +117,7 @@ public interface PooledConnection {
* information.
*
* @exception SQLException if a database access error occurs
* @exception SQLFeatureNotSupportedException if the JDBC driver does not support
* @exception java.sql.SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @since 1.4
*/
......
......@@ -293,7 +293,7 @@ public abstract class SyncProvider {
* SyncProvider.DATASOURCE_TABLE_LOCK,
* SyncProvider.DATASOURCE_DB_LOCK
* </pre>
* @throws SyncProviderExceptiom if an error occurs determining the data
* @throws SyncProviderException if an error occurs determining the data
* source locking level.
* @see #setDataSourceLock
......
/*
* Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1994, 2012, 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
......@@ -36,6 +36,7 @@ import sun.net.www.MeteredStream;
import sun.net.www.ParseUtil;
import sun.net.www.protocol.http.HttpURLConnection;
import sun.util.logging.PlatformLogger;
import static sun.net.www.protocol.http.HttpURLConnection.TunnelState.*;
/**
* @author Herb Jellinek
......@@ -244,16 +245,17 @@ public class HttpClient extends NetworkClient {
*/
public static HttpClient New(URL url)
throws IOException {
return HttpClient.New(url, Proxy.NO_PROXY, -1, true);
return HttpClient.New(url, Proxy.NO_PROXY, -1, true, null);
}
public static HttpClient New(URL url, boolean useCache)
throws IOException {
return HttpClient.New(url, Proxy.NO_PROXY, -1, useCache);
return HttpClient.New(url, Proxy.NO_PROXY, -1, useCache, null);
}
public static HttpClient New(URL url, Proxy p, int to, boolean useCache)
throws IOException {
public static HttpClient New(URL url, Proxy p, int to, boolean useCache,
HttpURLConnection httpuc) throws IOException
{
if (p == null) {
p = Proxy.NO_PROXY;
}
......@@ -261,6 +263,13 @@ public class HttpClient extends NetworkClient {
/* see if one's already around */
if (useCache) {
ret = kac.get(url, null);
if (ret != null && httpuc != null &&
httpuc.streaming() &&
httpuc.getRequestMethod() == "POST") {
if (!ret.available())
ret = null;
}
if (ret != null) {
if ((ret.proxy != null && ret.proxy.equals(p)) ||
(ret.proxy == null && p == null)) {
......@@ -268,6 +277,8 @@ public class HttpClient extends NetworkClient {
ret.cachedHttpClient = true;
assert ret.inCache;
ret.inCache = false;
if (httpuc != null && ret.needsTunneling())
httpuc.setTunnelState(TUNNELING);
PlatformLogger logger = HttpURLConnection.getHttpLogger();
if (logger.isLoggable(PlatformLogger.FINEST)) {
logger.finest("KeepAlive stream retrieved from the cache, " + ret);
......@@ -302,20 +313,25 @@ public class HttpClient extends NetworkClient {
return ret;
}
public static HttpClient New(URL url, Proxy p, int to) throws IOException {
return New(url, p, to, true);
public static HttpClient New(URL url, Proxy p, int to,
HttpURLConnection httpuc) throws IOException
{
return New(url, p, to, true, httpuc);
}
public static HttpClient New(URL url, String proxyHost, int proxyPort,
boolean useCache)
throws IOException {
return New(url, newHttpProxy(proxyHost, proxyPort, "http"), -1, useCache);
return New(url, newHttpProxy(proxyHost, proxyPort, "http"),
-1, useCache, null);
}
public static HttpClient New(URL url, String proxyHost, int proxyPort,
boolean useCache, int to)
boolean useCache, int to,
HttpURLConnection httpuc)
throws IOException {
return New(url, newHttpProxy(proxyHost, proxyPort, "http"), to, useCache);
return New(url, newHttpProxy(proxyHost, proxyPort, "http"),
to, useCache, httpuc);
}
/* return it to the cache as still usable, if:
......@@ -344,6 +360,34 @@ public class HttpClient extends NetworkClient {
}
}
protected synchronized boolean available() throws IOException {
boolean available = true;
int old = serverSocket.getSoTimeout();
serverSocket.setSoTimeout(1);
BufferedInputStream tmpbuf =
new BufferedInputStream(serverSocket.getInputStream());
PlatformLogger logger = HttpURLConnection.getHttpLogger();
try {
int r = tmpbuf.read();
if (r == -1) {
if (logger.isLoggable(PlatformLogger.FINEST)) {
logger.finest("HttpClient.available(): " +
"read returned -1: not available");
}
available = false;
}
} catch (SocketTimeoutException e) {
if (logger.isLoggable(PlatformLogger.FINEST)) {
logger.finest("HttpClient.available(): " +
"SocketTimeout: its available");
}
} finally {
serverSocket.setSoTimeout(old);
}
return available;
}
protected synchronized void putInKeepAliveCache() {
if (inCache) {
assert false : "Duplicate put to keep alive cache";
......
/*
* Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2012, 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
......@@ -351,7 +351,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
private HttpClient reuseClient = null;
/* Tunnel states */
enum TunnelState {
public enum TunnelState {
/* No tunnel */
NONE,
......@@ -662,7 +662,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
*/
protected void setNewClient (URL url, boolean useCache)
throws IOException {
http = HttpClient.New(url, null, -1, useCache, connectTimeout);
http = HttpClient.New(url, null, -1, useCache, connectTimeout, this);
http.setReadTimeout(readTimeout);
}
......@@ -703,7 +703,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
String proxyHost, int proxyPort,
boolean useCache)
throws IOException {
http = HttpClient.New (url, proxyHost, proxyPort, useCache, connectTimeout);
http = HttpClient.New (url, proxyHost, proxyPort, useCache,
connectTimeout, this);
http.setReadTimeout(readTimeout);
}
......@@ -994,14 +995,14 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
// subclass HttpsClient will overwrite & return an instance of HttpsClient
protected HttpClient getNewHttpClient(URL url, Proxy p, int connectTimeout)
throws IOException {
return HttpClient.New(url, p, connectTimeout);
return HttpClient.New(url, p, connectTimeout, this);
}
// subclass HttpsClient will overwrite & return an instance of HttpsClient
protected HttpClient getNewHttpClient(URL url, Proxy p,
int connectTimeout, boolean useCache)
throws IOException {
return HttpClient.New(url, p, connectTimeout, useCache);
return HttpClient.New(url, p, connectTimeout, useCache, this);
}
private void expect100Continue() throws IOException {
......@@ -1144,7 +1145,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
}
}
private boolean streaming () {
public boolean streaming () {
return (fixedContentLength != -1) || (fixedContentLengthLong != -1) ||
(chunkLength != -1);
}
......@@ -1739,7 +1740,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
*
* @param the state
*/
void setTunnelState(TunnelState tunnelState) {
public void setTunnelState(TunnelState tunnelState) {
this.tunnelState = tunnelState;
}
......
......@@ -1059,6 +1059,28 @@ class DatagramChannelImpl
return translateReadyOps(ops, 0, sk);
}
// package-private
int poll(int events, long timeout) throws IOException {
assert Thread.holdsLock(blockingLock()) && !isBlocking();
synchronized (readLock) {
int n = 0;
try {
begin();
synchronized (stateLock) {
if (!isOpen())
return 0;
readerThread = NativeThread.current();
}
n = Net.poll(fd, events, timeout);
} finally {
readerThread = 0;
end(n > 0);
}
return n;
}
}
/**
* Translates an interest operation set into a native poll event set
*/
......
......@@ -176,40 +176,31 @@ public class DatagramSocketAdaptor
return dc.receive(bb);
}
// Implement timeout with a selector
SelectionKey sk = null;
Selector sel = null;
dc.configureBlocking(false);
try {
int n;
SocketAddress sender;
if ((sender = dc.receive(bb)) != null)
return sender;
sel = Util.getTemporarySelector(dc);
sk = dc.register(sel, SelectionKey.OP_READ);
long to = timeout;
for (;;) {
if (!dc.isOpen())
throw new ClosedChannelException();
long st = System.currentTimeMillis();
int ns = sel.select(to);
if (ns > 0 && sk.isReadable()) {
int result = dc.poll(PollArrayWrapper.POLLIN, to);
if (result > 0 &&
((result & PollArrayWrapper.POLLIN) != 0)) {
if ((sender = dc.receive(bb)) != null)
return sender;
}
sel.selectedKeys().remove(sk);
to -= System.currentTimeMillis() - st;
if (to <= 0)
throw new SocketTimeoutException();
}
} finally {
if (sk != null)
sk.cancel();
if (dc.isOpen())
dc.configureBlocking(true);
if (sel != null)
Util.releaseTemporarySelector(sel);
}
}
......
......@@ -409,6 +409,9 @@ public class Net {
int level, int opt, int arg)
throws IOException;
static native int poll(FileDescriptor fd, int events, long timeout)
throws IOException;
// -- Multicast support --
......
......@@ -102,37 +102,26 @@ public class ServerSocketAdaptor // package-private
return sc.socket();
}
// Implement timeout with a selector
SelectionKey sk = null;
Selector sel = null;
ssc.configureBlocking(false);
try {
SocketChannel sc;
if ((sc = ssc.accept()) != null)
return sc.socket();
sel = Util.getTemporarySelector(ssc);
sk = ssc.register(sel, SelectionKey.OP_ACCEPT);
long to = timeout;
for (;;) {
if (!ssc.isOpen())
throw new ClosedChannelException();
long st = System.currentTimeMillis();
int ns = sel.select(to);
if (ns > 0 &&
sk.isAcceptable() && ((sc = ssc.accept()) != null))
int result = ssc.poll(PollArrayWrapper.POLLIN, to);
if (result > 0 && ((sc = ssc.accept()) != null))
return sc.socket();
sel.selectedKeys().remove(sk);
to -= System.currentTimeMillis() - st;
if (to <= 0)
throw new SocketTimeoutException();
}
} finally {
if (sk != null)
sk.cancel();
if (ssc.isOpen())
ssc.configureBlocking(true);
if (sel != null)
Util.releaseTemporarySelector(sel);
}
} catch (Exception x) {
......
......@@ -324,6 +324,28 @@ class ServerSocketChannelImpl
return translateReadyOps(ops, 0, sk);
}
// package-private
int poll(int events, long timeout) throws IOException {
assert Thread.holdsLock(blockingLock()) && !isBlocking();
synchronized (lock) {
int n = 0;
try {
begin();
synchronized (stateLock) {
if (!isOpen())
return 0;
thread = NativeThread.current();
}
n = Net.poll(fd, events, timeout);
} finally {
thread = 0;
end(n > 0);
}
return n;
}
}
/**
* Translates an interest operation set into a native poll event set
*/
......
......@@ -97,25 +97,19 @@ public class SocketAdaptor
return;
}
// Implement timeout with a selector
SelectionKey sk = null;
Selector sel = null;
sc.configureBlocking(false);
try {
if (sc.connect(remote))
return;
sel = Util.getTemporarySelector(sc);
sk = sc.register(sel, SelectionKey.OP_CONNECT);
long to = timeout;
for (;;) {
if (!sc.isOpen())
throw new ClosedChannelException();
long st = System.currentTimeMillis();
int ns = sel.select(to);
if (ns > 0 &&
sk.isConnectable() && sc.finishConnect())
int result = sc.poll(PollArrayWrapper.POLLCONN, to);
if (result > 0 && sc.finishConnect())
break;
sel.selectedKeys().remove(sk);
to -= System.currentTimeMillis() - st;
if (to <= 0) {
try {
......@@ -125,12 +119,8 @@ public class SocketAdaptor
}
}
} finally {
if (sk != null)
sk.cancel();
if (sc.isOpen())
sc.configureBlocking(true);
if (sel != null)
Util.releaseTemporarySelector(sel);
}
} catch (Exception x) {
......@@ -199,39 +189,29 @@ public class SocketAdaptor
throw new IllegalBlockingModeException();
if (timeout == 0)
return sc.read(bb);
// Implement timeout with a selector
SelectionKey sk = null;
Selector sel = null;
sc.configureBlocking(false);
try {
int n;
if ((n = sc.read(bb)) != 0)
return n;
sel = Util.getTemporarySelector(sc);
sk = sc.register(sel, SelectionKey.OP_READ);
long to = timeout;
for (;;) {
if (!sc.isOpen())
throw new ClosedChannelException();
long st = System.currentTimeMillis();
int ns = sel.select(to);
if (ns > 0 && sk.isReadable()) {
int result = sc.poll(PollArrayWrapper.POLLIN, to);
if (result > 0) {
if ((n = sc.read(bb)) != 0)
return n;
}
sel.selectedKeys().remove(sk);
to -= System.currentTimeMillis() - st;
if (to <= 0)
throw new SocketTimeoutException();
}
} finally {
if (sk != null)
sk.cancel();
if (sc.isOpen())
sc.configureBlocking(true);
if (sel != null)
Util.releaseTemporarySelector(sel);
}
}
......
......@@ -914,6 +914,28 @@ class SocketChannelImpl
return translateReadyOps(ops, 0, sk);
}
// package-private
int poll(int events, long timeout) throws IOException {
assert Thread.holdsLock(blockingLock()) && !isBlocking();
synchronized (readLock) {
int n = 0;
try {
begin();
synchronized (stateLock) {
if (!isOpen())
return 0;
readerThread = NativeThread.current();
}
n = Net.poll(fd, events, timeout);
} finally {
readerCleanup();
end(n > 0);
}
return n;
}
}
/**
* Translates an interest operation set into a native poll event set
*/
......
......@@ -218,66 +218,6 @@ public class Util {
((DirectBuffer)buf).cleaner().clean();
}
private static class SelectorWrapper {
private Selector sel;
private SelectorWrapper (Selector sel) {
this.sel = sel;
Cleaner.create(this, new Closer(sel));
}
private static class Closer implements Runnable {
private Selector sel;
private Closer (Selector sel) {
this.sel = sel;
}
public void run () {
try {
sel.close();
} catch (Throwable th) {
throw new Error(th);
}
}
}
public Selector get() { return sel;}
}
// Per-thread cached selector
private static ThreadLocal<SoftReference<SelectorWrapper>> localSelector
= new ThreadLocal<SoftReference<SelectorWrapper>>();
// Hold a reference to the selWrapper object to prevent it from
// being cleaned when the temporary selector wrapped is on lease.
private static ThreadLocal<SelectorWrapper> localSelectorWrapper
= new ThreadLocal<SelectorWrapper>();
// When finished, invoker must ensure that selector is empty
// by cancelling any related keys and explicitly releasing
// the selector by invoking releaseTemporarySelector()
static Selector getTemporarySelector(SelectableChannel sc)
throws IOException
{
SoftReference<SelectorWrapper> ref = localSelector.get();
SelectorWrapper selWrapper = null;
Selector sel = null;
if (ref == null
|| ((selWrapper = ref.get()) == null)
|| ((sel = selWrapper.get()) == null)
|| (sel.provider() != sc.provider())) {
sel = sc.provider().openSelector();
selWrapper = new SelectorWrapper(sel);
localSelector.set(new SoftReference<SelectorWrapper>(selWrapper));
}
localSelectorWrapper.set(selWrapper);
return sel;
}
static void releaseTemporarySelector(Selector sel)
throws IOException
{
// Selector should be empty
sel.selectNow(); // Flush cancelled keys
assert sel.keys().isEmpty() : "Temporary selector not empty";
localSelectorWrapper.set(null);
}
// -- Random stuff --
......
......@@ -193,9 +193,9 @@ final class P11Cipher extends CipherSpi {
} else { // DES, DESede, Blowfish
blockSize = 8;
}
this.blockMode =
(algoParts.length > 1 ? parseMode(algoParts[1]) : MODE_ECB);
}
this.blockMode =
(algoParts.length > 1 ? parseMode(algoParts[1]) : MODE_ECB);
String defPadding = (blockSize == 0 ? "NoPadding" : "PKCS5Padding");
String paddingStr =
(algoParts.length > 2 ? algoParts[2] : defPadding);
......
......@@ -82,7 +82,9 @@ implements java.security.interfaces.DSAKeyPairGenerator {
}
public void initialize(int modlen, SecureRandom random) {
initialize(modlen, false, random);
// generate new parameters when no precomputed ones available.
initialize(modlen, true, random);
this.forceNewParameters = false;
}
/**
......
......@@ -116,12 +116,13 @@ public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {
throw new InvalidAlgorithmParameterException("Invalid parameter");
}
DSAGenParameterSpec dsaGenParams = (DSAGenParameterSpec) genParamSpec;
if (dsaGenParams.getPrimePLength() > 2048) {
int primePLen = dsaGenParams.getPrimePLength();
if (primePLen > 2048) {
throw new InvalidParameterException
("Prime size should be 512 - 1024, or 2048");
("No support for prime size " + primePLen);
}
// directly initialize using the already validated values
this.valueL = dsaGenParams.getPrimePLength();
this.valueL = primePLen;
this.valueN = dsaGenParams.getSubprimeQLength();
this.seedLen = dsaGenParams.getSeedLength();
this.random = random;
......
......@@ -146,9 +146,14 @@ public final class ParameterCache {
InvalidAlgorithmParameterException {
AlgorithmParameterGenerator gen =
AlgorithmParameterGenerator.getInstance("DSA");
DSAGenParameterSpec genParams =
new DSAGenParameterSpec(primeLen, subprimeLen);
gen.init(genParams, random);
// Use init(int size, SecureRandom random) for legacy DSA key sizes
if (primeLen < 1024) {
gen.init(primeLen, random);
} else {
DSAGenParameterSpec genParams =
new DSAGenParameterSpec(primeLen, subprimeLen);
gen.init(genParams, random);
}
AlgorithmParameters params = gen.generateParameters();
DSAParameterSpec spec = params.getParameterSpec(DSAParameterSpec.class);
return spec;
......@@ -159,8 +164,9 @@ public final class ParameterCache {
dsaCache = new ConcurrentHashMap<Integer,DSAParameterSpec>();
/*
* We support precomputed parameter for 512, 768 and 1024 bit
* moduli. In this file we provide both the seed and counter
* We support precomputed parameter for legacy 512, 768 bit moduli,
* and (L, N) combinations of (1024, 160), (2048, 224), (2048, 256).
* In this file we provide both the seed and counter
* value of the generation process for each of these seeds,
* for validation purposes. We also include the test vectors
* from the DSA specification, FIPS 186, and the FIPS 186
......
/*
* Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2012, 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
......@@ -132,7 +132,7 @@ public abstract class HandshakeMessage {
*/
final void write(HandshakeOutStream s) throws IOException {
int len = messageLength();
if (len > (1 << 24)) {
if (len >= Record.OVERFLOW_OF_INT24) {
throw new SSLException("Handshake message too big"
+ ", type = " + messageType() + ", len = " + len);
}
......
/*
* Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2012, 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
......@@ -153,10 +153,12 @@ public class HandshakeOutStream extends OutputStream {
*/
void putInt8(int i) throws IOException {
checkOverflow(i, Record.OVERFLOW_OF_INT08);
r.write(i);
}
void putInt16(int i) throws IOException {
checkOverflow(i, Record.OVERFLOW_OF_INT16);
if (r.availableDataBytes() < 2) {
flush();
}
......@@ -165,6 +167,7 @@ public class HandshakeOutStream extends OutputStream {
}
void putInt24(int i) throws IOException {
checkOverflow(i, Record.OVERFLOW_OF_INT24);
if (r.availableDataBytes() < 3) {
flush();
}
......@@ -191,6 +194,8 @@ public class HandshakeOutStream extends OutputStream {
if (b == null) {
putInt8(0);
return;
} else {
checkOverflow(b.length, Record.OVERFLOW_OF_INT08);
}
putInt8(b.length);
write(b, 0, b.length);
......@@ -200,6 +205,8 @@ public class HandshakeOutStream extends OutputStream {
if (b == null) {
putInt16(0);
return;
} else {
checkOverflow(b.length, Record.OVERFLOW_OF_INT16);
}
putInt16(b.length);
write(b, 0, b.length);
......@@ -209,8 +216,19 @@ public class HandshakeOutStream extends OutputStream {
if (b == null) {
putInt24(0);
return;
} else {
checkOverflow(b.length, Record.OVERFLOW_OF_INT24);
}
putInt24(b.length);
write(b, 0, b.length);
}
private void checkOverflow(int length, int overflow) {
if (length >= overflow) {
// internal_error alert will be triggered
throw new RuntimeException(
"Field length overflow, the field length (" +
length + ") should be less than " + overflow);
}
}
}
/*
* Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2012, 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
......@@ -110,4 +110,10 @@ interface Record {
+ maxPadding // padding
+ trailerSize; // MAC
/*
* The overflow values of integers of 8, 16 and 24 bits.
*/
static final int OVERFLOW_OF_INT08 = (1 << 8);
static final int OVERFLOW_OF_INT16 = (1 << 16);
static final int OVERFLOW_OF_INT24 = (1 << 24);
}
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2012, 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
......@@ -31,6 +31,11 @@ package sun.text;
*/
public final class SupplementaryCharacterData implements Cloneable {
/**
* A token used as a character-category value to identify ignore characters
*/
private static final byte IGNORE = -1;
/**
* An array for supplementary characters and values.
* Lower one byte is used to keep a byte-value.
......@@ -78,7 +83,8 @@ public final class SupplementaryCharacterData implements Cloneable {
} else if (index > (end-1)) {
i = k;
} else {
return dataTable[k] & 0xFF;
int v = dataTable[k] & 0xFF;
return (v == 0xFF) ? IGNORE : v;
}
}
}
......
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.util.locale;
import java.util.HashMap;
import java.util.Map;
/**
* Locale equivalent map for BCP47 Locale matching
*/
final class LocaleEquivalentMaps {
static final Map<String, String> singleEquivMap;
static final Map<String, String[]> multiEquivsMap;
static final Map<String, String> regionVariantEquivMap;
static {
singleEquivMap = new HashMap<>();
multiEquivsMap = new HashMap<>();
regionVariantEquivMap = new HashMap<>();
// This is an auto-generated file and should not be manually edited.
// LSR Revision: 2012-09-04
singleEquivMap.put("ami", "i-ami");
singleEquivMap.put("art-lojban", "jbo");
singleEquivMap.put("ase", "sgn-us");
singleEquivMap.put("ayx", "nun");
singleEquivMap.put("bfi", "sgn-gb");
singleEquivMap.put("bjd", "drl");
singleEquivMap.put("bnn", "i-bnn");
singleEquivMap.put("bzs", "sgn-br");
singleEquivMap.put("cjr", "mom");
singleEquivMap.put("cka", "cmr");
singleEquivMap.put("cmk", "xch");
singleEquivMap.put("cmn-hans", "zh-cmn-hans");
singleEquivMap.put("cmn-hant", "zh-cmn-hant");
singleEquivMap.put("cmr", "cka");
singleEquivMap.put("csn", "sgn-co");
singleEquivMap.put("dev", "gav");
singleEquivMap.put("drh", "khk");
singleEquivMap.put("drl", "bjd");
singleEquivMap.put("dse", "sgn-nl");
singleEquivMap.put("dsl", "sgn-dk");
singleEquivMap.put("fsl", "sgn-fr");
singleEquivMap.put("gan", "zh-gan");
singleEquivMap.put("gav", "dev");
singleEquivMap.put("gsg", "sgn-de");
singleEquivMap.put("gss", "sgn-gr");
singleEquivMap.put("he", "iw");
singleEquivMap.put("hle", "sca");
singleEquivMap.put("hrr", "jal");
singleEquivMap.put("hsn", "zh-xiang");
singleEquivMap.put("i-ami", "ami");
singleEquivMap.put("i-bnn", "bnn");
singleEquivMap.put("i-klingon", "tlh");
singleEquivMap.put("i-lux", "lb");
singleEquivMap.put("i-navajo", "nv");
singleEquivMap.put("i-pwn", "pwn");
singleEquivMap.put("i-tao", "tao");
singleEquivMap.put("i-tay", "tay");
singleEquivMap.put("i-tsu", "tsu");
singleEquivMap.put("ibi", "opa");
singleEquivMap.put("id", "in");
singleEquivMap.put("in", "id");
singleEquivMap.put("ise", "sgn-it");
singleEquivMap.put("isg", "sgn-ie");
singleEquivMap.put("iw", "he");
singleEquivMap.put("jal", "hrr");
singleEquivMap.put("jbo", "art-lojban");
singleEquivMap.put("ji", "yi");
singleEquivMap.put("jsl", "sgn-jp");
singleEquivMap.put("jv", "jw");
singleEquivMap.put("jw", "jv");
singleEquivMap.put("kgh", "kml");
singleEquivMap.put("khk", "drh");
singleEquivMap.put("kml", "kgh");
singleEquivMap.put("lb", "i-lux");
singleEquivMap.put("lcq", "ppr");
singleEquivMap.put("lrr", "yma");
singleEquivMap.put("mfs", "sgn-mx");
singleEquivMap.put("mo", "ro");
singleEquivMap.put("mom", "cjr");
singleEquivMap.put("nan", "zh-min-nan");
singleEquivMap.put("nb", "no-bok");
singleEquivMap.put("ncs", "sgn-ni");
singleEquivMap.put("nn", "no-nyn");
singleEquivMap.put("no-bok", "nb");
singleEquivMap.put("no-nyn", "nn");
singleEquivMap.put("nsl", "sgn-no");
singleEquivMap.put("nun", "ayx");
singleEquivMap.put("nv", "i-navajo");
singleEquivMap.put("opa", "ibi");
singleEquivMap.put("ppr", "lcq");
singleEquivMap.put("psr", "sgn-pt");
singleEquivMap.put("pwn", "i-pwn");
singleEquivMap.put("ras", "tie");
singleEquivMap.put("ro", "mo");
singleEquivMap.put("sca", "hle");
singleEquivMap.put("sfb", "sgn-be-fr");
singleEquivMap.put("sfs", "sgn-za");
singleEquivMap.put("sgg", "sgn-ch-de");
singleEquivMap.put("sgn-be-fr", "sfb");
singleEquivMap.put("sgn-be-nl", "vgt");
singleEquivMap.put("sgn-br", "bzs");
singleEquivMap.put("sgn-ch-de", "sgg");
singleEquivMap.put("sgn-co", "csn");
singleEquivMap.put("sgn-de", "gsg");
singleEquivMap.put("sgn-dk", "dsl");
singleEquivMap.put("sgn-es", "ssp");
singleEquivMap.put("sgn-fr", "fsl");
singleEquivMap.put("sgn-gb", "bfi");
singleEquivMap.put("sgn-gr", "gss");
singleEquivMap.put("sgn-ie", "isg");
singleEquivMap.put("sgn-it", "ise");
singleEquivMap.put("sgn-jp", "jsl");
singleEquivMap.put("sgn-mx", "mfs");
singleEquivMap.put("sgn-ni", "ncs");
singleEquivMap.put("sgn-nl", "dse");
singleEquivMap.put("sgn-no", "nsl");
singleEquivMap.put("sgn-pt", "psr");
singleEquivMap.put("sgn-se", "swl");
singleEquivMap.put("sgn-us", "ase");
singleEquivMap.put("sgn-za", "sfs");
singleEquivMap.put("ssp", "sgn-es");
singleEquivMap.put("swl", "sgn-se");
singleEquivMap.put("tao", "i-tao");
singleEquivMap.put("tay", "i-tay");
singleEquivMap.put("tie", "ras");
singleEquivMap.put("tkk", "twm");
singleEquivMap.put("tlh", "i-klingon");
singleEquivMap.put("tlw", "weo");
singleEquivMap.put("tsu", "i-tsu");
singleEquivMap.put("twm", "tkk");
singleEquivMap.put("vgt", "sgn-be-nl");
singleEquivMap.put("weo", "tlw");
singleEquivMap.put("wuu", "zh-wuu");
singleEquivMap.put("xch", "cmk");
singleEquivMap.put("yi", "ji");
singleEquivMap.put("yma", "lrr");
singleEquivMap.put("yue", "zh-yue");
singleEquivMap.put("zh-cmn-hans", "cmn-hans");
singleEquivMap.put("zh-cmn-hant", "cmn-hant");
singleEquivMap.put("zh-gan", "gan");
singleEquivMap.put("zh-min-nan", "nan");
singleEquivMap.put("zh-wuu", "wuu");
singleEquivMap.put("zh-xiang", "hsn");
singleEquivMap.put("zh-yue", "yue");
multiEquivsMap.put("ccq", new String[] {"rki", "ybd"});
multiEquivsMap.put("cmn", new String[] {"zh-guoyu", "zh-cmn"});
multiEquivsMap.put("drw", new String[] {"prs", "tnf"});
multiEquivsMap.put("hak", new String[] {"i-hak", "zh-hakka"});
multiEquivsMap.put("i-hak", new String[] {"hak", "zh-hakka"});
multiEquivsMap.put("mry", new String[] {"mst", "myt"});
multiEquivsMap.put("mst", new String[] {"mry", "myt"});
multiEquivsMap.put("myt", new String[] {"mry", "mst"});
multiEquivsMap.put("prs", new String[] {"drw", "tnf"});
multiEquivsMap.put("rki", new String[] {"ccq", "ybd"});
multiEquivsMap.put("tnf", new String[] {"prs", "drw"});
multiEquivsMap.put("ybd", new String[] {"rki", "ccq"});
multiEquivsMap.put("zh-cmn", new String[] {"cmn", "zh-guoyu"});
multiEquivsMap.put("zh-guoyu", new String[] {"cmn", "zh-cmn"});
multiEquivsMap.put("zh-hakka", new String[] {"hak", "i-hak"});
regionVariantEquivMap.put("-alalc97", "-heploc");
regionVariantEquivMap.put("-bu", "-mm");
regionVariantEquivMap.put("-cd", "-zr");
regionVariantEquivMap.put("-dd", "-de");
regionVariantEquivMap.put("-de", "-dd");
regionVariantEquivMap.put("-fr", "-fx");
regionVariantEquivMap.put("-fx", "-fr");
regionVariantEquivMap.put("-heploc", "-alalc97");
regionVariantEquivMap.put("-mm", "-bu");
regionVariantEquivMap.put("-tl", "-tp");
regionVariantEquivMap.put("-tp", "-tl");
regionVariantEquivMap.put("-yd", "-ye");
regionVariantEquivMap.put("-ye", "-yd");
regionVariantEquivMap.put("-zr", "-cd");
}
}
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.util.locale;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Locale.*;
import static java.util.Locale.FilteringMode.*;
import static java.util.Locale.LanguageRange.*;
import java.util.Map;
import java.util.Set;
/**
* Implementation for BCP47 Locale matching
*
*/
public final class LocaleMatcher {
public static List<Locale> filter(List<LanguageRange> priorityList,
Collection<Locale> locales,
FilteringMode mode) {
if (priorityList.isEmpty() || locales.isEmpty()) {
return new ArrayList<>(); // need to return a empty mutable List
}
// Create a list of language tags to be matched.
List<String> tags = new ArrayList<>();
for (Locale locale : locales) {
tags.add(locale.toLanguageTag());
}
// Filter language tags.
List<String> filteredTags = filterTags(priorityList, tags, mode);
// Create a list of matching locales.
List<Locale> filteredLocales = new ArrayList<>(filteredTags.size());
for (String tag : filteredTags) {
filteredLocales.add(Locale.forLanguageTag(tag));
}
return filteredLocales;
}
public static List<String> filterTags(List<LanguageRange> priorityList,
Collection<String> tags,
FilteringMode mode) {
if (priorityList.isEmpty() || tags.isEmpty()) {
return new ArrayList<>(); // need to return a empty mutable List
}
ArrayList<LanguageRange> list;
if (mode == EXTENDED_FILTERING) {
return filterExtended(priorityList, tags);
} else {
list = new ArrayList<>();
for (LanguageRange lr : priorityList) {
String range = lr.getRange();
if (range.startsWith("*-")
|| range.indexOf("-*") != -1) { // Extended range
if (mode == AUTOSELECT_FILTERING) {
return filterExtended(priorityList, tags);
} else if (mode == MAP_EXTENDED_RANGES) {
if (range.charAt(0) == '*') {
range = "*";
} else {
range = range.replaceAll("-[*]", "");
}
list.add(new LanguageRange(range, lr.getWeight()));
} else if (mode == REJECT_EXTENDED_RANGES) {
throw new IllegalArgumentException("An extended range \""
+ range
+ "\" found in REJECT_EXTENDED_RANGES mode.");
}
} else { // Basic range
list.add(lr);
}
}
return filterBasic(list, tags);
}
}
private static List<String> filterBasic(List<LanguageRange> priorityList,
Collection<String> tags) {
List<String> list = new ArrayList<>();
for (LanguageRange lr : priorityList) {
String range = lr.getRange();
if (range.equals("*")) {
return new ArrayList<String>(tags);
} else {
for (String tag : tags) {
tag = tag.toLowerCase();
if (tag.startsWith(range)) {
int len = range.length();
if ((tag.length() == len || tag.charAt(len) == '-')
&& !list.contains(tag)) {
list.add(tag);
}
}
}
}
}
return list;
}
private static List<String> filterExtended(List<LanguageRange> priorityList,
Collection<String> tags) {
List<String> list = new ArrayList<>();
for (LanguageRange lr : priorityList) {
String range = lr.getRange();
if (range.equals("*")) {
return new ArrayList<String>(tags);
}
String[] rangeSubtags = range.split("-");
for (String tag : tags) {
tag = tag.toLowerCase();
String[] tagSubtags = tag.split("-");
if (!rangeSubtags[0].equals(tagSubtags[0])
&& !rangeSubtags[0].equals("*")) {
continue;
}
int rangeIndex = 1;
int tagIndex = 1;
while (rangeIndex < rangeSubtags.length
&& tagIndex < tagSubtags.length) {
if (rangeSubtags[rangeIndex].equals("*")) {
rangeIndex++;
} else if (rangeSubtags[rangeIndex].equals(tagSubtags[tagIndex])) {
rangeIndex++;
tagIndex++;
} else if (tagSubtags[tagIndex].length() == 1
&& !tagSubtags[tagIndex].equals("*")) {
break;
} else {
tagIndex++;
}
}
if (rangeSubtags.length == rangeIndex && !list.contains(tag)) {
list.add(tag);
}
}
}
return list;
}
public static Locale lookup(List<LanguageRange> priorityList,
Collection<Locale> locales) {
if (priorityList.isEmpty() || locales.isEmpty()) {
return null;
}
// Create a list of language tags to be matched.
List<String> tags = new ArrayList<>();
for (Locale locale : locales) {
tags.add(locale.toLanguageTag());
}
// Look up a language tags.
String lookedUpTag = lookupTag(priorityList, tags);
if (lookedUpTag == null) {
return null;
} else {
return Locale.forLanguageTag(lookedUpTag);
}
}
public static String lookupTag(List<LanguageRange> priorityList,
Collection<String> tags) {
if (priorityList.isEmpty() || tags.isEmpty()) {
return null;
}
for (LanguageRange lr : priorityList) {
String range = lr.getRange();
// Special language range ("*") is ignored in lookup.
if (range.equals("*")) {
continue;
}
String rangeForRegex = range.replaceAll("\\x2A", "\\\\p{Alnum}*");
while (rangeForRegex.length() > 0) {
for (String tag : tags) {
tag = tag.toLowerCase();
if (tag.matches(rangeForRegex)) {
return tag;
}
}
// Truncate from the end....
int index = rangeForRegex.lastIndexOf('-');
if (index >= 0) {
rangeForRegex = rangeForRegex.substring(0, index);
// if range ends with an extension key, truncate it.
if (rangeForRegex.lastIndexOf('-') == rangeForRegex.length()-2) {
rangeForRegex =
rangeForRegex.substring(0, rangeForRegex.length()-2);
}
} else {
rangeForRegex = "";
}
}
}
return null;
}
public static List<LanguageRange> parse(String ranges) {
ranges = ranges.replaceAll(" ", "").toLowerCase();
if (ranges.startsWith("accept-language:")) {
ranges = ranges.substring(16); // delete unnecessary prefix
}
String[] langRanges = ranges.split(",");
List<LanguageRange> list = new ArrayList<>(langRanges.length);
List<String> tempList = new ArrayList<>();
int numOfRanges = 0;
for (String range : langRanges) {
int index;
String r;
double w;
if ((index = range.indexOf(";q=")) == -1) {
r = range;
w = MAX_WEIGHT;
} else {
r = range.substring(0, index);
index += 3;
try {
w = Double.parseDouble(range.substring(index));
}
catch (Exception e) {
throw new IllegalArgumentException("weight=\""
+ range.substring(index)
+ "\" for language range \"" + r + "\"");
}
if (w < MIN_WEIGHT || w > MAX_WEIGHT) {
throw new IllegalArgumentException("weight=" + w
+ " for language range \"" + r
+ "\". It must be between " + MIN_WEIGHT
+ " and " + MAX_WEIGHT + ".");
}
}
if (!tempList.contains(r)) {
LanguageRange lr = new LanguageRange(r, w);
index = numOfRanges;
for (int j = 0; j < numOfRanges; j++) {
if (list.get(j).getWeight() < w) {
index = j;
break;
}
}
list.add(index, lr);
numOfRanges++;
tempList.add(r);
// Check if the range has an equivalent using IANA LSR data.
// If yes, add it to the User's Language Priority List as well.
// aa-XX -> aa-YY
String equivalent;
if ((equivalent = getEquivalentForRegionAndVariant(r)) != null
&& !tempList.contains(equivalent)) {
list.add(index+1, new LanguageRange(equivalent, w));
numOfRanges++;
tempList.add(equivalent);
}
String[] equivalents;
if ((equivalents = getEquivalentsForLanguage(r)) != null) {
for (String equiv: equivalents) {
// aa-XX -> bb-XX(, cc-XX)
if (!tempList.contains(equiv)) {
list.add(index+1, new LanguageRange(equiv, w));
numOfRanges++;
tempList.add(equiv);
}
// bb-XX -> bb-YY(, cc-YY)
equivalent = getEquivalentForRegionAndVariant(equiv);
if (equivalent != null
&& !tempList.contains(equivalent)) {
list.add(index+1, new LanguageRange(equivalent, w));
numOfRanges++;
tempList.add(equivalent);
}
}
}
}
}
return list;
}
private static String[] getEquivalentsForLanguage(String range) {
String r = range;
while (r.length() > 0) {
if (LocaleEquivalentMaps.singleEquivMap.containsKey(r)) {
String equiv = LocaleEquivalentMaps.singleEquivMap.get(r);
// Return immediately for performance if the first matching
// subtag is found.
return new String[] {range.replaceFirst(r, equiv)};
} else if (LocaleEquivalentMaps.multiEquivsMap.containsKey(r)) {
String[] equivs = LocaleEquivalentMaps.multiEquivsMap.get(r);
for (int i = 0; i < equivs.length; i++) {
equivs[i] = range.replaceFirst(r, equivs[i]);
}
return equivs;
}
// Truncate the last subtag simply.
int index = r.lastIndexOf('-');
if (index == -1) {
break;
}
r = r.substring(0, index);
}
return null;
}
private static String getEquivalentForRegionAndVariant(String range) {
int extensionKeyIndex = getExtentionKeyIndex(range);
for (String subtag : LocaleEquivalentMaps.regionVariantEquivMap.keySet()) {
int index;
if ((index = range.indexOf(subtag)) != -1) {
// Check if the matching text is a valid region or variant.
if (extensionKeyIndex != Integer.MIN_VALUE
&& index > extensionKeyIndex) {
continue;
}
int len = index + subtag.length();
if (range.length() == len || range.charAt(len) == '-') {
return range.replaceFirst(subtag, LocaleEquivalentMaps.regionVariantEquivMap.get(subtag));
}
}
}
return null;
}
private static int getExtentionKeyIndex(String s) {
char[] c = s.toCharArray();
int index = Integer.MIN_VALUE;
for (int i = 1; i < c.length; i++) {
if (c[i] == '-') {
if (i - index == 2) {
return index;
} else {
index = i;
}
}
}
return Integer.MIN_VALUE;
}
public static List<LanguageRange> mapEquivalents(
List<LanguageRange>priorityList,
Map<String, List<String>> map) {
if (priorityList.isEmpty()) {
return new ArrayList<>(); // need to return a empty mutable List
}
if (map == null || map.isEmpty()) {
return new ArrayList<LanguageRange>(priorityList);
}
// Create a map, key=originalKey.toLowerCaes(), value=originalKey
Map<String, String> keyMap = new HashMap<>();
for (String key : map.keySet()) {
keyMap.put(key.toLowerCase(), key);
}
List<LanguageRange> list = new ArrayList<>();
for (LanguageRange lr : priorityList) {
String range = lr.getRange();
String r = range;
boolean hasEquivalent = false;
while (r.length() > 0) {
if (keyMap.containsKey(r)) {
hasEquivalent = true;
List<String> equivalents = map.get(keyMap.get(r));
if (equivalents != null) {
int len = r.length();
for (String equivalent : equivalents) {
list.add(new LanguageRange(equivalent.toLowerCase()
+ range.substring(len),
lr.getWeight()));
}
}
// Return immediately if the first matching subtag is found.
break;
}
// Truncate the last subtag simply.
int index = r.lastIndexOf('-');
if (index == -1) {
break;
}
r = r.substring(0, index);
}
if (!hasEquivalent) {
list.add(lr);
}
}
return list;
}
private LocaleMatcher() {}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册