提交 78874f27 编写于 作者: L lana

Merge

...@@ -413,6 +413,7 @@ JAVA_JAVA_java = \ ...@@ -413,6 +413,7 @@ JAVA_JAVA_java = \
java/io/FilePermission.java \ java/io/FilePermission.java \
java/io/Serializable.java \ java/io/Serializable.java \
java/io/Externalizable.java \ java/io/Externalizable.java \
java/io/SerialCallbackContext.java \
java/io/Bits.java \ java/io/Bits.java \
java/io/ObjectInput.java \ java/io/ObjectInput.java \
java/io/ObjectInputStream.java \ java/io/ObjectInputStream.java \
......
...@@ -148,14 +148,9 @@ include $(BUILDDIR)/common/Library.gmk ...@@ -148,14 +148,9 @@ include $(BUILDDIR)/common/Library.gmk
# #
ifeq ($(PLATFORM), windows) ifeq ($(PLATFORM), windows)
STATIC_LIBRARY_DIR = $(OBJDIR)/static STATIC_LIBRARY = $(OBJDIR)/static/$(LIBPREFIX)$(LIBRARY).lib
STATIC_LIBRARY_NAME = $(LIBPREFIX)$(LIBRARY).lib
STATIC_LIBRARY = $(STATIC_LIBRARY_DIR)/$(STATIC_LIBRARY_NAME)
$(STATIC_LIBRARY_DIR): $(OBJDIR) $(STATIC_LIBRARY): $(FILES_o)
@$(MKDIR) $(STATIC_LIBRARY_DIR)
$(STATIC_LIBRARY): $(STATIC_LIBRARY_DIR)
@$(prep-target) @$(prep-target)
$(LIBEXE) -nologo -out:$@ $(FILES_o) $(LIBEXE) -nologo -out:$@ $(FILES_o)
......
...@@ -33,7 +33,6 @@ FILES_src = \ ...@@ -33,7 +33,6 @@ FILES_src = \
java/nio/channels/AsynchronousByteChannel.java \ java/nio/channels/AsynchronousByteChannel.java \
java/nio/channels/AsynchronousChannel.java \ java/nio/channels/AsynchronousChannel.java \
java/nio/channels/AsynchronousChannelGroup.java \ java/nio/channels/AsynchronousChannelGroup.java \
java/nio/channels/AsynchronousDatagramChannel.java \
java/nio/channels/AsynchronousFileChannel.java \ java/nio/channels/AsynchronousFileChannel.java \
java/nio/channels/AsynchronousServerSocketChannel.java \ java/nio/channels/AsynchronousServerSocketChannel.java \
java/nio/channels/AsynchronousSocketChannel.java \ java/nio/channels/AsynchronousSocketChannel.java \
...@@ -207,7 +206,6 @@ FILES_src = \ ...@@ -207,7 +206,6 @@ FILES_src = \
sun/nio/ch/SelChImpl.java \ sun/nio/ch/SelChImpl.java \
sun/nio/ch/ServerSocketAdaptor.java \ sun/nio/ch/ServerSocketAdaptor.java \
sun/nio/ch/ServerSocketChannelImpl.java \ sun/nio/ch/ServerSocketChannelImpl.java \
sun/nio/ch/SimpleAsynchronousDatagramChannelImpl.java \
sun/nio/ch/SinkChannelImpl.java \ sun/nio/ch/SinkChannelImpl.java \
sun/nio/ch/SocketAdaptor.java \ sun/nio/ch/SocketAdaptor.java \
sun/nio/ch/SocketChannelImpl.java \ sun/nio/ch/SocketChannelImpl.java \
......
...@@ -53,7 +53,7 @@ FILES_export = \ ...@@ -53,7 +53,7 @@ FILES_export = \
# #
# Extra cc/linker flags. # Extra cc/linker flags.
# #
LDLIBS += dsound.lib winmm.lib user32.lib LDLIBS += dsound.lib winmm.lib user32.lib ole32.lib
CPPFLAGS += \ CPPFLAGS += \
-DUSE_DAUDIO=TRUE \ -DUSE_DAUDIO=TRUE \
-I$(SHARE_SRC)/native/com/sun/media/sound \ -I$(SHARE_SRC)/native/com/sun/media/sound \
......
...@@ -48,8 +48,8 @@ jar.jmx.name = jmx.jar ...@@ -48,8 +48,8 @@ jar.jmx.name = jmx.jar
jar.jmx.sealed = true jar.jmx.sealed = true
jar.jmx.spec.title = JSR 003, 160, 255 - JMX API jar.jmx.spec.title = JSR 003, 160, 255 - JMX API
jar.jmx.spec.version = ${project.spec.version} jar.jmx.spec.version = ${project.spec.version}
jar.jmx.spec.vendor = Sun Microsystems, Inc. jar.jmx.spec.vendor = Oracle Corporation
jar.jmx.impl.title = JSR 003, 160, 255 - OpenJDK 7 JMX API jar.jmx.impl.title = JSR 003, 160, 255 - OpenJDK 7 JMX API
jar.jmx.impl.vendor = Project OpenJDK jar.jmx.impl.vendor = Project OpenJDK
javadoc.options=-J-Xmx256m javadoc.options=-J-Xmx256m
...@@ -21,4 +21,4 @@ ...@@ -21,4 +21,4 @@
# or visit www.oracle.com if you need additional information or have any # or visit www.oracle.com if you need additional information or have any
# questions. # questions.
# #
tzdata2010l tzdata2010o
...@@ -569,8 +569,8 @@ Rule HK 1953 only - Nov 1 3:30 0 - ...@@ -569,8 +569,8 @@ Rule HK 1953 only - Nov 1 3:30 0 -
Rule HK 1954 1964 - Mar Sun>=18 3:30 1:00 S Rule HK 1954 1964 - Mar Sun>=18 3:30 1:00 S
Rule HK 1954 only - Oct 31 3:30 0 - Rule HK 1954 only - Oct 31 3:30 0 -
Rule HK 1955 1964 - Nov Sun>=1 3:30 0 - Rule HK 1955 1964 - Nov Sun>=1 3:30 0 -
Rule HK 1965 1977 - Apr Sun>=16 3:30 1:00 S Rule HK 1965 1976 - Apr Sun>=16 3:30 1:00 S
Rule HK 1965 1977 - Oct Sun>=16 3:30 0 - Rule HK 1965 1976 - Oct Sun>=16 3:30 0 -
Rule HK 1973 only - Dec 30 3:30 1:00 S Rule HK 1973 only - Dec 30 3:30 1:00 S
Rule HK 1979 only - May Sun>=8 3:30 1:00 S Rule HK 1979 only - May Sun>=8 3:30 1:00 S
Rule HK 1979 only - Oct Sun>=16 3:30 0 - Rule HK 1979 only - Oct Sun>=16 3:30 0 -
......
...@@ -306,13 +306,26 @@ Zone Indian/Cocos 6:27:40 - LMT 1900 ...@@ -306,13 +306,26 @@ Zone Indian/Cocos 6:27:40 - LMT 1900
# http://www.timeanddate.com/news/time/fiji-dst-ends-march-2010.html # http://www.timeanddate.com/news/time/fiji-dst-ends-march-2010.html
# </a> # </a>
# From Alexander Krivenyshev (2010-10-24):
# According to Radio Fiji and Fiji Times online, Fiji will end DST 3
# weeks earlier than expected - on March 6, 2011, not March 27, 2011...
# Here is confirmation from Government of the Republic of the Fiji Islands,
# Ministry of Information (fiji.gov.fj) web site:
# <a href="http://www.fiji.gov.fj/index.php?option=com_content&view=article&id=2608:daylight-savings&catid=71:press-releases&Itemid=155">
# http://www.fiji.gov.fj/index.php?option=com_content&view=article&id=2608:daylight-savings&catid=71:press-releases&Itemid=155
# </a>
# or
# <a href="http://www.worldtimezone.com/dst_news/dst_news_fiji04.html">
# http://www.worldtimezone.com/dst_news/dst_news_fiji04.html
# </a>
# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S
Rule Fiji 1998 1999 - Nov Sun>=1 2:00 1:00 S Rule Fiji 1998 1999 - Nov Sun>=1 2:00 1:00 S
Rule Fiji 1999 2000 - Feb lastSun 3:00 0 - Rule Fiji 1999 2000 - Feb lastSun 3:00 0 -
Rule Fiji 2009 only - Nov 29 2:00 1:00 S Rule Fiji 2009 only - Nov 29 2:00 1:00 S
Rule Fiji 2010 only - Mar lastSun 3:00 0 - Rule Fiji 2010 only - Mar lastSun 3:00 0 -
Rule Fiji 2010 only - Oct 24 2:00 1:00 S Rule Fiji 2010 only - Oct 24 2:00 1:00 S
Rule Fiji 2011 only - Mar lastSun 3:00 0 - Rule Fiji 2011 only - Mar Sun>=1 3:00 0 -
# Zone NAME GMTOFF RULES FORMAT [UNTIL] # Zone NAME GMTOFF RULES FORMAT [UNTIL]
Zone Pacific/Fiji 11:53:40 - LMT 1915 Oct 26 # Suva Zone Pacific/Fiji 11:53:40 - LMT 1915 Oct 26 # Suva
12:00 Fiji FJ%sT # Fiji Time 12:00 Fiji FJ%sT # Fiji Time
...@@ -509,11 +522,21 @@ Zone Pacific/Pago_Pago 12:37:12 - LMT 1879 Jul 5 ...@@ -509,11 +522,21 @@ Zone Pacific/Pago_Pago 12:37:12 - LMT 1879 Jul 5
# http://www.parliament.gov.ws/documents/acts/Daylight%20Saving%20Act%20%202009%20%28English%29%20-%20Final%207-7-091.pdf # http://www.parliament.gov.ws/documents/acts/Daylight%20Saving%20Act%20%202009%20%28English%29%20-%20Final%207-7-091.pdf
# </a> # </a>
# From Raymond Hughes (2010-10-07):
# Please see
# <a href="http://www.mcil.gov.ws">
# http://www.mcil.gov.ws
# </a>,
# the Ministry of Commerce, Industry and Labour (sideframe) "Last Sunday
# September 2010 (26/09/10) - adjust clocks forward from 12:00 midnight
# to 01:00am and First Sunday April 2011 (03/04/11) - adjust clocks
# backwards from 1:00am to 12:00am"
Zone Pacific/Apia 12:33:04 - LMT 1879 Jul 5 Zone Pacific/Apia 12:33:04 - LMT 1879 Jul 5
-11:26:56 - LMT 1911 -11:26:56 - LMT 1911
-11:30 - SAMT 1950 # Samoa Time -11:30 - SAMT 1950 # Samoa Time
-11:00 - WST 2010 Sep 26 -11:00 - WST 2010 Sep 26
-11:00 1:00 WSDT 2011 Apr 3 -11:00 1:00 WSDT 2011 Apr 3 1:00
-11:00 - WST -11:00 - WST
# Solomon Is # Solomon Is
......
...@@ -63,7 +63,7 @@ AQ -6448-06406 Antarctica/Palmer Palmer Station, Anvers Island ...@@ -63,7 +63,7 @@ AQ -6448-06406 Antarctica/Palmer Palmer Station, Anvers Island
AQ -6736+06253 Antarctica/Mawson Mawson Station, Holme Bay AQ -6736+06253 Antarctica/Mawson Mawson Station, Holme Bay
AQ -6835+07758 Antarctica/Davis Davis Station, Vestfold Hills AQ -6835+07758 Antarctica/Davis Davis Station, Vestfold Hills
AQ -6617+11031 Antarctica/Casey Casey Station, Bailey Peninsula AQ -6617+11031 Antarctica/Casey Casey Station, Bailey Peninsula
AQ -7824+10654 Antarctica/Vostok Vostok Station, S Magnetic Pole AQ -7824+10654 Antarctica/Vostok Vostok Station, Lake Vostok
AQ -6640+14001 Antarctica/DumontDUrville Dumont-d'Urville Station, Terre Adelie AQ -6640+14001 Antarctica/DumontDUrville Dumont-d'Urville Station, Terre Adelie
AQ -690022+0393524 Antarctica/Syowa Syowa Station, E Ongul I AQ -690022+0393524 Antarctica/Syowa Syowa Station, E Ongul I
AQ -5430+15857 Antarctica/Macquarie Macquarie Island Station, Macquarie Island AQ -5430+15857 Antarctica/Macquarie Macquarie Island Station, Macquarie Island
......
...@@ -355,7 +355,6 @@ JavaMain(void * _args) ...@@ -355,7 +355,6 @@ JavaMain(void * _args)
JavaVM *vm = 0; JavaVM *vm = 0;
JNIEnv *env = 0; JNIEnv *env = 0;
jstring mainClassName;
jclass mainClass; jclass mainClass;
jmethodID mainID; jmethodID mainID;
jobjectArray mainArgs; jobjectArray mainArgs;
......
...@@ -72,7 +72,7 @@ inflate_file(int fd, zentry *entry, int *size_out) ...@@ -72,7 +72,7 @@ inflate_file(int fd, zentry *entry, int *size_out)
if (entry->how == STORED) { if (entry->how == STORED) {
*(char *)((size_t)in + entry->csize) = '\0'; *(char *)((size_t)in + entry->csize) = '\0';
if (size_out) { if (size_out) {
*size_out = entry->csize; *size_out = (int)entry->csize;
} }
return (in); return (in);
} else if (entry->how == DEFLATED) { } else if (entry->how == DEFLATED) {
...@@ -103,7 +103,7 @@ inflate_file(int fd, zentry *entry, int *size_out) ...@@ -103,7 +103,7 @@ inflate_file(int fd, zentry *entry, int *size_out)
return (NULL); return (NULL);
} }
if (size_out) { if (size_out) {
*size_out = entry->isize; *size_out = (int)entry->isize;
} }
return (out); return (out);
} else } else
...@@ -317,7 +317,7 @@ find_file(int fd, zentry *entry, const char *file_name) ...@@ -317,7 +317,7 @@ find_file(int fd, zentry *entry, const char *file_name)
* manifest. If so, build the entry record from the data found in * manifest. If so, build the entry record from the data found in
* the header located and return success. * the header located and return success.
*/ */
if (CENNAM(p) == JLI_StrLen(file_name) && if ((size_t)CENNAM(p) == JLI_StrLen(file_name) &&
memcmp((p + CENHDR), file_name, JLI_StrLen(file_name)) == 0) { memcmp((p + CENHDR), file_name, JLI_StrLen(file_name)) == 0) {
if (lseek(fd, base_offset + CENOFF(p), SEEK_SET) < (off_t)0) { if (lseek(fd, base_offset + CENOFF(p), SEEK_SET) < (off_t)0) {
free(buffer); free(buffer);
...@@ -606,8 +606,5 @@ JLI_ManifestIterate(const char *jarfile, attribute_closure ac, void *user_data) ...@@ -606,8 +606,5 @@ JLI_ManifestIterate(const char *jarfile, attribute_closure ac, void *user_data)
} }
free(mp); free(mp);
close(fd); close(fd);
if (rc == 0) return (rc == 0) ? 0 : -2;
return (0);
else
return (-2);
} }
...@@ -290,12 +290,12 @@ FileList_join(FileList fl, char sep) ...@@ -290,12 +290,12 @@ FileList_join(FileList fl, char sep)
char *path; char *path;
char *p; char *p;
for (i = 0, size = 1; i < fl->size; i++) for (i = 0, size = 1; i < fl->size; i++)
size += JLI_StrLen(fl->files[i]) + 1; size += (int)JLI_StrLen(fl->files[i]) + 1;
path = JLI_MemAlloc(size); path = JLI_MemAlloc(size);
for (i = 0, p = path; i < fl->size; i++) { for (i = 0, p = path; i < fl->size; i++) {
int len = JLI_StrLen(fl->files[i]); int len = (int)JLI_StrLen(fl->files[i]);
if (i > 0) *p++ = sep; if (i > 0) *p++ = sep;
memcpy(p, fl->files[i], len); memcpy(p, fl->files[i], len);
p += len; p += len;
...@@ -309,7 +309,7 @@ static FileList ...@@ -309,7 +309,7 @@ static FileList
FileList_split(const char *path, char sep) FileList_split(const char *path, char sep)
{ {
const char *p, *q; const char *p, *q;
int len = JLI_StrLen(path); int len = (int)JLI_StrLen(path);
int count; int count;
FileList fl; FileList fl;
for (count = 1, p = path; p < path + len; p++) for (count = 1, p = path; p < path + len; p++)
...@@ -330,7 +330,7 @@ FileList_split(const char *path, char sep) ...@@ -330,7 +330,7 @@ FileList_split(const char *path, char sep)
static int static int
isJarFileName(const char *filename) isJarFileName(const char *filename)
{ {
int len = JLI_StrLen(filename); int len = (int)JLI_StrLen(filename);
return (len >= 4) && return (len >= 4) &&
(filename[len - 4] == '.') && (filename[len - 4] == '.') &&
(equal(filename + len - 3, "jar") || (equal(filename + len - 3, "jar") ||
...@@ -342,8 +342,8 @@ isJarFileName(const char *filename) ...@@ -342,8 +342,8 @@ isJarFileName(const char *filename)
static char * static char *
wildcardConcat(const char *wildcard, const char *basename) wildcardConcat(const char *wildcard, const char *basename)
{ {
int wildlen = JLI_StrLen(wildcard); int wildlen = (int)JLI_StrLen(wildcard);
int baselen = JLI_StrLen(basename); int baselen = (int)JLI_StrLen(basename);
char *filename = (char *) JLI_MemAlloc(wildlen + baselen); char *filename = (char *) JLI_MemAlloc(wildlen + baselen);
/* Replace the trailing '*' with basename */ /* Replace the trailing '*' with basename */
memcpy(filename, wildcard, wildlen-1); memcpy(filename, wildcard, wildlen-1);
...@@ -369,7 +369,7 @@ wildcardFileList(const char *wildcard) ...@@ -369,7 +369,7 @@ wildcardFileList(const char *wildcard)
static int static int
isWildcard(const char *filename) isWildcard(const char *filename)
{ {
int len = JLI_StrLen(filename); int len = (int)JLI_StrLen(filename);
return (len > 0) && return (len > 0) &&
(filename[len - 1] == '*') && (filename[len - 1] == '*') &&
(len == 1 || IS_FILE_SEPARATOR(filename[len - 2])) && (len == 1 || IS_FILE_SEPARATOR(filename[len - 2])) &&
......
/* /*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -253,7 +253,8 @@ final class AESCrypt extends SymmetricCipher implements AESConstants ...@@ -253,7 +253,8 @@ final class AESCrypt extends SymmetricCipher implements AESConstants
for (j = 0; j < 8; j++) { for (j = 0; j < 8; j++) {
if (AA[i][j] != 0) { if (AA[i][j] != 0) {
AA[i][j] = (byte) AA[i][j] = (byte)
alog[(255 + log[AA[i][j] & 0xFF] - log[pivot & 0xFF]) % 255]; alog[(255 + log[AA[i][j] & 0xFF] - log[pivot & 0xFF])
% 255];
} }
} }
for (t = 0; t < 4; t++) { for (t = 0; t < 4; t++) {
......
/* /*
* Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -92,7 +92,8 @@ public final class ARCFOURCipher extends CipherSpi { ...@@ -92,7 +92,8 @@ public final class ARCFOURCipher extends CipherSpi {
} }
// core crypt code. OFB style, so works for both encryption and decryption // core crypt code. OFB style, so works for both encryption and decryption
private void crypt(byte[] in, int inOfs, int inLen, byte[] out, int outOfs) { private void crypt(byte[] in, int inOfs, int inLen, byte[] out,
int outOfs) {
if (is < 0) { if (is < 0) {
// doFinal() was called, need to reset the cipher to initial state // doFinal() was called, need to reset the cipher to initial state
init(lastKey); init(lastKey);
......
/* /*
* Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -31,8 +31,8 @@ import javax.crypto.*; ...@@ -31,8 +31,8 @@ import javax.crypto.*;
import javax.crypto.spec.*; import javax.crypto.spec.*;
/** /**
* This class implements the DESede algorithm (DES-EDE, tripleDES) in its various * This class implements the DESede algorithm (DES-EDE, tripleDES) in
* modes (<code>ECB</code>, <code>CFB</code>, <code>OFB</code>, * its various modes (<code>ECB</code>, <code>CFB</code>, <code>OFB</code>,
* <code>CBC</code>, <code>PCBC</code>) and padding schemes * <code>CBC</code>, <code>PCBC</code>) and padding schemes
* (<code>PKCS5Padding</code>, <code>NoPadding</code>, * (<code>PKCS5Padding</code>, <code>NoPadding</code>,
* <code>ISO10126Padding</code>). * <code>ISO10126Padding</code>).
......
/* /*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -190,7 +190,8 @@ javax.crypto.interfaces.DHPrivateKey, Serializable { ...@@ -190,7 +190,8 @@ javax.crypto.interfaces.DHPrivateKey, Serializable {
ike.initCause(e); ike.initCause(e);
throw ike; throw ike;
} catch (IOException e) { } catch (IOException e) {
InvalidKeyException ike = new InvalidKeyException("Error parsing key encoding: " + e.getMessage()); InvalidKeyException ike = new InvalidKeyException(
"Error parsing key encoding: " + e.getMessage());
ike.initCause(e); ike.initCause(e);
throw ike; throw ike;
} }
...@@ -300,7 +301,8 @@ javax.crypto.interfaces.DHPrivateKey, Serializable { ...@@ -300,7 +301,8 @@ javax.crypto.interfaces.DHPrivateKey, Serializable {
DerInputStream in = new DerInputStream(this.key); DerInputStream in = new DerInputStream(this.key);
this.x = in.getBigInteger(); this.x = in.getBigInteger();
} catch (IOException e) { } catch (IOException e) {
InvalidKeyException ike = new InvalidKeyException("Error parsing key encoding: " + e.getMessage()); InvalidKeyException ike = new InvalidKeyException(
"Error parsing key encoding: " + e.getMessage());
ike.initCause(e); ike.initCause(e);
throw ike; throw ike;
} }
......
/* /*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -180,7 +180,8 @@ javax.crypto.interfaces.DHPublicKey, Serializable { ...@@ -180,7 +180,8 @@ javax.crypto.interfaces.DHPublicKey, Serializable {
throw new InvalidKeyException("Private-value length too big"); throw new InvalidKeyException("Private-value length too big");
} catch (IOException e) { } catch (IOException e) {
throw new InvalidKeyException("Error parsing key encoding: " + e.toString()); throw new InvalidKeyException(
"Error parsing key encoding: " + e.toString());
} }
} }
...@@ -281,7 +282,8 @@ javax.crypto.interfaces.DHPublicKey, Serializable { ...@@ -281,7 +282,8 @@ javax.crypto.interfaces.DHPublicKey, Serializable {
DerInputStream in = new DerInputStream(this.key); DerInputStream in = new DerInputStream(this.key);
this.y = in.getBigInteger(); this.y = in.getBigInteger();
} catch (IOException e) { } catch (IOException e) {
throw new InvalidKeyException("Error parsing key encoding: " + e.toString()); throw new InvalidKeyException(
"Error parsing key encoding: " + e.toString());
} }
} }
......
/* /*
* Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -764,7 +764,8 @@ public final class JceKeyStore extends KeyStoreSpi { ...@@ -764,7 +764,8 @@ public final class JceKeyStore extends KeyStoreSpi {
cf = (CertificateFactory)cfs.get(certType); cf = (CertificateFactory)cfs.get(certType);
} else { } else {
// create new certificate factory // create new certificate factory
cf = CertificateFactory.getInstance(certType); cf = CertificateFactory.getInstance(
certType);
// store the certificate factory so we can // store the certificate factory so we can
// reuse it later // reuse it later
cfs.put(certType, cf); cfs.put(certType, cf);
...@@ -863,8 +864,9 @@ public final class JceKeyStore extends KeyStoreSpi { ...@@ -863,8 +864,9 @@ public final class JceKeyStore extends KeyStoreSpi {
dis.readFully(actual); dis.readFully(actual);
for (int i = 0; i < computed.length; i++) { for (int i = 0; i < computed.length; i++) {
if (computed[i] != actual[i]) { if (computed[i] != actual[i]) {
throw new IOException("Keystore was tampered with, or " throw new IOException(
+ "password was incorrect"); "Keystore was tampered with, or "
+ "password was incorrect");
} }
} }
} }
......
/* /*
* Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -139,7 +139,8 @@ public final class OAEPParameters extends AlgorithmParametersSpi { ...@@ -139,7 +139,8 @@ public final class OAEPParameters extends AlgorithmParametersSpi {
if (!val.getOID().equals((Object) OID_MGF1)) { if (!val.getOID().equals((Object) OID_MGF1)) {
throw new IOException("Only MGF1 mgf is supported"); throw new IOException("Only MGF1 mgf is supported");
} }
AlgorithmId params = AlgorithmId.parse(new DerValue(val.getEncodedParams())); AlgorithmId params = AlgorithmId.parse(
new DerValue(val.getEncodedParams()));
String mgfDigestName = convertToStandardName(params.getName()); String mgfDigestName = convertToStandardName(params.getName());
if (mgfDigestName.equals("SHA-1")) { if (mgfDigestName.equals("SHA-1")) {
mgfSpec = MGF1ParameterSpec.SHA1; mgfSpec = MGF1ParameterSpec.SHA1;
...@@ -150,7 +151,8 @@ public final class OAEPParameters extends AlgorithmParametersSpi { ...@@ -150,7 +151,8 @@ public final class OAEPParameters extends AlgorithmParametersSpi {
} else if (mgfDigestName.equals("SHA-512")) { } else if (mgfDigestName.equals("SHA-512")) {
mgfSpec = MGF1ParameterSpec.SHA512; mgfSpec = MGF1ParameterSpec.SHA512;
} else { } else {
throw new IOException("Unrecognized message digest algorithm"); throw new IOException(
"Unrecognized message digest algorithm");
} }
} else if (data.isContextSpecific((byte) 0x02)) { } else if (data.isContextSpecific((byte) 0x02)) {
// pSource algid // pSource algid
......
/* /*
* Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -121,8 +121,8 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey { ...@@ -121,8 +121,8 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey {
this.key = deriveKey(prf, passwdBytes, salt, iterCount, keyLength); this.key = deriveKey(prf, passwdBytes, salt, iterCount, keyLength);
} }
private static byte[] deriveKey(final Mac prf, final byte[] password, byte[] salt, private static byte[] deriveKey(final Mac prf, final byte[] password,
int iterCount, int keyLengthInBit) { byte[] salt, int iterCount, int keyLengthInBit) {
int keyLength = keyLengthInBit/8; int keyLength = keyLengthInBit/8;
byte[] key = new byte[keyLength]; byte[] key = new byte[keyLength];
try { try {
...@@ -155,8 +155,9 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey { ...@@ -155,8 +155,9 @@ final class PBKDF2KeyImpl implements javax.crypto.interfaces.PBEKey {
if (this == obj) return true; if (this == obj) return true;
if (this.getClass() != obj.getClass()) return false; if (this.getClass() != obj.getClass()) return false;
SecretKey sk = (SecretKey)obj; SecretKey sk = (SecretKey)obj;
return prf.getAlgorithm().equalsIgnoreCase(sk.getAlgorithm()) && return prf.getAlgorithm().equalsIgnoreCase(
Arrays.equals(password, sk.getEncoded()); sk.getAlgorithm()) &&
Arrays.equals(password, sk.getEncoded());
} }
}; };
prf.init(macKey); prf.init(macKey);
......
/* /*
* Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -206,7 +206,8 @@ final class PKCS12PBECipherCore { ...@@ -206,7 +206,8 @@ final class PKCS12PBECipherCore {
(algo.equalsIgnoreCase("RC2")?"RC2_40":algo), "SunJCE"); (algo.equalsIgnoreCase("RC2")?"RC2_40":algo), "SunJCE");
} catch (GeneralSecurityException gse) { } catch (GeneralSecurityException gse) {
// should never happen // should never happen
throw new RuntimeException("SunJCE provider is not configured properly"); throw new RuntimeException(
"SunJCE provider is not configured properly");
} }
try { try {
params.init(pbeSpec); params.init(pbeSpec);
...@@ -316,7 +317,8 @@ final class PKCS12PBECipherCore { ...@@ -316,7 +317,8 @@ final class PKCS12PBECipherCore {
try { try {
paramSpec = params.getParameterSpec(PBEParameterSpec.class); paramSpec = params.getParameterSpec(PBEParameterSpec.class);
} catch (InvalidParameterSpecException ipse) { } catch (InvalidParameterSpecException ipse) {
throw new InvalidAlgorithmParameterException("requires PBE parameters"); throw new InvalidAlgorithmParameterException(
"requires PBE parameters");
} }
} }
implInit(opmode, key, paramSpec, random); implInit(opmode, key, paramSpec, random);
......
/* /*
* Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -423,15 +423,31 @@ public final class SunJCE extends Provider { ...@@ -423,15 +423,31 @@ public final class SunJCE extends Provider {
/* /*
* SSL/TLS mechanisms * SSL/TLS mechanisms
*
* These are strictly internal implementations and may
* be changed at any time. These names were chosen
* because PKCS11/SunPKCS11 does not yet have TLS1.2
* mechanisms, and it will cause calls to come here.
*/ */
put("KeyGenerator.SunTlsPrf", put("KeyGenerator.SunTlsPrf",
"com.sun.crypto.provider.TlsPrfGenerator"); "com.sun.crypto.provider.TlsPrfGenerator$V10");
put("KeyGenerator.SunTlsRsaPremasterSecret", put("KeyGenerator.SunTls12Prf",
"com.sun.crypto.provider.TlsRsaPremasterSecretGenerator"); "com.sun.crypto.provider.TlsPrfGenerator$V12");
put("KeyGenerator.SunTlsMasterSecret", put("KeyGenerator.SunTlsMasterSecret",
"com.sun.crypto.provider.TlsMasterSecretGenerator"); "com.sun.crypto.provider.TlsMasterSecretGenerator");
put("Alg.Alias.KeyGenerator.SunTls12MasterSecret",
"SunTlsMasterSecret");
put("KeyGenerator.SunTlsKeyMaterial", put("KeyGenerator.SunTlsKeyMaterial",
"com.sun.crypto.provider.TlsKeyMaterialGenerator"); "com.sun.crypto.provider.TlsKeyMaterialGenerator");
put("Alg.Alias.KeyGenerator.SunTls12KeyMaterial",
"SunTlsKeyMaterial");
put("KeyGenerator.SunTlsRsaPremasterSecret",
"com.sun.crypto.provider.TlsRsaPremasterSecretGenerator");
put("Alg.Alias.KeyGenerator.SunTls12RsaPremasterSecret",
"SunTlsRsaPremasterSecret");
return null; return null;
} }
......
/* /*
* Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -65,12 +65,14 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi { ...@@ -65,12 +65,14 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi {
} }
this.spec = (TlsKeyMaterialParameterSpec)params; this.spec = (TlsKeyMaterialParameterSpec)params;
if ("RAW".equals(spec.getMasterSecret().getFormat()) == false) { if ("RAW".equals(spec.getMasterSecret().getFormat()) == false) {
throw new InvalidAlgorithmParameterException("Key format must be RAW"); throw new InvalidAlgorithmParameterException(
"Key format must be RAW");
} }
protocolVersion = (spec.getMajorVersion() << 8) | spec.getMinorVersion(); protocolVersion = (spec.getMajorVersion() << 8)
if ((protocolVersion < 0x0300) || (protocolVersion > 0x0302)) { | spec.getMinorVersion();
throw new InvalidAlgorithmParameterException if ((protocolVersion < 0x0300) || (protocolVersion > 0x0303)) {
("Only SSL 3.0, TLS 1.0, and TLS 1.1 supported"); throw new InvalidAlgorithmParameterException(
"Only SSL 3.0, TLS 1.0/1.1/1.2 supported");
} }
} }
...@@ -80,8 +82,8 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi { ...@@ -80,8 +82,8 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi {
protected SecretKey engineGenerateKey() { protected SecretKey engineGenerateKey() {
if (spec == null) { if (spec == null) {
throw new IllegalStateException throw new IllegalStateException(
("TlsKeyMaterialGenerator must be initialized"); "TlsKeyMaterialGenerator must be initialized");
} }
try { try {
return engineGenerateKey0(); return engineGenerateKey0();
...@@ -99,8 +101,8 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi { ...@@ -99,8 +101,8 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi {
SecretKey clientMacKey = null; SecretKey clientMacKey = null;
SecretKey serverMacKey = null; SecretKey serverMacKey = null;
SecretKey clientCipherKey = null; SecretKey clientCipherKey = null;
IvParameterSpec clientIv = null;
SecretKey serverCipherKey = null; SecretKey serverCipherKey = null;
IvParameterSpec clientIv = null;
IvParameterSpec serverIv = null; IvParameterSpec serverIv = null;
int macLength = spec.getMacKeyLength(); int macLength = spec.getMacKeyLength();
...@@ -109,21 +111,33 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi { ...@@ -109,21 +111,33 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi {
int keyLength = spec.getCipherKeyLength(); int keyLength = spec.getCipherKeyLength();
int ivLength = spec.getIvLength(); int ivLength = spec.getIvLength();
int keyBlockLen = macLength + keyLength + (isExportable ? 0 : ivLength); int keyBlockLen = macLength + keyLength
+ (isExportable ? 0 : ivLength);
keyBlockLen <<= 1; keyBlockLen <<= 1;
byte[] keyBlock = new byte[keyBlockLen]; byte[] keyBlock = new byte[keyBlockLen];
MessageDigest md5 = MessageDigest.getInstance("MD5"); // These may be used again later for exportable suite calculations.
MessageDigest sha = MessageDigest.getInstance("SHA1"); MessageDigest md5 = null;
MessageDigest sha = null;
// generate key block // generate key block
if (protocolVersion >= 0x0301) { if (protocolVersion >= 0x0303) {
// TLS // TLS 1.2
byte[] seed = concat(serverRandom, clientRandom);
keyBlock = doTLS12PRF(masterSecret, LABEL_KEY_EXPANSION, seed,
keyBlockLen, spec.getPRFHashAlg(),
spec.getPRFHashLength(), spec.getPRFBlockSize());
} else if (protocolVersion >= 0x0301) {
// TLS 1.0/1.1
md5 = MessageDigest.getInstance("MD5");
sha = MessageDigest.getInstance("SHA1");
byte[] seed = concat(serverRandom, clientRandom); byte[] seed = concat(serverRandom, clientRandom);
keyBlock = doPRF(masterSecret, LABEL_KEY_EXPANSION, seed, keyBlock = doTLS10PRF(masterSecret, LABEL_KEY_EXPANSION, seed,
keyBlockLen, md5, sha); keyBlockLen, md5, sha);
} else { } else {
// SSL // SSL
md5 = MessageDigest.getInstance("MD5");
sha = MessageDigest.getInstance("SHA1");
keyBlock = new byte[keyBlockLen]; keyBlock = new byte[keyBlockLen];
byte[] tmp = new byte[20]; byte[] tmp = new byte[20];
...@@ -169,6 +183,7 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi { ...@@ -169,6 +183,7 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi {
String alg = spec.getCipherAlgorithm(); String alg = spec.getCipherAlgorithm();
// cipher keys
byte[] clientKeyBytes = new byte[keyLength]; byte[] clientKeyBytes = new byte[keyLength];
System.arraycopy(keyBlock, ofs, clientKeyBytes, 0, keyLength); System.arraycopy(keyBlock, ofs, clientKeyBytes, 0, keyLength);
ofs += keyLength; ofs += keyLength;
...@@ -182,6 +197,7 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi { ...@@ -182,6 +197,7 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi {
clientCipherKey = new SecretKeySpec(clientKeyBytes, alg); clientCipherKey = new SecretKeySpec(clientKeyBytes, alg);
serverCipherKey = new SecretKeySpec(serverKeyBytes, alg); serverCipherKey = new SecretKeySpec(serverKeyBytes, alg);
// IV keys if needed.
if (ivLength != 0) { if (ivLength != 0) {
tmp = new byte[ivLength]; tmp = new byte[ivLength];
...@@ -194,21 +210,28 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi { ...@@ -194,21 +210,28 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi {
serverIv = new IvParameterSpec(tmp); serverIv = new IvParameterSpec(tmp);
} }
} else { } else {
// if exportable suites, calculate the alternate
// cipher key expansion and IV generation // cipher key expansion and IV generation
if (protocolVersion >= 0x0301) { if (protocolVersion >= 0x0302) {
// TLS 1.1+
throw new RuntimeException(
"Internal Error: TLS 1.1+ should not be negotiating" +
"exportable ciphersuites");
} else if (protocolVersion == 0x0301) {
// TLS 1.0
byte[] seed = concat(clientRandom, serverRandom); byte[] seed = concat(clientRandom, serverRandom);
tmp = doPRF(clientKeyBytes, LABEL_CLIENT_WRITE_KEY, seed, tmp = doTLS10PRF(clientKeyBytes, LABEL_CLIENT_WRITE_KEY, seed,
expandedKeyLength, md5, sha); expandedKeyLength, md5, sha);
clientCipherKey = new SecretKeySpec(tmp, alg); clientCipherKey = new SecretKeySpec(tmp, alg);
tmp = doPRF(serverKeyBytes, LABEL_SERVER_WRITE_KEY, seed, tmp = doTLS10PRF(serverKeyBytes, LABEL_SERVER_WRITE_KEY, seed,
expandedKeyLength, md5, sha); expandedKeyLength, md5, sha);
serverCipherKey = new SecretKeySpec(tmp, alg); serverCipherKey = new SecretKeySpec(tmp, alg);
if (ivLength != 0) { if (ivLength != 0) {
tmp = new byte[ivLength]; tmp = new byte[ivLength];
byte[] block = doPRF(null, LABEL_IV_BLOCK, seed, byte[] block = doTLS10PRF(null, LABEL_IV_BLOCK, seed,
ivLength << 1, md5, sha); ivLength << 1, md5, sha);
System.arraycopy(block, 0, tmp, 0, ivLength); System.arraycopy(block, 0, tmp, 0, ivLength);
clientIv = new IvParameterSpec(tmp); clientIv = new IvParameterSpec(tmp);
...@@ -216,6 +239,7 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi { ...@@ -216,6 +239,7 @@ public final class TlsKeyMaterialGenerator extends KeyGeneratorSpi {
serverIv = new IvParameterSpec(tmp); serverIv = new IvParameterSpec(tmp);
} }
} else { } else {
// SSLv3
tmp = new byte[expandedKeyLength]; tmp = new byte[expandedKeyLength];
md5.update(clientKeyBytes); md5.update(clientKeyBytes);
......
/* /*
* Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -64,12 +64,14 @@ public final class TlsMasterSecretGenerator extends KeyGeneratorSpi { ...@@ -64,12 +64,14 @@ public final class TlsMasterSecretGenerator extends KeyGeneratorSpi {
} }
this.spec = (TlsMasterSecretParameterSpec)params; this.spec = (TlsMasterSecretParameterSpec)params;
if ("RAW".equals(spec.getPremasterSecret().getFormat()) == false) { if ("RAW".equals(spec.getPremasterSecret().getFormat()) == false) {
throw new InvalidAlgorithmParameterException("Key format must be RAW"); throw new InvalidAlgorithmParameterException(
"Key format must be RAW");
} }
protocolVersion = (spec.getMajorVersion() << 8) | spec.getMinorVersion(); protocolVersion = (spec.getMajorVersion() << 8)
if ((protocolVersion < 0x0300) || (protocolVersion > 0x0302)) { | spec.getMinorVersion();
throw new InvalidAlgorithmParameterException if ((protocolVersion < 0x0300) || (protocolVersion > 0x0303)) {
("Only SSL 3.0, TLS 1.0, and TLS 1.1 supported"); throw new InvalidAlgorithmParameterException(
"Only SSL 3.0, TLS 1.0/1.1/1.2 supported");
} }
} }
...@@ -79,8 +81,8 @@ public final class TlsMasterSecretGenerator extends KeyGeneratorSpi { ...@@ -79,8 +81,8 @@ public final class TlsMasterSecretGenerator extends KeyGeneratorSpi {
protected SecretKey engineGenerateKey() { protected SecretKey engineGenerateKey() {
if (spec == null) { if (spec == null) {
throw new IllegalStateException throw new IllegalStateException(
("TlsMasterSecretGenerator must be initialized"); "TlsMasterSecretGenerator must be initialized");
} }
SecretKey premasterKey = spec.getPremasterSecret(); SecretKey premasterKey = spec.getPremasterSecret();
byte[] premaster = premasterKey.getEncoded(); byte[] premaster = premasterKey.getEncoded();
...@@ -103,7 +105,11 @@ public final class TlsMasterSecretGenerator extends KeyGeneratorSpi { ...@@ -103,7 +105,11 @@ public final class TlsMasterSecretGenerator extends KeyGeneratorSpi {
if (protocolVersion >= 0x0301) { if (protocolVersion >= 0x0301) {
byte[] seed = concat(clientRandom, serverRandom); byte[] seed = concat(clientRandom, serverRandom);
master = doPRF(premaster, LABEL_MASTER_SECRET, seed, 48); master = ((protocolVersion >= 0x0303) ?
doTLS12PRF(premaster, LABEL_MASTER_SECRET, seed, 48,
spec.getPRFHashAlg(), spec.getPRFHashLength(),
spec.getPRFBlockSize()) :
doTLS10PRF(premaster, LABEL_MASTER_SECRET, seed, 48));
} else { } else {
master = new byte[48]; master = new byte[48];
MessageDigest md5 = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5");
...@@ -124,7 +130,8 @@ public final class TlsMasterSecretGenerator extends KeyGeneratorSpi { ...@@ -124,7 +130,8 @@ public final class TlsMasterSecretGenerator extends KeyGeneratorSpi {
} }
return new TlsMasterSecretKey(master, premasterMajor, premasterMinor); return new TlsMasterSecretKey(master, premasterMajor,
premasterMinor);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
throw new ProviderException(e); throw new ProviderException(e);
} catch (DigestException e) { } catch (DigestException e) {
......
/* /*
* Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -37,11 +37,15 @@ import sun.security.internal.spec.TlsPrfParameterSpec; ...@@ -37,11 +37,15 @@ import sun.security.internal.spec.TlsPrfParameterSpec;
/** /**
* KeyGenerator implementation for the TLS PRF function. * KeyGenerator implementation for the TLS PRF function.
* <p>
* This class duplicates the HMAC functionality (RFC 2104) with
* performance optimizations (e.g. XOR'ing keys with padding doesn't
* need to be redone for each HMAC operation).
* *
* @author Andreas Sterbenz * @author Andreas Sterbenz
* @since 1.6 * @since 1.6
*/ */
public final class TlsPrfGenerator extends KeyGeneratorSpi { abstract class TlsPrfGenerator extends KeyGeneratorSpi {
// magic constants and utility functions, also used by other files // magic constants and utility functions, also used by other files
// in this package // in this package
...@@ -69,8 +73,10 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi { ...@@ -69,8 +73,10 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi {
* TLS HMAC "inner" and "outer" padding. This isn't a function * TLS HMAC "inner" and "outer" padding. This isn't a function
* of the digest algorithm. * of the digest algorithm.
*/ */
private static final byte[] HMAC_ipad = genPad((byte)0x36, 64); private static final byte[] HMAC_ipad64 = genPad((byte)0x36, 64);
private static final byte[] HMAC_opad = genPad((byte)0x5c, 64); private static final byte[] HMAC_ipad128 = genPad((byte)0x36, 128);
private static final byte[] HMAC_opad64 = genPad((byte)0x5c, 64);
private static final byte[] HMAC_opad128 = genPad((byte)0x5c, 128);
// SSL3 magic mix constants ("A", "BB", "CCC", ...) // SSL3 magic mix constants ("A", "BB", "CCC", ...)
final static byte[][] SSL3_CONST = genConst(); final static byte[][] SSL3_CONST = genConst();
...@@ -123,8 +129,8 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi { ...@@ -123,8 +129,8 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi {
this.spec = (TlsPrfParameterSpec)params; this.spec = (TlsPrfParameterSpec)params;
SecretKey key = spec.getSecret(); SecretKey key = spec.getSecret();
if ((key != null) && ("RAW".equals(key.getFormat()) == false)) { if ((key != null) && ("RAW".equals(key.getFormat()) == false)) {
throw new InvalidAlgorithmParameterException throw new InvalidAlgorithmParameterException(
("Key encoding format must be RAW"); "Key encoding format must be RAW");
} }
} }
...@@ -132,17 +138,21 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi { ...@@ -132,17 +138,21 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi {
throw new InvalidParameterException(MSG); throw new InvalidParameterException(MSG);
} }
protected SecretKey engineGenerateKey() { SecretKey engineGenerateKey0(boolean tls12) {
if (spec == null) { if (spec == null) {
throw new IllegalStateException throw new IllegalStateException(
("TlsPrfGenerator must be initialized"); "TlsPrfGenerator must be initialized");
} }
SecretKey key = spec.getSecret(); SecretKey key = spec.getSecret();
byte[] secret = (key == null) ? null : key.getEncoded(); byte[] secret = (key == null) ? null : key.getEncoded();
try { try {
byte[] labelBytes = spec.getLabel().getBytes("UTF8"); byte[] labelBytes = spec.getLabel().getBytes("UTF8");
int n = spec.getOutputLength(); int n = spec.getOutputLength();
byte[] prfBytes = doPRF(secret, labelBytes, spec.getSeed(), n); byte[] prfBytes = (tls12 ?
doTLS12PRF(secret, labelBytes, spec.getSeed(), n,
spec.getPRFHashAlg(), spec.getPRFHashLength(),
spec.getPRFBlockSize()) :
doTLS10PRF(secret, labelBytes, spec.getSeed(), n));
return new SecretKeySpec(prfBytes, "TlsPrf"); return new SecretKeySpec(prfBytes, "TlsPrf");
} catch (GeneralSecurityException e) { } catch (GeneralSecurityException e) {
throw new ProviderException("Could not generate PRF", e); throw new ProviderException("Could not generate PRF", e);
...@@ -151,16 +161,67 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi { ...@@ -151,16 +161,67 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi {
} }
} }
static final byte[] doPRF(byte[] secret, byte[] labelBytes, byte[] seed, static byte[] doTLS12PRF(byte[] secret, byte[] labelBytes,
int outputLength) throws NoSuchAlgorithmException, DigestException { byte[] seed, int outputLength,
String prfHash, int prfHashLength, int prfBlockSize)
throws NoSuchAlgorithmException, DigestException {
if (prfHash == null) {
throw new NoSuchAlgorithmException("Unspecified PRF algorithm");
}
MessageDigest prfMD = MessageDigest.getInstance(prfHash);
return doTLS12PRF(secret, labelBytes, seed, outputLength,
prfMD, prfHashLength, prfBlockSize);
}
static byte[] doTLS12PRF(byte[] secret, byte[] labelBytes,
byte[] seed, int outputLength,
MessageDigest mdPRF, int mdPRFLen, int mdPRFBlockSize)
throws DigestException {
if (secret == null) {
secret = B0;
}
// If we have a long secret, digest it first.
if (secret.length > mdPRFBlockSize) {
secret = mdPRF.digest(secret);
}
byte[] output = new byte[outputLength];
byte [] ipad;
byte [] opad;
switch (mdPRFBlockSize) {
case 64:
ipad = HMAC_ipad64.clone();
opad = HMAC_opad64.clone();
break;
case 128:
ipad = HMAC_ipad128.clone();
opad = HMAC_opad128.clone();
break;
default:
throw new DigestException("Unexpected block size.");
}
// P_HASH(Secret, label + seed)
expand(mdPRF, mdPRFLen, secret, 0, secret.length, labelBytes,
seed, output, ipad, opad);
return output;
}
static byte[] doTLS10PRF(byte[] secret, byte[] labelBytes,
byte[] seed, int outputLength) throws NoSuchAlgorithmException,
DigestException {
MessageDigest md5 = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5");
MessageDigest sha = MessageDigest.getInstance("SHA1"); MessageDigest sha = MessageDigest.getInstance("SHA1");
return doPRF(secret, labelBytes, seed, outputLength, md5, sha); return doTLS10PRF(secret, labelBytes, seed, outputLength, md5, sha);
} }
static final byte[] doPRF(byte[] secret, byte[] labelBytes, byte[] seed, static byte[] doTLS10PRF(byte[] secret, byte[] labelBytes,
int outputLength, MessageDigest md5, MessageDigest sha) byte[] seed, int outputLength, MessageDigest md5,
throws DigestException { MessageDigest sha) throws DigestException {
/* /*
* Split the secret into two halves S1 and S2 of same length. * Split the secret into two halves S1 and S2 of same length.
* S1 is taken from the first half of the secret, S2 from the * S1 is taken from the first half of the secret, S2 from the
...@@ -183,10 +244,12 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi { ...@@ -183,10 +244,12 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi {
byte[] output = new byte[outputLength]; byte[] output = new byte[outputLength];
// P_MD5(S1, label + seed) // P_MD5(S1, label + seed)
expand(md5, 16, secret, 0, seclen, labelBytes, seed, output); expand(md5, 16, secret, 0, seclen, labelBytes, seed, output,
HMAC_ipad64.clone(), HMAC_opad64.clone());
// P_SHA-1(S2, label + seed) // P_SHA-1(S2, label + seed)
expand(sha, 20, secret, off, seclen, labelBytes, seed, output); expand(sha, 20, secret, off, seclen, labelBytes, seed, output,
HMAC_ipad64.clone(), HMAC_opad64.clone());
return output; return output;
} }
...@@ -201,16 +264,13 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi { ...@@ -201,16 +264,13 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi {
* @param seed the seed * @param seed the seed
* @param output the output array * @param output the output array
*/ */
private static final void expand(MessageDigest digest, int hmacSize, private static void expand(MessageDigest digest, int hmacSize,
byte[] secret, int secOff, int secLen, byte[] label, byte[] seed, byte[] secret, int secOff, int secLen, byte[] label, byte[] seed,
byte[] output) throws DigestException { byte[] output, byte[] pad1, byte[] pad2) throws DigestException {
/* /*
* modify the padding used, by XORing the key into our copy of that * modify the padding used, by XORing the key into our copy of that
* padding. That's to avoid doing that for each HMAC computation. * padding. That's to avoid doing that for each HMAC computation.
*/ */
byte[] pad1 = HMAC_ipad.clone();
byte[] pad2 = HMAC_opad.clone();
for (int i = 0; i < secLen; i++) { for (int i = 0; i < secLen; i++) {
pad1[i] ^= secret[i + secOff]; pad1[i] ^= secret[i + secOff];
pad2[i] ^= secret[i + secOff]; pad2[i] ^= secret[i + secOff];
...@@ -275,7 +335,34 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi { ...@@ -275,7 +335,34 @@ public final class TlsPrfGenerator extends KeyGeneratorSpi {
} }
remaining -= k; remaining -= k;
} }
}
/**
* A KeyGenerator implementation that supports TLS 1.2.
* <p>
* TLS 1.2 uses a different hash algorithm than 1.0/1.1 for the PRF
* calculations. As of 2010, there is no PKCS11-level support for TLS
* 1.2 PRF calculations, and no known OS's have an internal variant
* we could use. Therefore for TLS 1.2, we are updating JSSE to request
* a different provider algorithm: "SunTls12Prf". If we reused the
* name "SunTlsPrf", the PKCS11 provider would need be updated to
* fail correctly when presented with the wrong version number
* (via Provider.Service.supportsParameters()), and add the
* appropriate supportsParamters() checks into KeyGenerators (not
* currently there).
*/
static public class V12 extends TlsPrfGenerator {
protected SecretKey engineGenerateKey() {
return engineGenerateKey0(true);
}
} }
/**
* A KeyGenerator implementation that supports TLS 1.0/1.1.
*/
static public class V10 extends TlsPrfGenerator {
protected SecretKey engineGenerateKey() {
return engineGenerateKey0(false);
}
}
} }
/* /*
* Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -69,8 +69,8 @@ public final class TlsRsaPremasterSecretGenerator extends KeyGeneratorSpi { ...@@ -69,8 +69,8 @@ public final class TlsRsaPremasterSecretGenerator extends KeyGeneratorSpi {
protected SecretKey engineGenerateKey() { protected SecretKey engineGenerateKey() {
if (spec == null) { if (spec == null) {
throw new IllegalStateException throw new IllegalStateException(
("TlsRsaPremasterSecretGenerator must be initialized"); "TlsRsaPremasterSecretGenerator must be initialized");
} }
if (random == null) { if (random == null) {
random = new SecureRandom(); random = new SecureRandom();
......
...@@ -76,9 +76,9 @@ public class ServiceName { ...@@ -76,9 +76,9 @@ public class ServiceName {
/** /**
* The vendor of the JMX specification implemented by this product. * The vendor of the JMX specification implemented by this product.
* <BR> * <BR>
* The value is <CODE>Sun Microsystems</CODE>. * The value is <CODE>Oracle Corporation</CODE>.
*/ */
public static final String JMX_SPEC_VENDOR = "Sun Microsystems"; public static final String JMX_SPEC_VENDOR = "Oracle Corporation";
/** /**
* The name of this product implementing the JMX specification. * The name of this product implementing the JMX specification.
...@@ -91,7 +91,7 @@ public class ServiceName { ...@@ -91,7 +91,7 @@ public class ServiceName {
* The name of the vendor of this product implementing the * The name of the vendor of this product implementing the
* JMX specification. * JMX specification.
* <BR> * <BR>
* The value is <CODE>Sun Microsystems</CODE>. * The value is <CODE>Oracle Corporation</CODE>.
*/ */
public static final String JMX_IMPL_VENDOR = "Sun Microsystems"; public static final String JMX_IMPL_VENDOR = "Oracle Corporation";
} }
...@@ -27,7 +27,7 @@ package com.sun.jmx.snmp; ...@@ -27,7 +27,7 @@ package com.sun.jmx.snmp;
/** /**
* Used for storing default values used by SNMP Runtime services. * Used for storing default values used by SNMP Runtime services.
* <p><b>This API is a Sun Microsystems internal API and is subject * <p><b>This API is an Oracle Corporation internal API and is subject
* to change without notice.</b></p> * to change without notice.</b></p>
*/ */
public class ServiceName { public class ServiceName {
...@@ -144,16 +144,16 @@ public class ServiceName { ...@@ -144,16 +144,16 @@ public class ServiceName {
/** /**
* The vendor of the JMX specification implemented by this product. * The vendor of the JMX specification implemented by this product.
* <BR> * <BR>
* The value is <CODE>Sun Microsystems</CODE>. * The value is <CODE>Oracle Corporation</CODE>.
*/ */
public static final String JMX_SPEC_VENDOR = "Sun Microsystems"; public static final String JMX_SPEC_VENDOR = "Oracle Corporation";
/** /**
* The name of the vendor of this product implementing the JMX specification. * The name of the vendor of this product implementing the JMX specification.
* <BR> * <BR>
* The value is <CODE>Sun Microsystems</CODE>. * The value is <CODE>Oracle Corporation</CODE>.
*/ */
public static final String JMX_IMPL_VENDOR = "Sun Microsystems"; public static final String JMX_IMPL_VENDOR = "Oracle Corporation";
/** /**
* The build number of the current product version, of the form <CODE>rXX</CODE>. * The build number of the current product version, of the form <CODE>rXX</CODE>.
......
...@@ -30,7 +30,7 @@ questions. ...@@ -30,7 +30,7 @@ questions.
</head> </head>
<body bgcolor="white"> <body bgcolor="white">
This package contains Sun Microsystem's platform extension to This package contains Oracle Corporation's platform extension to
the implementation of the the implementation of the
<a href="{@docRoot}/../../../../api/java/lang/management/package-summary.html"> <a href="{@docRoot}/../../../../api/java/lang/management/package-summary.html">
java.lang.management</a> API and also defines the management java.lang.management</a> API and also defines the management
......
/* /*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -25,6 +25,8 @@ ...@@ -25,6 +25,8 @@
package java.awt; package java.awt;
import java.beans.ConstructorProperties;
/** /**
* The <code>BasicStroke</code> class defines a basic set of rendering * The <code>BasicStroke</code> class defines a basic set of rendering
* attributes for the outlines of graphics primitives, which are rendered * attributes for the outlines of graphics primitives, which are rendered
...@@ -183,6 +185,7 @@ public class BasicStroke implements Stroke { ...@@ -183,6 +185,7 @@ public class BasicStroke implements Stroke {
* <code>dash</code> is zero * <code>dash</code> is zero
* @throws IllegalArgumentException if dash lengths are all zero. * @throws IllegalArgumentException if dash lengths are all zero.
*/ */
@ConstructorProperties({ "lineWidth", "endCap", "lineJoin", "miterLimit", "dashArray", "dashPhase" })
public BasicStroke(float width, int cap, int join, float miterlimit, public BasicStroke(float width, int cap, int join, float miterlimit,
float dash[], float dash_phase) { float dash[], float dash_phase) {
if (width < 0.0f) { if (width < 0.0f) {
......
/* /*
* Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -29,6 +29,7 @@ import java.awt.geom.Point2D; ...@@ -29,6 +29,7 @@ import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D; import java.awt.geom.Rectangle2D;
import java.awt.geom.AffineTransform; import java.awt.geom.AffineTransform;
import java.awt.image.ColorModel; import java.awt.image.ColorModel;
import java.beans.ConstructorProperties;
/** /**
* The <code>GradientPaint</code> class provides a way to fill * The <code>GradientPaint</code> class provides a way to fill
...@@ -166,6 +167,7 @@ public class GradientPaint implements Paint { ...@@ -166,6 +167,7 @@ public class GradientPaint implements Paint {
* @throws NullPointerException if either one of colors or points * @throws NullPointerException if either one of colors or points
* is null * is null
*/ */
@ConstructorProperties({ "point1", "color1", "point2", "color2", "cyclic" })
public GradientPaint(Point2D pt1, public GradientPaint(Point2D pt1,
Color color1, Color color1,
Point2D pt2, Point2D pt2,
......
...@@ -126,7 +126,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable { ...@@ -126,7 +126,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable {
/** /**
* Place the component centered along the edge of its display area * Place the component centered along the edge of its display area
* associated with the start of a page for the current * associated with the start of a page for the current
* <code>ComponentOrienation</code>. Equal to NORTH for horizontal * {@code ComponentOrientation}. Equal to NORTH for horizontal
* orientations. * orientations.
*/ */
public static final int PAGE_START = 19; public static final int PAGE_START = 19;
...@@ -134,7 +134,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable { ...@@ -134,7 +134,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable {
/** /**
* Place the component centered along the edge of its display area * Place the component centered along the edge of its display area
* associated with the end of a page for the current * associated with the end of a page for the current
* <code>ComponentOrienation</code>. Equal to SOUTH for horizontal * {@code ComponentOrientation}. Equal to SOUTH for horizontal
* orientations. * orientations.
*/ */
public static final int PAGE_END = 20; public static final int PAGE_END = 20;
...@@ -142,7 +142,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable { ...@@ -142,7 +142,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable {
/** /**
* Place the component centered along the edge of its display area where * Place the component centered along the edge of its display area where
* lines of text would normally begin for the current * lines of text would normally begin for the current
* <code>ComponentOrienation</code>. Equal to WEST for horizontal, * {@code ComponentOrientation}. Equal to WEST for horizontal,
* left-to-right orientations and EAST for horizontal, right-to-left * left-to-right orientations and EAST for horizontal, right-to-left
* orientations. * orientations.
*/ */
...@@ -151,7 +151,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable { ...@@ -151,7 +151,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable {
/** /**
* Place the component centered along the edge of its display area where * Place the component centered along the edge of its display area where
* lines of text would normally end for the current * lines of text would normally end for the current
* <code>ComponentOrienation</code>. Equal to EAST for horizontal, * {@code ComponentOrientation}. Equal to EAST for horizontal,
* left-to-right orientations and WEST for horizontal, right-to-left * left-to-right orientations and WEST for horizontal, right-to-left
* orientations. * orientations.
*/ */
...@@ -160,7 +160,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable { ...@@ -160,7 +160,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable {
/** /**
* Place the component in the corner of its display area where * Place the component in the corner of its display area where
* the first line of text on a page would normally begin for the current * the first line of text on a page would normally begin for the current
* <code>ComponentOrienation</code>. Equal to NORTHWEST for horizontal, * {@code ComponentOrientation}. Equal to NORTHWEST for horizontal,
* left-to-right orientations and NORTHEAST for horizontal, right-to-left * left-to-right orientations and NORTHEAST for horizontal, right-to-left
* orientations. * orientations.
*/ */
...@@ -169,7 +169,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable { ...@@ -169,7 +169,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable {
/** /**
* Place the component in the corner of its display area where * Place the component in the corner of its display area where
* the first line of text on a page would normally end for the current * the first line of text on a page would normally end for the current
* <code>ComponentOrienation</code>. Equal to NORTHEAST for horizontal, * {@code ComponentOrientation}. Equal to NORTHEAST for horizontal,
* left-to-right orientations and NORTHWEST for horizontal, right-to-left * left-to-right orientations and NORTHWEST for horizontal, right-to-left
* orientations. * orientations.
*/ */
...@@ -178,7 +178,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable { ...@@ -178,7 +178,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable {
/** /**
* Place the component in the corner of its display area where * Place the component in the corner of its display area where
* the last line of text on a page would normally start for the current * the last line of text on a page would normally start for the current
* <code>ComponentOrienation</code>. Equal to SOUTHWEST for horizontal, * {@code ComponentOrientation}. Equal to SOUTHWEST for horizontal,
* left-to-right orientations and SOUTHEAST for horizontal, right-to-left * left-to-right orientations and SOUTHEAST for horizontal, right-to-left
* orientations. * orientations.
*/ */
...@@ -187,7 +187,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable { ...@@ -187,7 +187,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable {
/** /**
* Place the component in the corner of its display area where * Place the component in the corner of its display area where
* the last line of text on a page would normally end for the current * the last line of text on a page would normally end for the current
* <code>ComponentOrienation</code>. Equal to SOUTHEAST for horizontal, * {@code ComponentOrientation}. Equal to SOUTHEAST for horizontal,
* left-to-right orientations and SOUTHWEST for horizontal, right-to-left * left-to-right orientations and SOUTHWEST for horizontal, right-to-left
* orientations. * orientations.
*/ */
...@@ -437,7 +437,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable { ...@@ -437,7 +437,7 @@ public class GridBagConstraints implements Cloneable, java.io.Serializable {
* <code>LINE_START</code>, <code>LINE_END</code>, * <code>LINE_START</code>, <code>LINE_END</code>,
* <code>FIRST_LINE_START</code>, <code>FIRST_LINE_END</code>, * <code>FIRST_LINE_START</code>, <code>FIRST_LINE_END</code>,
* <code>LAST_LINE_START</code> and <code>LAST_LINE_END</code>. The * <code>LAST_LINE_START</code> and <code>LAST_LINE_END</code>. The
* baseline relvative values are: * baseline relative values are:
* <code>BASELINE</code>, <code>BASELINE_LEADING</code>, * <code>BASELINE</code>, <code>BASELINE_LEADING</code>,
* <code>BASELINE_TRAILING</code>, * <code>BASELINE_TRAILING</code>,
* <code>ABOVE_BASELINE</code>, <code>ABOVE_BASELINE_LEADING</code>, * <code>ABOVE_BASELINE</code>, <code>ABOVE_BASELINE_LEADING</code>,
......
/* /*
* Copyright (c) 2006, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -26,10 +26,10 @@ ...@@ -26,10 +26,10 @@
package java.awt; package java.awt;
import java.awt.geom.AffineTransform; import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D; import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D; import java.awt.geom.Rectangle2D;
import java.awt.image.ColorModel; import java.awt.image.ColorModel;
import java.beans.ConstructorProperties;
/** /**
* The {@code LinearGradientPaint} class provides a way to fill * The {@code LinearGradientPaint} class provides a way to fill
...@@ -271,6 +271,7 @@ public final class LinearGradientPaint extends MultipleGradientPaint { ...@@ -271,6 +271,7 @@ public final class LinearGradientPaint extends MultipleGradientPaint {
* or a {@code fractions} value is less than 0.0 or greater than 1.0, * or a {@code fractions} value is less than 0.0 or greater than 1.0,
* or the {@code fractions} are not provided in strictly increasing order * or the {@code fractions} are not provided in strictly increasing order
*/ */
@ConstructorProperties({ "startPoint", "endPoint", "fractions", "colors", "cycleMethod", "colorSpace", "transform" })
public LinearGradientPaint(Point2D start, Point2D end, public LinearGradientPaint(Point2D start, Point2D end,
float[] fractions, Color[] colors, float[] fractions, Color[] colors,
CycleMethod cycleMethod, CycleMethod cycleMethod,
......
/* /*
* Copyright (c) 2006, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -29,6 +29,7 @@ import java.awt.geom.AffineTransform; ...@@ -29,6 +29,7 @@ import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D; import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D; import java.awt.geom.Rectangle2D;
import java.awt.image.ColorModel; import java.awt.image.ColorModel;
import java.beans.ConstructorProperties;
/** /**
* The {@code RadialGradientPaint} class provides a way to fill a shape with * The {@code RadialGradientPaint} class provides a way to fill a shape with
...@@ -428,6 +429,7 @@ public final class RadialGradientPaint extends MultipleGradientPaint { ...@@ -428,6 +429,7 @@ public final class RadialGradientPaint extends MultipleGradientPaint {
* or a {@code fractions} value is less than 0.0 or greater than 1.0, * or a {@code fractions} value is less than 0.0 or greater than 1.0,
* or the {@code fractions} are not provided in strictly increasing order * or the {@code fractions} are not provided in strictly increasing order
*/ */
@ConstructorProperties({ "centerPoint", "radius", "focusPoint", "fractions", "colors", "cycleMethod", "colorSpace", "transform" })
public RadialGradientPaint(Point2D center, public RadialGradientPaint(Point2D center,
float radius, float radius,
Point2D focus, Point2D focus,
......
...@@ -213,7 +213,8 @@ public class Scrollbar extends Component implements Adjustable, Accessible { ...@@ -213,7 +213,8 @@ public class Scrollbar extends Component implements Adjustable, Accessible {
* The size of the <code>Scrollbar</code>'s bubble. * The size of the <code>Scrollbar</code>'s bubble.
* When a scroll bar is used to select a range of values, * When a scroll bar is used to select a range of values,
* the visibleAmount represents the size of this range. * the visibleAmount represents the size of this range.
* This is visually indicated by the size of the bubble. * Depending on platform, this may be visually indicated
* by the size of the bubble.
* *
* @serial * @serial
* @see #getVisibleAmount * @see #getVisibleAmount
...@@ -637,6 +638,8 @@ public class Scrollbar extends Component implements Adjustable, Accessible { ...@@ -637,6 +638,8 @@ public class Scrollbar extends Component implements Adjustable, Accessible {
* bubble (also called a thumb or scroll box), usually gives a * bubble (also called a thumb or scroll box), usually gives a
* visual representation of the relationship of the visible * visual representation of the relationship of the visible
* amount to the range of the scroll bar. * amount to the range of the scroll bar.
* Note that depending on platform, the value of the visible amount property
* may not be visually indicated by the size of the bubble.
* <p> * <p>
* The scroll bar's bubble may not be displayed when it is not * The scroll bar's bubble may not be displayed when it is not
* moveable (e.g. when it takes up the entire length of the * moveable (e.g. when it takes up the entire length of the
...@@ -670,6 +673,8 @@ public class Scrollbar extends Component implements Adjustable, Accessible { ...@@ -670,6 +673,8 @@ public class Scrollbar extends Component implements Adjustable, Accessible {
* bubble (also called a thumb or scroll box), usually gives a * bubble (also called a thumb or scroll box), usually gives a
* visual representation of the relationship of the visible * visual representation of the relationship of the visible
* amount to the range of the scroll bar. * amount to the range of the scroll bar.
* Note that depending on platform, the value of the visible amount property
* may not be visually indicated by the size of the bubble.
* <p> * <p>
* The scroll bar's bubble may not be displayed when it is not * The scroll bar's bubble may not be displayed when it is not
* moveable (e.g. when it takes up the entire length of the * moveable (e.g. when it takes up the entire length of the
......
...@@ -1831,7 +1831,11 @@ public abstract class Toolkit { ...@@ -1831,7 +1831,11 @@ public abstract class Toolkit {
desktopProperties.put(name, newValue); desktopProperties.put(name, newValue);
} }
desktopPropsSupport.firePropertyChange(name, oldValue, newValue); // Don't fire change event if old and new values are null.
// It helps to avoid recursive resending of WM_THEMECHANGED
if (oldValue != null || newValue != null) {
desktopPropsSupport.firePropertyChange(name, oldValue, newValue);
}
} }
/** /**
......
/* /*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
package java.awt.geom; package java.awt.geom;
import java.awt.Shape; import java.awt.Shape;
import java.beans.ConstructorProperties;
/** /**
* The <code>AffineTransform</code> class represents a 2D affine transform * The <code>AffineTransform</code> class represents a 2D affine transform
...@@ -508,6 +509,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable { ...@@ -508,6 +509,7 @@ public class AffineTransform implements Cloneable, java.io.Serializable {
* @param m12 the Y coordinate translation element of the 3x3 matrix * @param m12 the Y coordinate translation element of the 3x3 matrix
* @since 1.2 * @since 1.2
*/ */
@ConstructorProperties({ "scaleX", "shearY", "shearX", "scaleY", "translateX", "translateY" })
public AffineTransform(float m00, float m10, public AffineTransform(float m00, float m10,
float m01, float m11, float m01, float m11,
float m02, float m12) { float m02, float m12) {
......
/* /*
* Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -265,7 +265,7 @@ public class ObjectInputStream ...@@ -265,7 +265,7 @@ public class ObjectInputStream
* object currently being deserialized and descriptor for current class. * object currently being deserialized and descriptor for current class.
* Null when not during readObject upcall. * Null when not during readObject upcall.
*/ */
private CallbackContext curContext; private SerialCallbackContext curContext;
/** /**
* Creates an ObjectInputStream that reads from the specified InputStream. * Creates an ObjectInputStream that reads from the specified InputStream.
...@@ -1798,7 +1798,7 @@ public class ObjectInputStream ...@@ -1798,7 +1798,7 @@ public class ObjectInputStream
private void readExternalData(Externalizable obj, ObjectStreamClass desc) private void readExternalData(Externalizable obj, ObjectStreamClass desc)
throws IOException throws IOException
{ {
CallbackContext oldContext = curContext; SerialCallbackContext oldContext = curContext;
curContext = null; curContext = null;
try { try {
boolean blocked = desc.hasBlockExternalData(); boolean blocked = desc.hasBlockExternalData();
...@@ -1857,10 +1857,10 @@ public class ObjectInputStream ...@@ -1857,10 +1857,10 @@ public class ObjectInputStream
slotDesc.hasReadObjectMethod() && slotDesc.hasReadObjectMethod() &&
handles.lookupException(passHandle) == null) handles.lookupException(passHandle) == null)
{ {
CallbackContext oldContext = curContext; SerialCallbackContext oldContext = curContext;
try { try {
curContext = new CallbackContext(obj, slotDesc); curContext = new SerialCallbackContext(obj, slotDesc);
bin.setBlockDataMode(true); bin.setBlockDataMode(true);
slotDesc.invokeReadObject(obj, this); slotDesc.invokeReadObject(obj, this);
...@@ -3505,42 +3505,4 @@ public class ObjectInputStream ...@@ -3505,42 +3505,4 @@ public class ObjectInputStream
} }
} }
/**
* Context that during upcalls to class-defined readObject methods; holds
* object currently being deserialized and descriptor for current class.
* This context keeps a boolean state to indicate that defaultReadObject
* or readFields has already been invoked with this context or the class's
* readObject method has returned; if true, the getObj method throws
* NotActiveException.
*/
private static class CallbackContext {
private final Object obj;
private final ObjectStreamClass desc;
private final AtomicBoolean used = new AtomicBoolean();
public CallbackContext(Object obj, ObjectStreamClass desc) {
this.obj = obj;
this.desc = desc;
}
public Object getObj() throws NotActiveException {
checkAndSetUsed();
return obj;
}
public ObjectStreamClass getDesc() {
return desc;
}
private void checkAndSetUsed() throws NotActiveException {
if (!used.compareAndSet(false, true)) {
throw new NotActiveException(
"not in readObject invocation or fields already read");
}
}
public void setUsed() {
used.set(true);
}
}
} }
/* /*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -35,6 +35,7 @@ import java.util.List; ...@@ -35,6 +35,7 @@ import java.util.List;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import static java.io.ObjectStreamClass.processQueue; import static java.io.ObjectStreamClass.processQueue;
import java.io.SerialCallbackContext;
/** /**
* An ObjectOutputStream writes primitive data types and graphs of Java objects * An ObjectOutputStream writes primitive data types and graphs of Java objects
...@@ -191,10 +192,12 @@ public class ObjectOutputStream ...@@ -191,10 +192,12 @@ public class ObjectOutputStream
private boolean enableReplace; private boolean enableReplace;
// values below valid only during upcalls to writeObject()/writeExternal() // values below valid only during upcalls to writeObject()/writeExternal()
/** object currently being serialized */ /**
private Object curObj; * Context during upcalls to class-defined writeObject methods; holds
/** descriptor for current class (null if in writeExternal()) */ * object currently being serialized and descriptor for current class.
private ObjectStreamClass curDesc; * Null when not during writeObject upcall.
*/
private SerialCallbackContext curContext;
/** current PutField object */ /** current PutField object */
private PutFieldImpl curPut; private PutFieldImpl curPut;
...@@ -426,9 +429,11 @@ public class ObjectOutputStream ...@@ -426,9 +429,11 @@ public class ObjectOutputStream
* <code>OutputStream</code> * <code>OutputStream</code>
*/ */
public void defaultWriteObject() throws IOException { public void defaultWriteObject() throws IOException {
if (curObj == null || curDesc == null) { if ( curContext == null ) {
throw new NotActiveException("not in call to writeObject"); throw new NotActiveException("not in call to writeObject");
} }
Object curObj = curContext.getObj();
ObjectStreamClass curDesc = curContext.getDesc();
bout.setBlockDataMode(false); bout.setBlockDataMode(false);
defaultWriteFields(curObj, curDesc); defaultWriteFields(curObj, curDesc);
bout.setBlockDataMode(true); bout.setBlockDataMode(true);
...@@ -446,9 +451,11 @@ public class ObjectOutputStream ...@@ -446,9 +451,11 @@ public class ObjectOutputStream
*/ */
public ObjectOutputStream.PutField putFields() throws IOException { public ObjectOutputStream.PutField putFields() throws IOException {
if (curPut == null) { if (curPut == null) {
if (curObj == null || curDesc == null) { if (curContext == null) {
throw new NotActiveException("not in call to writeObject"); throw new NotActiveException("not in call to writeObject");
} }
Object curObj = curContext.getObj();
ObjectStreamClass curDesc = curContext.getDesc();
curPut = new PutFieldImpl(curDesc); curPut = new PutFieldImpl(curDesc);
} }
return curPut; return curPut;
...@@ -1420,17 +1427,15 @@ public class ObjectOutputStream ...@@ -1420,17 +1427,15 @@ public class ObjectOutputStream
* writeExternal() method. * writeExternal() method.
*/ */
private void writeExternalData(Externalizable obj) throws IOException { private void writeExternalData(Externalizable obj) throws IOException {
Object oldObj = curObj;
ObjectStreamClass oldDesc = curDesc;
PutFieldImpl oldPut = curPut; PutFieldImpl oldPut = curPut;
curObj = obj;
curDesc = null;
curPut = null; curPut = null;
if (extendedDebugInfo) { if (extendedDebugInfo) {
debugInfoStack.push("writeExternal data"); debugInfoStack.push("writeExternal data");
} }
SerialCallbackContext oldContext = curContext;
try { try {
curContext = null;
if (protocol == PROTOCOL_VERSION_1) { if (protocol == PROTOCOL_VERSION_1) {
obj.writeExternal(this); obj.writeExternal(this);
} else { } else {
...@@ -1440,13 +1445,12 @@ public class ObjectOutputStream ...@@ -1440,13 +1445,12 @@ public class ObjectOutputStream
bout.writeByte(TC_ENDBLOCKDATA); bout.writeByte(TC_ENDBLOCKDATA);
} }
} finally { } finally {
curContext = oldContext;
if (extendedDebugInfo) { if (extendedDebugInfo) {
debugInfoStack.pop(); debugInfoStack.pop();
} }
} }
curObj = oldObj;
curDesc = oldDesc;
curPut = oldPut; curPut = oldPut;
} }
...@@ -1461,12 +1465,9 @@ public class ObjectOutputStream ...@@ -1461,12 +1465,9 @@ public class ObjectOutputStream
for (int i = 0; i < slots.length; i++) { for (int i = 0; i < slots.length; i++) {
ObjectStreamClass slotDesc = slots[i].desc; ObjectStreamClass slotDesc = slots[i].desc;
if (slotDesc.hasWriteObjectMethod()) { if (slotDesc.hasWriteObjectMethod()) {
Object oldObj = curObj;
ObjectStreamClass oldDesc = curDesc;
PutFieldImpl oldPut = curPut; PutFieldImpl oldPut = curPut;
curObj = obj;
curDesc = slotDesc;
curPut = null; curPut = null;
SerialCallbackContext oldContext = curContext;
if (extendedDebugInfo) { if (extendedDebugInfo) {
debugInfoStack.push( debugInfoStack.push(
...@@ -1474,18 +1475,19 @@ public class ObjectOutputStream ...@@ -1474,18 +1475,19 @@ public class ObjectOutputStream
slotDesc.getName() + "\")"); slotDesc.getName() + "\")");
} }
try { try {
curContext = new SerialCallbackContext(obj, slotDesc);
bout.setBlockDataMode(true); bout.setBlockDataMode(true);
slotDesc.invokeWriteObject(obj, this); slotDesc.invokeWriteObject(obj, this);
bout.setBlockDataMode(false); bout.setBlockDataMode(false);
bout.writeByte(TC_ENDBLOCKDATA); bout.writeByte(TC_ENDBLOCKDATA);
} finally { } finally {
curContext.setUsed();
curContext = oldContext;
if (extendedDebugInfo) { if (extendedDebugInfo) {
debugInfoStack.pop(); debugInfoStack.pop();
} }
} }
curObj = oldObj;
curDesc = oldDesc;
curPut = oldPut; curPut = oldPut;
} else { } else {
defaultWriteFields(obj, slotDesc); defaultWriteFields(obj, slotDesc);
......
/* /*
* Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -1830,8 +1830,10 @@ public class ObjectStreamClass implements Serializable { ...@@ -1830,8 +1830,10 @@ public class ObjectStreamClass implements Serializable {
private final ObjectStreamField[] fields; private final ObjectStreamField[] fields;
/** number of primitive fields */ /** number of primitive fields */
private final int numPrimFields; private final int numPrimFields;
/** unsafe field keys */ /** unsafe field keys for reading fields - may contain dupes */
private final long[] keys; private final long[] readKeys;
/** unsafe fields keys for writing fields - no dupes */
private final long[] writeKeys;
/** field data offsets */ /** field data offsets */
private final int[] offsets; private final int[] offsets;
/** field type codes */ /** field type codes */
...@@ -1849,16 +1851,22 @@ public class ObjectStreamClass implements Serializable { ...@@ -1849,16 +1851,22 @@ public class ObjectStreamClass implements Serializable {
FieldReflector(ObjectStreamField[] fields) { FieldReflector(ObjectStreamField[] fields) {
this.fields = fields; this.fields = fields;
int nfields = fields.length; int nfields = fields.length;
keys = new long[nfields]; readKeys = new long[nfields];
writeKeys = new long[nfields];
offsets = new int[nfields]; offsets = new int[nfields];
typeCodes = new char[nfields]; typeCodes = new char[nfields];
ArrayList<Class<?>> typeList = new ArrayList<Class<?>>(); ArrayList<Class<?>> typeList = new ArrayList<Class<?>>();
Set<Long> usedKeys = new HashSet<Long>();
for (int i = 0; i < nfields; i++) { for (int i = 0; i < nfields; i++) {
ObjectStreamField f = fields[i]; ObjectStreamField f = fields[i];
Field rf = f.getField(); Field rf = f.getField();
keys[i] = (rf != null) ? long key = (rf != null) ?
unsafe.objectFieldOffset(rf) : Unsafe.INVALID_FIELD_OFFSET; unsafe.objectFieldOffset(rf) : Unsafe.INVALID_FIELD_OFFSET;
readKeys[i] = key;
writeKeys[i] = usedKeys.add(key) ?
key : Unsafe.INVALID_FIELD_OFFSET;
offsets[i] = f.getOffset(); offsets[i] = f.getOffset();
typeCodes[i] = f.getTypeCode(); typeCodes[i] = f.getTypeCode();
if (!f.isPrimitive()) { if (!f.isPrimitive()) {
...@@ -1894,7 +1902,7 @@ public class ObjectStreamClass implements Serializable { ...@@ -1894,7 +1902,7 @@ public class ObjectStreamClass implements Serializable {
* in array should be equal to Unsafe.INVALID_FIELD_OFFSET. * in array should be equal to Unsafe.INVALID_FIELD_OFFSET.
*/ */
for (int i = 0; i < numPrimFields; i++) { for (int i = 0; i < numPrimFields; i++) {
long key = keys[i]; long key = readKeys[i];
int off = offsets[i]; int off = offsets[i];
switch (typeCodes[i]) { switch (typeCodes[i]) {
case 'Z': case 'Z':
...@@ -1945,7 +1953,7 @@ public class ObjectStreamClass implements Serializable { ...@@ -1945,7 +1953,7 @@ public class ObjectStreamClass implements Serializable {
throw new NullPointerException(); throw new NullPointerException();
} }
for (int i = 0; i < numPrimFields; i++) { for (int i = 0; i < numPrimFields; i++) {
long key = keys[i]; long key = writeKeys[i];
if (key == Unsafe.INVALID_FIELD_OFFSET) { if (key == Unsafe.INVALID_FIELD_OFFSET) {
continue; // discard value continue; // discard value
} }
...@@ -2006,7 +2014,7 @@ public class ObjectStreamClass implements Serializable { ...@@ -2006,7 +2014,7 @@ public class ObjectStreamClass implements Serializable {
switch (typeCodes[i]) { switch (typeCodes[i]) {
case 'L': case 'L':
case '[': case '[':
vals[offsets[i]] = unsafe.getObject(obj, keys[i]); vals[offsets[i]] = unsafe.getObject(obj, readKeys[i]);
break; break;
default: default:
...@@ -2027,7 +2035,7 @@ public class ObjectStreamClass implements Serializable { ...@@ -2027,7 +2035,7 @@ public class ObjectStreamClass implements Serializable {
throw new NullPointerException(); throw new NullPointerException();
} }
for (int i = numPrimFields; i < fields.length; i++) { for (int i = numPrimFields; i < fields.length; i++) {
long key = keys[i]; long key = writeKeys[i];
if (key == Unsafe.INVALID_FIELD_OFFSET) { if (key == Unsafe.INVALID_FIELD_OFFSET) {
continue; // discard value continue; // discard value
} }
......
/*
* %W% %E%
*
* Copyright (c) 2006, 2010 Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.io;
/**
* Context during upcalls from object stream to class-defined
* readObject/writeObject methods.
* Holds object currently being deserialized and descriptor for current class.
*
* This context keeps track of the thread it was constructed on, and allows
* only a single call of defaultReadObject, readFields, defaultWriteObject
* or writeFields which must be invoked on the same thread before the class's
* readObject/writeObject method has returned.
* If not set to the current thread, the getObj method throws NotActiveException.
*/
final class SerialCallbackContext {
private final Object obj;
private final ObjectStreamClass desc;
/**
* Thread this context is in use by.
* As this only works in one thread, we do not need to worry about thread-safety.
*/
private Thread thread;
public SerialCallbackContext(Object obj, ObjectStreamClass desc) {
this.obj = obj;
this.desc = desc;
this.thread = Thread.currentThread();
}
public Object getObj() throws NotActiveException {
checkAndSetUsed();
return obj;
}
public ObjectStreamClass getDesc() {
return desc;
}
private void checkAndSetUsed() throws NotActiveException {
if (thread != Thread.currentThread()) {
throw new NotActiveException(
"not in readObject invocation or fields already read");
}
thread = null;
}
public void setUsed() {
thread = null;
}
}
...@@ -100,7 +100,8 @@ abstract class AbstractStringBuilder implements Appendable, CharSequence { ...@@ -100,7 +100,8 @@ abstract class AbstractStringBuilder implements Appendable, CharSequence {
* @param minimumCapacity the minimum desired capacity. * @param minimumCapacity the minimum desired capacity.
*/ */
public void ensureCapacity(int minimumCapacity) { public void ensureCapacity(int minimumCapacity) {
ensureCapacityInternal(minimumCapacity); if (minimumCapacity > 0)
ensureCapacityInternal(minimumCapacity);
} }
/** /**
...@@ -108,6 +109,7 @@ abstract class AbstractStringBuilder implements Appendable, CharSequence { ...@@ -108,6 +109,7 @@ abstract class AbstractStringBuilder implements Appendable, CharSequence {
* never synchronized. * never synchronized.
*/ */
private void ensureCapacityInternal(int minimumCapacity) { private void ensureCapacityInternal(int minimumCapacity) {
// overflow-conscious code
if (minimumCapacity - value.length > 0) if (minimumCapacity - value.length > 0)
expandCapacity(minimumCapacity); expandCapacity(minimumCapacity);
} }
......
...@@ -553,6 +553,13 @@ public abstract class ClassLoader { ...@@ -553,6 +553,13 @@ public abstract class ClassLoader {
* If either <tt>off</tt> or <tt>len</tt> is negative, or if * If either <tt>off</tt> or <tt>len</tt> is negative, or if
* <tt>off+len</tt> is greater than <tt>b.length</tt>. * <tt>off+len</tt> is greater than <tt>b.length</tt>.
* *
* @throws SecurityException
* If an attempt is made to add this class to a package that
* contains classes that were signed by a different set of
* certificates than this class, or if an attempt is made
* to define a class in a package with a fully-qualified name
* that starts with "{@code java.}".
*
* @see #loadClass(String, boolean) * @see #loadClass(String, boolean)
* @see #resolveClass(Class) * @see #resolveClass(Class)
* *
......
...@@ -28,9 +28,7 @@ package java.net; ...@@ -28,9 +28,7 @@ package java.net;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.InterruptedIOException;
import java.io.FileDescriptor; import java.io.FileDescriptor;
import java.io.ByteArrayOutputStream;
import sun.net.ConnectionResetException; import sun.net.ConnectionResetException;
import sun.net.NetHooks; import sun.net.NetHooks;
...@@ -58,7 +56,7 @@ abstract class AbstractPlainSocketImpl extends SocketImpl ...@@ -58,7 +56,7 @@ abstract class AbstractPlainSocketImpl extends SocketImpl
protected int fdUseCount = 0; protected int fdUseCount = 0;
/* lock when increment/decrementing fdUseCount */ /* lock when increment/decrementing fdUseCount */
protected Object fdLock = new Object(); protected final Object fdLock = new Object();
/* indicates a close is pending on the file descriptor */ /* indicates a close is pending on the file descriptor */
protected boolean closePending = false; protected boolean closePending = false;
...@@ -68,7 +66,7 @@ abstract class AbstractPlainSocketImpl extends SocketImpl ...@@ -68,7 +66,7 @@ abstract class AbstractPlainSocketImpl extends SocketImpl
private int CONNECTION_RESET_PENDING = 1; private int CONNECTION_RESET_PENDING = 1;
private int CONNECTION_RESET = 2; private int CONNECTION_RESET = 2;
private int resetState; private int resetState;
private Object resetLock = new Object(); private final Object resetLock = new Object();
/** /**
* Load net library into runtime. * Load net library into runtime.
...@@ -100,25 +98,24 @@ abstract class AbstractPlainSocketImpl extends SocketImpl ...@@ -100,25 +98,24 @@ abstract class AbstractPlainSocketImpl extends SocketImpl
protected void connect(String host, int port) protected void connect(String host, int port)
throws UnknownHostException, IOException throws UnknownHostException, IOException
{ {
IOException pending = null; boolean connected = false;
try { try {
InetAddress address = InetAddress.getByName(host); InetAddress address = InetAddress.getByName(host);
this.port = port; this.port = port;
this.address = address; this.address = address;
try { connectToAddress(address, port, timeout);
connectToAddress(address, port, timeout); connected = true;
return; } finally {
} catch (IOException e) { if (!connected) {
pending = e; try {
close();
} catch (IOException ioe) {
/* Do nothing. If connect threw an exception then
it will be passed up the call stack */
}
} }
} catch (UnknownHostException e) {
pending = e;
} }
// everything failed
close();
throw pending;
} }
/** /**
...@@ -151,22 +148,29 @@ abstract class AbstractPlainSocketImpl extends SocketImpl ...@@ -151,22 +148,29 @@ abstract class AbstractPlainSocketImpl extends SocketImpl
* SocketAddress subclass not supported by this socket * SocketAddress subclass not supported by this socket
* @since 1.4 * @since 1.4
*/ */
protected void connect(SocketAddress address, int timeout) throws IOException { protected void connect(SocketAddress address, int timeout)
if (address == null || !(address instanceof InetSocketAddress)) throws IOException {
throw new IllegalArgumentException("unsupported address type"); boolean connected = false;
InetSocketAddress addr = (InetSocketAddress) address;
if (addr.isUnresolved())
throw new UnknownHostException(addr.getHostName());
this.port = addr.getPort();
this.address = addr.getAddress();
try { try {
if (address == null || !(address instanceof InetSocketAddress))
throw new IllegalArgumentException("unsupported address type");
InetSocketAddress addr = (InetSocketAddress) address;
if (addr.isUnresolved())
throw new UnknownHostException(addr.getHostName());
this.port = addr.getPort();
this.address = addr.getAddress();
connectToAddress(this.address, port, timeout); connectToAddress(this.address, port, timeout);
return; connected = true;
} catch (IOException e) { } finally {
// everything failed if (!connected) {
close(); try {
throw e; close();
} catch (IOException ioe) {
/* Do nothing. If connect threw an exception then
it will be passed up the call stack */
}
}
} }
} }
...@@ -311,7 +315,7 @@ abstract class AbstractPlainSocketImpl extends SocketImpl ...@@ -311,7 +315,7 @@ abstract class AbstractPlainSocketImpl extends SocketImpl
} }
} }
try { try {
FileDescriptor fd = acquireFD(); acquireFD();
try { try {
socketConnect(address, port, timeout); socketConnect(address, port, timeout);
/* socket may have been closed during poll/select */ /* socket may have been closed during poll/select */
...@@ -370,7 +374,7 @@ abstract class AbstractPlainSocketImpl extends SocketImpl ...@@ -370,7 +374,7 @@ abstract class AbstractPlainSocketImpl extends SocketImpl
* @param s the connection * @param s the connection
*/ */
protected void accept(SocketImpl s) throws IOException { protected void accept(SocketImpl s) throws IOException {
FileDescriptor fd = acquireFD(); acquireFD();
try { try {
socketAccept(s); socketAccept(s);
} finally { } finally {
...@@ -562,7 +566,6 @@ abstract class AbstractPlainSocketImpl extends SocketImpl ...@@ -562,7 +566,6 @@ abstract class AbstractPlainSocketImpl extends SocketImpl
close(); close();
} }
/* /*
* "Acquires" and returns the FileDescriptor for this impl * "Acquires" and returns the FileDescriptor for this impl
* *
......
...@@ -27,6 +27,7 @@ ...@@ -27,6 +27,7 @@
package java.nio; package java.nio;
import java.io.FileDescriptor;
import sun.misc.Cleaner; import sun.misc.Cleaner;
import sun.misc.Unsafe; import sun.misc.Unsafe;
import sun.misc.VM; import sun.misc.VM;
...@@ -114,7 +115,7 @@ class Direct$Type$Buffer$RW$$BO$ ...@@ -114,7 +115,7 @@ class Direct$Type$Buffer$RW$$BO$
// //
Direct$Type$Buffer$RW$(int cap) { // package-private Direct$Type$Buffer$RW$(int cap) { // package-private
#if[rw] #if[rw]
super(-1, 0, cap, cap, false); super(-1, 0, cap, cap);
boolean pa = VM.isDirectMemoryPageAligned(); boolean pa = VM.isDirectMemoryPageAligned();
int ps = Bits.pageSize(); int ps = Bits.pageSize();
long size = Math.max(1L, (long)cap + (pa ? ps : 0)); long size = Math.max(1L, (long)cap + (pa ? ps : 0));
...@@ -145,7 +146,7 @@ class Direct$Type$Buffer$RW$$BO$ ...@@ -145,7 +146,7 @@ class Direct$Type$Buffer$RW$$BO$
// Invoked only by JNI: NewDirectByteBuffer(void*, long) // Invoked only by JNI: NewDirectByteBuffer(void*, long)
// //
private Direct$Type$Buffer(long addr, int cap) { private Direct$Type$Buffer(long addr, int cap) {
super(-1, 0, cap, cap, false); super(-1, 0, cap, cap);
address = addr; address = addr;
cleaner = null; cleaner = null;
} }
...@@ -154,14 +155,17 @@ class Direct$Type$Buffer$RW$$BO$ ...@@ -154,14 +155,17 @@ class Direct$Type$Buffer$RW$$BO$
// For memory-mapped buffers -- invoked by FileChannelImpl via reflection // For memory-mapped buffers -- invoked by FileChannelImpl via reflection
// //
protected Direct$Type$Buffer$RW$(int cap, long addr, Runnable unmapper) { protected Direct$Type$Buffer$RW$(int cap, long addr,
FileDescriptor fd,
Runnable unmapper)
{
#if[rw] #if[rw]
super(-1, 0, cap, cap, true); super(-1, 0, cap, cap, fd);
address = addr; address = addr;
viewedBuffer = null; viewedBuffer = null;
cleaner = Cleaner.create(this, unmapper); cleaner = Cleaner.create(this, unmapper);
#else[rw] #else[rw]
super(cap, addr, unmapper); super(cap, addr, fd, unmapper);
#end[rw] #end[rw]
} }
......
...@@ -25,6 +25,7 @@ ...@@ -25,6 +25,7 @@
package java.nio; package java.nio;
import java.io.FileDescriptor;
import sun.misc.Unsafe; import sun.misc.Unsafe;
...@@ -71,26 +72,26 @@ public abstract class MappedByteBuffer ...@@ -71,26 +72,26 @@ public abstract class MappedByteBuffer
// for optimization purposes, it's easier to do it the other way around. // for optimization purposes, it's easier to do it the other way around.
// This works because DirectByteBuffer is a package-private class. // This works because DirectByteBuffer is a package-private class.
// Volatile to make sure that the finalization thread sees the current // For mapped buffers, a FileDescriptor that may be used for mapping
// value of this so that a region is not accidentally unmapped again later. // operations if valid; null if the buffer is not mapped.
volatile boolean isAMappedBuffer; // package-private private final FileDescriptor fd;
// This should only be invoked by the DirectByteBuffer constructors // This should only be invoked by the DirectByteBuffer constructors
// //
MappedByteBuffer(int mark, int pos, int lim, int cap, // package-private MappedByteBuffer(int mark, int pos, int lim, int cap, // package-private
boolean mapped) FileDescriptor fd)
{ {
super(mark, pos, lim, cap); super(mark, pos, lim, cap);
isAMappedBuffer = mapped; this.fd = fd;
} }
MappedByteBuffer(int mark, int pos, int lim, int cap) { // package-private MappedByteBuffer(int mark, int pos, int lim, int cap) { // package-private
super(mark, pos, lim, cap); super(mark, pos, lim, cap);
isAMappedBuffer = false; this.fd = null;
} }
private void checkMapped() { private void checkMapped() {
if (!isAMappedBuffer) if (fd == null)
// Can only happen if a luser explicitly casts a direct byte buffer // Can only happen if a luser explicitly casts a direct byte buffer
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
...@@ -191,13 +192,12 @@ public abstract class MappedByteBuffer ...@@ -191,13 +192,12 @@ public abstract class MappedByteBuffer
checkMapped(); checkMapped();
if ((address != 0) && (capacity() != 0)) { if ((address != 0) && (capacity() != 0)) {
long offset = mappingOffset(); long offset = mappingOffset();
force0(mappingAddress(offset), mappingLength(offset)); force0(fd, mappingAddress(offset), mappingLength(offset));
} }
return this; return this;
} }
private native boolean isLoaded0(long address, long length, int pageCount); private native boolean isLoaded0(long address, long length, int pageCount);
private native void load0(long address, long length); private native void load0(long address, long length);
private native void force0(long address, long length); private native void force0(FileDescriptor fd, long address, long length);
} }
...@@ -232,8 +232,6 @@ ...@@ -232,8 +232,6 @@
* <td>An asynchronous channel to a stream-oriented connecting socket</td></tr> * <td>An asynchronous channel to a stream-oriented connecting socket</td></tr>
* <tr><td valign=top><tt>{@link java.nio.channels.AsynchronousServerSocketChannel}&nbsp;&nbsp;</tt></td> * <tr><td valign=top><tt>{@link java.nio.channels.AsynchronousServerSocketChannel}&nbsp;&nbsp;</tt></td>
* <td>An asynchronous channel to a stream-oriented listening socket</td></tr> * <td>An asynchronous channel to a stream-oriented listening socket</td></tr>
* <tr><td valign=top><tt>{@link java.nio.channels.AsynchronousDatagramChannel}</tt></td>
* <td>An asynchronous channel to a datagram-oriented socket</td></tr>
* <tr><td valign=top><tt>{@link java.nio.channels.CompletionHandler}</tt></td> * <tr><td valign=top><tt>{@link java.nio.channels.CompletionHandler}</tt></td>
* <td>A handler for consuming the result of an asynchronous operation</td></tr> * <td>A handler for consuming the result of an asynchronous operation</td></tr>
* <tr><td valign=top><tt>{@link java.nio.channels.AsynchronousChannelGroup}</tt></td> * <tr><td valign=top><tt>{@link java.nio.channels.AsynchronousChannelGroup}</tt></td>
......
...@@ -26,7 +26,6 @@ ...@@ -26,7 +26,6 @@
package java.nio.channels.spi; package java.nio.channels.spi;
import java.nio.channels.*; import java.nio.channels.*;
import java.net.ProtocolFamily;
import java.io.IOException; import java.io.IOException;
import java.util.Iterator; import java.util.Iterator;
import java.util.ServiceLoader; import java.util.ServiceLoader;
...@@ -239,26 +238,4 @@ public abstract class AsynchronousChannelProvider { ...@@ -239,26 +238,4 @@ public abstract class AsynchronousChannelProvider {
*/ */
public abstract AsynchronousSocketChannel openAsynchronousSocketChannel public abstract AsynchronousSocketChannel openAsynchronousSocketChannel
(AsynchronousChannelGroup group) throws IOException; (AsynchronousChannelGroup group) throws IOException;
/**
* Opens an asynchronous datagram channel.
*
* @param family
* The protocol family, or {@code null} for the default protocol
* family
* @param group
* The group to which the channel is bound, or {@code null} to
* bind to the default group
*
* @return The new channel
*
* @throws IllegalChannelGroupException
* If the provider that created the group differs from this provider
* @throws ShutdownChannelGroupException
* The group is shutdown
* @throws IOException
* If an I/O error occurs
*/
public abstract AsynchronousDatagramChannel openAsynchronousDatagramChannel
(ProtocolFamily family, AsynchronousChannelGroup group) throws IOException;
} }
/*
* Copyright (c) 2010, 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 java.security;
import java.util.Set;
/**
* This interface specifies constraints for cryptographic algorithms,
* keys (key sizes), and other algorithm parameters.
* <p>
* {@code AlgorithmConstraints} objects are immutable. An implementation
* of this interface should not provide methods that can change the state
* of an instance once it has been created.
* <p>
* Note that {@code AlgorithmConstraints} can be used to represent the
* restrictions described by the security properties
* {@code jdk.certpath.disabledAlgorithms} and
* {@code jdk.tls.disabledAlgorithms}, or could be used by a
* concrete {@code PKIXCertPathChecker} to check whether a specified
* certificate in the certification path contains the required algorithm
* constraints.
*
* @see javax.net.ssl.SSLParameters#getAlgorithmConstraints
* @see javax.net.ssl.SSLParameters#setAlgorithmConstraints(AlgorithmConstraints)
*
* @since 1.7
*/
public interface AlgorithmConstraints {
/**
* Determines whether an algorithm is granted permission for the
* specified cryptographic primitives.
*
* @param primitives a set of cryptographic primitives
* @param algorithm the algorithm name
* @param parameters the algorithm parameters, or null if no additional
* parameters
*
* @return true if the algorithm is permitted and can be used for all
* of the specified cryptographic primitives
*
* @throws IllegalArgumentException if primitives or algorithm is null
* or empty
*/
public boolean permits(Set<CryptoPrimitive> primitives,
String algorithm, AlgorithmParameters parameters);
/**
* Determines whether a key is granted permission for the specified
* cryptographic primitives.
* <p>
* This method is usually used to check key size and key usage.
*
* @param primitives a set of cryptographic primitives
* @param key the key
*
* @return true if the key can be used for all of the specified
* cryptographic primitives
*
* @throws IllegalArgumentException if primitives is null or empty,
* or the key is null
*/
public boolean permits(Set<CryptoPrimitive> primitives, Key key);
/**
* Determines whether an algorithm and the corresponding key are granted
* permission for the specified cryptographic primitives.
*
* @param primitives a set of cryptographic primitives
* @param algorithm the algorithm name
* @param key the key
* @param parameters the algorithm parameters, or null if no additional
* parameters
*
* @return true if the key and the algorithm can be used for all of the
* specified cryptographic primitives
*
* @throws IllegalArgumentException if primitives or algorithm is null
* or empty, or the key is null
*/
public boolean permits(Set<CryptoPrimitive> primitives,
String algorithm, Key key, AlgorithmParameters parameters);
}
/* /*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -23,71 +23,61 @@ ...@@ -23,71 +23,61 @@
* questions. * questions.
*/ */
package sun.java2d.pisces; package java.security;
/** /**
* The <code>LineSink</code> interface accepts a series of line * An enumeration of cryptographic primitives.
* drawing commands: <code>moveTo</code>, <code>lineTo</code>,
* <code>close</code> (equivalent to a <code>lineTo</code> command
* with an argument equal to the argument of the last
* <code>moveTo</code> command), and <code>end</code>.
*
* <p> A <code>Flattener</code> may be used to connect a general path
* source to a <code>LineSink</code>.
*
* <p> The <code>Renderer</code> class implements the
* <code>LineSink</code> interface.
* *
* @since 1.7
*/ */
public interface LineSink { public enum CryptoPrimitive {
/**
* Hash function
*/
MESSAGE_DIGEST,
/** /**
* Moves the current drawing position to the point <code>(x0, * Cryptographic random number generator
* y0)</code>.
*
* @param x0 the X coordinate
* @param y0 the Y coordinate
*/ */
public void moveTo(float x0, float y0); SECURE_RANDOM,
/** /**
* Provides a hint that the current segment should be joined to * Symmetric primitive: block cipher
* the following segment using an explicit miter or round join if
* required.
*
* <p> An application-generated path will generally have no need
* to contain calls to this method; they are typically introduced
* by a <code>Flattener</code> to mark segment divisions that
* appear in its input, and consumed by a <code>Stroker</code>
* that is responsible for emitting the miter or round join
* segments.
*
* <p> Other <code>LineSink</code> classes should simply pass this
* hint to their output sink as needed.
*/ */
public void lineJoin(); BLOCK_CIPHER,
/** /**
* Draws a line from the current drawing position to the point * Symmetric primitive: stream cipher
* <code>(x1, y1)</code> and sets the current drawing position to
* <code>(x1, y1)</code>.
*
* @param x1 the X coordinate
* @param y1 the Y coordinate
*/ */
public void lineTo(float x1, float y1); STREAM_CIPHER,
/** /**
* Closes the current path by drawing a line from the current * Symmetric primitive: message authentication code
* drawing position to the point specified by the moset recent
* <code>moveTo</code> command.
*/ */
public void close(); MAC,
/** /**
* Ends the current path. It may be necessary to end a path in * Symmetric primitive: key wrap
* order to allow end caps to be drawn.
*/ */
public void end(); KEY_WRAP,
/**
* Asymmetric primitive: public key encryption
*/
PUBLIC_KEY_ENCRYPTION,
/**
* Asymmetric primitive: signature scheme
*/
SIGNATURE,
/**
* Asymmetric primitive: key encapsulation mechanism
*/
KEY_ENCAPSULATION,
/**
* Asymmetric primitive: key agreement and key distribution
*/
KEY_AGREEMENT
} }
...@@ -44,11 +44,12 @@ import java.io.Serializable; ...@@ -44,11 +44,12 @@ import java.io.Serializable;
import java.lang.ref.SoftReference; import java.lang.ref.SoftReference;
import java.text.spi.DateFormatSymbolsProvider; import java.text.spi.DateFormatSymbolsProvider;
import java.util.Arrays; import java.util.Arrays;
import java.util.Hashtable;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.ResourceBundle; import java.util.ResourceBundle;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.spi.LocaleServiceProvider; import java.util.spi.LocaleServiceProvider;
import sun.util.LocaleServiceProviderPool; import sun.util.LocaleServiceProviderPool;
import sun.util.TimeZoneNameUtility; import sun.util.TimeZoneNameUtility;
...@@ -321,20 +322,64 @@ public class DateFormatSymbols implements Serializable, Cloneable { ...@@ -321,20 +322,64 @@ public class DateFormatSymbols implements Serializable, Cloneable {
* @since 1.6 * @since 1.6
*/ */
public static final DateFormatSymbols getInstance(Locale locale) { public static final DateFormatSymbols getInstance(Locale locale) {
DateFormatSymbols dfs = getProviderInstance(locale);
if (dfs != null) {
return dfs;
}
return (DateFormatSymbols) getCachedInstance(locale).clone();
}
/**
* Returns a DateFormatSymbols provided by a provider or found in
* the cache. Note that this method returns a cached instance,
* not its clone. Therefore, the instance should never be given to
* an application.
*/
static final DateFormatSymbols getInstanceRef(Locale locale) {
DateFormatSymbols dfs = getProviderInstance(locale);
if (dfs != null) {
return dfs;
}
return getCachedInstance(locale);
}
private static DateFormatSymbols getProviderInstance(Locale locale) {
DateFormatSymbols providersInstance = null;
// Check whether a provider can provide an implementation that's closer // Check whether a provider can provide an implementation that's closer
// to the requested locale than what the Java runtime itself can provide. // to the requested locale than what the Java runtime itself can provide.
LocaleServiceProviderPool pool = LocaleServiceProviderPool pool =
LocaleServiceProviderPool.getPool(DateFormatSymbolsProvider.class); LocaleServiceProviderPool.getPool(DateFormatSymbolsProvider.class);
if (pool.hasProviders()) { if (pool.hasProviders()) {
DateFormatSymbols providersInstance = pool.getLocalizedObject( providersInstance = pool.getLocalizedObject(
DateFormatSymbolsGetter.INSTANCE, locale); DateFormatSymbolsGetter.INSTANCE, locale);
if (providersInstance != null) { }
return providersInstance; return providersInstance;
}
/**
* Returns a cached DateFormatSymbols if it's found in the
* cache. Otherwise, this method returns a newly cached instance
* for the given locale.
*/
private static DateFormatSymbols getCachedInstance(Locale locale) {
SoftReference<DateFormatSymbols> ref = cachedInstances.get(locale);
DateFormatSymbols dfs = null;
if (ref == null || (dfs = ref.get()) == null) {
dfs = new DateFormatSymbols(locale);
ref = new SoftReference<DateFormatSymbols>(dfs);
SoftReference<DateFormatSymbols> x = cachedInstances.putIfAbsent(locale, ref);
if (x != null) {
DateFormatSymbols y = x.get();
if (y != null) {
dfs = y;
} else {
// Replace the empty SoftReference with ref.
cachedInstances.put(locale, ref);
}
} }
} }
return dfs;
return new DateFormatSymbols(locale);
} }
/** /**
...@@ -597,56 +642,44 @@ public class DateFormatSymbols implements Serializable, Cloneable { ...@@ -597,56 +642,44 @@ public class DateFormatSymbols implements Serializable, Cloneable {
static final int millisPerHour = 60*60*1000; static final int millisPerHour = 60*60*1000;
/** /**
* Cache to hold the FormatData and TimeZoneNames ResourceBundles * Cache to hold DateFormatSymbols instances per Locale.
* of a Locale.
*/ */
private static Hashtable cachedLocaleData = new Hashtable(3); private static final ConcurrentMap<Locale, SoftReference<DateFormatSymbols>> cachedInstances
= new ConcurrentHashMap<Locale, SoftReference<DateFormatSymbols>>(3);
/** private void initializeData(Locale desiredLocale) {
* Look up resource data for the desiredLocale in the cache; update the locale = desiredLocale;
* cache if necessary.
*/ // Copy values of a cached instance if any.
private static ResourceBundle cacheLookup(Locale desiredLocale) { SoftReference<DateFormatSymbols> ref = cachedInstances.get(locale);
ResourceBundle rb; DateFormatSymbols dfs;
SoftReference data if (ref != null && (dfs = ref.get()) != null) {
= (SoftReference)cachedLocaleData.get(desiredLocale); copyMembers(dfs, this);
if (data == null) { return;
rb = LocaleData.getDateFormatData(desiredLocale);
data = new SoftReference(rb);
cachedLocaleData.put(desiredLocale, data);
} else {
if ((rb = (ResourceBundle)data.get()) == null) {
rb = LocaleData.getDateFormatData(desiredLocale);
data = new SoftReference(rb);
}
} }
return rb;
}
private void initializeData(Locale desiredLocale) { // Initialize the fields from the ResourceBundle for locale.
int i; ResourceBundle resource = LocaleData.getDateFormatData(locale);
ResourceBundle resource = cacheLookup(desiredLocale);
// FIXME: cache only ResourceBundle. Hence every time, will do eras = resource.getStringArray("Eras");
// getObject(). This won't be necessary if the Resource itself
// is cached.
eras = (String[])resource.getObject("Eras");
months = resource.getStringArray("MonthNames"); months = resource.getStringArray("MonthNames");
shortMonths = resource.getStringArray("MonthAbbreviations"); shortMonths = resource.getStringArray("MonthAbbreviations");
String[] lWeekdays = resource.getStringArray("DayNames");
weekdays = new String[8];
weekdays[0] = ""; // 1-based
for (i=0; i<lWeekdays.length; i++)
weekdays[i+1] = lWeekdays[i];
String[] sWeekdays = resource.getStringArray("DayAbbreviations");
shortWeekdays = new String[8];
shortWeekdays[0] = ""; // 1-based
for (i=0; i<sWeekdays.length; i++)
shortWeekdays[i+1] = sWeekdays[i];
ampms = resource.getStringArray("AmPmMarkers"); ampms = resource.getStringArray("AmPmMarkers");
localPatternChars = resource.getString("DateTimePatternChars"); localPatternChars = resource.getString("DateTimePatternChars");
locale = desiredLocale; // Day of week names are stored in a 1-based array.
weekdays = toOneBasedArray(resource.getStringArray("DayNames"));
shortWeekdays = toOneBasedArray(resource.getStringArray("DayAbbreviations"));
}
private static String[] toOneBasedArray(String[] src) {
int len = src.length;
String[] dst = new String[len + 1];
dst[0] = "";
for (int i = 0; i < len; i++) {
dst[i + 1] = src[i];
}
return dst;
} }
/** /**
......
/* /*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -46,9 +46,10 @@ import java.math.BigInteger; ...@@ -46,9 +46,10 @@ import java.math.BigInteger;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Currency; import java.util.Currency;
import java.util.Hashtable;
import java.util.Locale; import java.util.Locale;
import java.util.ResourceBundle; import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import sun.util.resources.LocaleData; import sun.util.resources.LocaleData;
...@@ -394,14 +395,14 @@ public class DecimalFormat extends NumberFormat { ...@@ -394,14 +395,14 @@ public class DecimalFormat extends NumberFormat {
public DecimalFormat() { public DecimalFormat() {
Locale def = Locale.getDefault(Locale.Category.FORMAT); Locale def = Locale.getDefault(Locale.Category.FORMAT);
// try to get the pattern from the cache // try to get the pattern from the cache
String pattern = (String) cachedLocaleData.get(def); String pattern = cachedLocaleData.get(def);
if (pattern == null) { /* cache miss */ if (pattern == null) { /* cache miss */
// Get the pattern for the default locale. // Get the pattern for the default locale.
ResourceBundle rb = LocaleData.getNumberFormatData(def); ResourceBundle rb = LocaleData.getNumberFormatData(def);
String[] all = rb.getStringArray("NumberPatterns"); String[] all = rb.getStringArray("NumberPatterns");
pattern = all[0]; pattern = all[0];
/* update cache */ /* update cache */
cachedLocaleData.put(def, pattern); cachedLocaleData.putIfAbsent(def, pattern);
} }
// Always applyPattern after the symbols are set // Always applyPattern after the symbols are set
...@@ -3272,5 +3273,6 @@ public class DecimalFormat extends NumberFormat { ...@@ -3272,5 +3273,6 @@ public class DecimalFormat extends NumberFormat {
/** /**
* Cache to hold the NumberPattern of a Locale. * Cache to hold the NumberPattern of a Locale.
*/ */
private static Hashtable cachedLocaleData = new Hashtable(3); private static final ConcurrentMap<Locale, String> cachedLocaleData
= new ConcurrentHashMap<Locale, String>(3);
} }
...@@ -44,13 +44,14 @@ import java.io.ObjectInputStream; ...@@ -44,13 +44,14 @@ import java.io.ObjectInputStream;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.MissingResourceException; import java.util.MissingResourceException;
import java.util.ResourceBundle; import java.util.ResourceBundle;
import java.util.SimpleTimeZone; import java.util.SimpleTimeZone;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import sun.util.calendar.CalendarUtils; import sun.util.calendar.CalendarUtils;
import sun.util.calendar.ZoneInfoFile; import sun.util.calendar.ZoneInfoFile;
import sun.util.resources.LocaleData; import sun.util.resources.LocaleData;
...@@ -503,14 +504,14 @@ public class SimpleDateFormat extends DateFormat { ...@@ -503,14 +504,14 @@ public class SimpleDateFormat extends DateFormat {
/** /**
* Cache to hold the DateTimePatterns of a Locale. * Cache to hold the DateTimePatterns of a Locale.
*/ */
private static Hashtable<String,String[]> cachedLocaleData private static final ConcurrentMap<String, String[]> cachedLocaleData
= new Hashtable<String,String[]>(3); = new ConcurrentHashMap<String, String[]>(3);
/** /**
* Cache NumberFormat instances with Locale key. * Cache NumberFormat instances with Locale key.
*/ */
private static Hashtable<Locale,NumberFormat> cachedNumberFormatData private static final ConcurrentMap<Locale, NumberFormat> cachedNumberFormatData
= new Hashtable<Locale,NumberFormat>(3); = new ConcurrentHashMap<Locale, NumberFormat>(3);
/** /**
* The Locale used to instantiate this * The Locale used to instantiate this
...@@ -579,7 +580,7 @@ public class SimpleDateFormat extends DateFormat { ...@@ -579,7 +580,7 @@ public class SimpleDateFormat extends DateFormat {
initializeCalendar(locale); initializeCalendar(locale);
this.pattern = pattern; this.pattern = pattern;
this.formatData = DateFormatSymbols.getInstance(locale); this.formatData = DateFormatSymbols.getInstanceRef(locale);
this.locale = locale; this.locale = locale;
initialize(locale); initialize(locale);
} }
...@@ -632,9 +633,9 @@ public class SimpleDateFormat extends DateFormat { ...@@ -632,9 +633,9 @@ public class SimpleDateFormat extends DateFormat {
dateTimePatterns = r.getStringArray("DateTimePatterns"); dateTimePatterns = r.getStringArray("DateTimePatterns");
} }
/* update cache */ /* update cache */
cachedLocaleData.put(key, dateTimePatterns); cachedLocaleData.putIfAbsent(key, dateTimePatterns);
} }
formatData = DateFormatSymbols.getInstance(loc); formatData = DateFormatSymbols.getInstanceRef(loc);
if ((timeStyle >= 0) && (dateStyle >= 0)) { if ((timeStyle >= 0) && (dateStyle >= 0)) {
Object[] dateTimeArgs = {dateTimePatterns[timeStyle], Object[] dateTimeArgs = {dateTimePatterns[timeStyle],
dateTimePatterns[dateStyle + 4]}; dateTimePatterns[dateStyle + 4]};
...@@ -665,7 +666,7 @@ public class SimpleDateFormat extends DateFormat { ...@@ -665,7 +666,7 @@ public class SimpleDateFormat extends DateFormat {
numberFormat.setGroupingUsed(false); numberFormat.setGroupingUsed(false);
/* update cache */ /* update cache */
cachedNumberFormatData.put(loc, numberFormat); cachedNumberFormatData.putIfAbsent(loc, numberFormat);
} }
numberFormat = (NumberFormat) numberFormat.clone(); numberFormat = (NumberFormat) numberFormat.clone();
...@@ -897,7 +898,7 @@ public class SimpleDateFormat extends DateFormat { ...@@ -897,7 +898,7 @@ public class SimpleDateFormat extends DateFormat {
* so we can call it from readObject(). * so we can call it from readObject().
*/ */
private void initializeDefaultCentury() { private void initializeDefaultCentury() {
calendar.setTime( new Date() ); calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add( Calendar.YEAR, -80 ); calendar.add( Calendar.YEAR, -80 );
parseAmbiguousDatesAsAfter(calendar.getTime()); parseAmbiguousDatesAsAfter(calendar.getTime());
} }
...@@ -921,7 +922,7 @@ public class SimpleDateFormat extends DateFormat { ...@@ -921,7 +922,7 @@ public class SimpleDateFormat extends DateFormat {
* @since 1.2 * @since 1.2
*/ */
public void set2DigitYearStart(Date startDate) { public void set2DigitYearStart(Date startDate) {
parseAmbiguousDatesAsAfter(startDate); parseAmbiguousDatesAsAfter(new Date(startDate.getTime()));
} }
/** /**
...@@ -934,7 +935,7 @@ public class SimpleDateFormat extends DateFormat { ...@@ -934,7 +935,7 @@ public class SimpleDateFormat extends DateFormat {
* @since 1.2 * @since 1.2
*/ */
public Date get2DigitYearStart() { public Date get2DigitYearStart() {
return defaultCenturyStart; return (Date) defaultCenturyStart.clone();
} }
/** /**
......
...@@ -176,6 +176,11 @@ public class ArrayList<E> extends AbstractList<E> ...@@ -176,6 +176,11 @@ public class ArrayList<E> extends AbstractList<E>
* @param minCapacity the desired minimum capacity * @param minCapacity the desired minimum capacity
*/ */
public void ensureCapacity(int minCapacity) { public void ensureCapacity(int minCapacity) {
if (minCapacity > 0)
ensureCapacityInternal(minCapacity);
}
private void ensureCapacityInternal(int minCapacity) {
modCount++; modCount++;
// overflow-conscious code // overflow-conscious code
if (minCapacity - elementData.length > 0) if (minCapacity - elementData.length > 0)
...@@ -403,7 +408,7 @@ public class ArrayList<E> extends AbstractList<E> ...@@ -403,7 +408,7 @@ public class ArrayList<E> extends AbstractList<E>
* @return <tt>true</tt> (as specified by {@link Collection#add}) * @return <tt>true</tt> (as specified by {@link Collection#add})
*/ */
public boolean add(E e) { public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!! ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e; elementData[size++] = e;
return true; return true;
} }
...@@ -420,7 +425,7 @@ public class ArrayList<E> extends AbstractList<E> ...@@ -420,7 +425,7 @@ public class ArrayList<E> extends AbstractList<E>
public void add(int index, E element) { public void add(int index, E element) {
rangeCheckForAdd(index); rangeCheckForAdd(index);
ensureCapacity(size + 1); // Increments modCount!! ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1, System.arraycopy(elementData, index, elementData, index + 1,
size - index); size - index);
elementData[index] = element; elementData[index] = element;
...@@ -524,7 +529,7 @@ public class ArrayList<E> extends AbstractList<E> ...@@ -524,7 +529,7 @@ public class ArrayList<E> extends AbstractList<E>
public boolean addAll(Collection<? extends E> c) { public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray(); Object[] a = c.toArray();
int numNew = a.length; int numNew = a.length;
ensureCapacity(size + numNew); // Increments modCount ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew); System.arraycopy(a, 0, elementData, size, numNew);
size += numNew; size += numNew;
return numNew != 0; return numNew != 0;
...@@ -550,7 +555,7 @@ public class ArrayList<E> extends AbstractList<E> ...@@ -550,7 +555,7 @@ public class ArrayList<E> extends AbstractList<E>
Object[] a = c.toArray(); Object[] a = c.toArray();
int numNew = a.length; int numNew = a.length;
ensureCapacity(size + numNew); // Increments modCount ensureCapacityInternal(size + numNew); // Increments modCount
int numMoved = size - index; int numMoved = size - index;
if (numMoved > 0) if (numMoved > 0)
......
...@@ -51,6 +51,8 @@ import java.security.PrivilegedExceptionAction; ...@@ -51,6 +51,8 @@ import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain; import java.security.ProtectionDomain;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.DateFormatSymbols; import java.text.DateFormatSymbols;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import sun.util.BuddhistCalendar; import sun.util.BuddhistCalendar;
import sun.util.calendar.ZoneInfo; import sun.util.calendar.ZoneInfo;
import sun.util.resources.LocaleData; import sun.util.resources.LocaleData;
...@@ -837,7 +839,8 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca ...@@ -837,7 +839,8 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca
* Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek * Cache to hold the firstDayOfWeek and minimalDaysInFirstWeek
* of a Locale. * of a Locale.
*/ */
private static Hashtable<Locale, int[]> cachedLocaleData = new Hashtable<Locale, int[]>(3); private static final ConcurrentMap<Locale, int[]> cachedLocaleData
= new ConcurrentHashMap<Locale, int[]>(3);
// Special values of stamp[] // Special values of stamp[]
/** /**
...@@ -1022,7 +1025,7 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca ...@@ -1022,7 +1025,7 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca
// returns a BuddhistCalendar instance. // returns a BuddhistCalendar instance.
if ("th".equals(aLocale.getLanguage()) if ("th".equals(aLocale.getLanguage())
&& ("TH".equals(aLocale.getCountry()))) { && ("TH".equals(aLocale.getCountry()))) {
cal = new BuddhistCalendar(zone, aLocale); cal = new BuddhistCalendar(zone, aLocale);
} else { } else {
cal = new GregorianCalendar(zone, aLocale); cal = new GregorianCalendar(zone, aLocale);
} }
...@@ -2588,7 +2591,7 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca ...@@ -2588,7 +2591,7 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable<Ca
data = new int[2]; data = new int[2];
data[0] = Integer.parseInt(bundle.getString("firstDayOfWeek")); data[0] = Integer.parseInt(bundle.getString("firstDayOfWeek"));
data[1] = Integer.parseInt(bundle.getString("minimalDaysInFirstWeek")); data[1] = Integer.parseInt(bundle.getString("minimalDaysInFirstWeek"));
cachedLocaleData.put(desiredLocale, data); cachedLocaleData.putIfAbsent(desiredLocale, data);
} }
firstDayOfWeek = data[0]; firstDayOfWeek = data[0];
minimalDaysInFirstWeek = data[1]; minimalDaysInFirstWeek = data[1];
......
...@@ -758,7 +758,7 @@ public final class Locale implements Cloneable, Serializable { ...@@ -758,7 +758,7 @@ public final class Locale implements Cloneable, Serializable {
} }
private static void initDefault() { private static void initDefault() {
String language, region, country, variant; String language, region, script, country, variant;
language = AccessController.doPrivileged( language = AccessController.doPrivileged(
new GetPropertyAction("user.language", "en")); new GetPropertyAction("user.language", "en"));
// for compatibility, check for old user.region property // for compatibility, check for old user.region property
...@@ -774,43 +774,41 @@ public final class Locale implements Cloneable, Serializable { ...@@ -774,43 +774,41 @@ public final class Locale implements Cloneable, Serializable {
country = region; country = region;
variant = ""; variant = "";
} }
script = "";
} else { } else {
script = AccessController.doPrivileged(
new GetPropertyAction("user.script", ""));
country = AccessController.doPrivileged( country = AccessController.doPrivileged(
new GetPropertyAction("user.country", "")); new GetPropertyAction("user.country", ""));
variant = AccessController.doPrivileged( variant = AccessController.doPrivileged(
new GetPropertyAction("user.variant", "")); new GetPropertyAction("user.variant", ""));
} }
defaultLocale = getInstance(language, country, variant); defaultLocale = getInstance(language, script, country, variant, null);
} }
private static void initDefault(Locale.Category category) { private static void initDefault(Locale.Category category) {
String language, region, country, variant; // make sure defaultLocale is initialized
if (defaultLocale == null) {
initDefault();
}
Locale defaultCategoryLocale = getInstance(
AccessController.doPrivileged(
new GetPropertyAction(category.languageKey, defaultLocale.getLanguage())),
AccessController.doPrivileged(
new GetPropertyAction(category.scriptKey, defaultLocale.getScript())),
AccessController.doPrivileged(
new GetPropertyAction(category.countryKey, defaultLocale.getCountry())),
AccessController.doPrivileged(
new GetPropertyAction(category.variantKey, defaultLocale.getVariant())),
null);
switch (category) { switch (category) {
case DISPLAY: case DISPLAY:
language = AccessController.doPrivileged( defaultDisplayLocale = defaultCategoryLocale;
new GetPropertyAction("user.language.display", ""));
if ("".equals(language)) {
defaultDisplayLocale = getDefault();
} else {
country = AccessController.doPrivileged(
new GetPropertyAction("user.country.display", ""));
variant = AccessController.doPrivileged(
new GetPropertyAction("user.variant.display", ""));
defaultDisplayLocale = getInstance(language, country, variant);
}
break; break;
case FORMAT: case FORMAT:
language = AccessController.doPrivileged( defaultFormatLocale = defaultCategoryLocale;
new GetPropertyAction("user.language.format", ""));
if ("".equals(language)) {
defaultFormatLocale = getDefault();
} else {
country = AccessController.doPrivileged(
new GetPropertyAction("user.country.format", ""));
variant = AccessController.doPrivileged(
new GetPropertyAction("user.variant.format", ""));
defaultFormatLocale = getInstance(language, country, variant);
}
break; break;
} }
} }
...@@ -2124,13 +2122,31 @@ public final class Locale implements Cloneable, Serializable { ...@@ -2124,13 +2122,31 @@ public final class Locale implements Cloneable, Serializable {
* Category used to represent the default locale for * Category used to represent the default locale for
* displaying user interfaces. * displaying user interfaces.
*/ */
DISPLAY, DISPLAY("user.language.display",
"user.script.display",
"user.country.display",
"user.variant.display"),
/** /**
* Category used to represent the default locale for * Category used to represent the default locale for
* formatting dates, numbers, and/or currencies. * formatting dates, numbers, and/or currencies.
*/ */
FORMAT, FORMAT("user.language.format",
"user.script.format",
"user.country.format",
"user.variant.format");
Category(String languageKey, String scriptKey, String countryKey, String variantKey) {
this.languageKey = languageKey;
this.scriptKey = scriptKey;
this.countryKey = countryKey;
this.variantKey = variantKey;
}
final String languageKey;
final String scriptKey;
final String countryKey;
final String variantKey;
} }
/** /**
......
...@@ -160,11 +160,6 @@ abstract public class TimeZone implements Serializable, Cloneable { ...@@ -160,11 +160,6 @@ abstract public class TimeZone implements Serializable, Cloneable {
private static final int ONE_HOUR = 60*ONE_MINUTE; private static final int ONE_HOUR = 60*ONE_MINUTE;
private static final int ONE_DAY = 24*ONE_HOUR; private static final int ONE_DAY = 24*ONE_HOUR;
/**
* Cache to hold the SimpleDateFormat objects for a Locale.
*/
private static Hashtable cachedLocaleData = new Hashtable(3);
// Proclaim serialization compatibility with JDK 1.1 // Proclaim serialization compatibility with JDK 1.1
static final long serialVersionUID = 3581463369166924961L; static final long serialVersionUID = 3581463369166924961L;
......
...@@ -222,8 +222,10 @@ public class Vector<E> ...@@ -222,8 +222,10 @@ public class Vector<E>
* @param minCapacity the desired minimum capacity * @param minCapacity the desired minimum capacity
*/ */
public synchronized void ensureCapacity(int minCapacity) { public synchronized void ensureCapacity(int minCapacity) {
modCount++; if (minCapacity > 0) {
ensureCapacityHelper(minCapacity); modCount++;
ensureCapacityHelper(minCapacity);
}
} }
/** /**
......
...@@ -529,8 +529,6 @@ public class LogRecord implements java.io.Serializable { ...@@ -529,8 +529,6 @@ public class LogRecord implements java.io.Serializable {
Throwable throwable = new Throwable(); Throwable throwable = new Throwable();
int depth = access.getStackTraceDepth(throwable); int depth = access.getStackTraceDepth(throwable);
String logClassName = "java.util.logging.Logger";
String plogClassName = "sun.util.logging.PlatformLogger";
boolean lookingForLogger = true; boolean lookingForLogger = true;
for (int ix = 0; ix < depth; ix++) { for (int ix = 0; ix < depth; ix++) {
// Calling getStackTraceElement directly prevents the VM // Calling getStackTraceElement directly prevents the VM
...@@ -538,13 +536,14 @@ public class LogRecord implements java.io.Serializable { ...@@ -538,13 +536,14 @@ public class LogRecord implements java.io.Serializable {
StackTraceElement frame = StackTraceElement frame =
access.getStackTraceElement(throwable, ix); access.getStackTraceElement(throwable, ix);
String cname = frame.getClassName(); String cname = frame.getClassName();
boolean isLoggerImpl = isLoggerImplFrame(cname);
if (lookingForLogger) { if (lookingForLogger) {
// Skip all frames until we have found the first logger frame. // Skip all frames until we have found the first logger frame.
if (cname.equals(logClassName) || cname.startsWith(plogClassName)) { if (isLoggerImpl) {
lookingForLogger = false; lookingForLogger = false;
} }
} else { } else {
if (!cname.equals(logClassName) && !cname.startsWith(plogClassName)) { if (!isLoggerImpl) {
// skip reflection call // skip reflection call
if (!cname.startsWith("java.lang.reflect.") && !cname.startsWith("sun.reflect.")) { if (!cname.startsWith("java.lang.reflect.") && !cname.startsWith("sun.reflect.")) {
// We've found the relevant frame. // We've found the relevant frame.
...@@ -558,4 +557,11 @@ public class LogRecord implements java.io.Serializable { ...@@ -558,4 +557,11 @@ public class LogRecord implements java.io.Serializable {
// We haven't found a suitable frame, so just punt. This is // We haven't found a suitable frame, so just punt. This is
// OK as we are only committed to making a "best effort" here. // OK as we are only committed to making a "best effort" here.
} }
private boolean isLoggerImplFrame(String cname) {
// the log record could be created for a platform logger
return (cname.equals("java.util.logging.Logger") ||
cname.startsWith("java.util.logging.LoggingProxyImpl") ||
cname.startsWith("sun.util.logging."));
}
} }
...@@ -211,8 +211,8 @@ import java.util.Map; ...@@ -211,8 +211,8 @@ import java.util.Map;
* reverse DNS name of the organization that specifies the MBeans, * reverse DNS name of the organization that specifies the MBeans,
* followed by a period and a string whose interpretation is * followed by a period and a string whose interpretation is
* determined by that organization. For example, MBeans specified by * determined by that organization. For example, MBeans specified by
* Sun Microsystems Inc., DNS name <code>sun.com</code>, would have * <code>example.com</code> would have
* domains such as <code>com.sun.MyDomain</code>. This is essentially * domains such as <code>com.example.MyDomain</code>. This is essentially
* the same convention as for Java-language package names.</p> * the same convention as for Java-language package names.</p>
* *
* <p>The <b>serialVersionUID</b> of this class is <code>1081892073854801359L</code>. * <p>The <b>serialVersionUID</b> of this class is <code>1081892073854801359L</code>.
......
...@@ -35,18 +35,18 @@ ...@@ -35,18 +35,18 @@
. Please also read the important comment on basedir definition below. . Please also read the important comment on basedir definition below.
--> -->
<project name="JMX API Version 1.4 - Java SE 6 implementation" <project name="JMX API Version 1.4 - Java SE 6 implementation"
default="jar" default="jar"
basedir="../../../../.." basedir="../../../../.."
> >
<!-- IMPORTANT: BASEDIR DEFINITION <!-- IMPORTANT: BASEDIR DEFINITION
This file is assumed to be in: This file is assumed to be in:
<src_bundle_dir>/j2se/src/share/classes/javax/management <src_bundle_dir>/j2se/src/share/classes/javax/management
Thus the basedir for this project is defined above as: Thus the basedir for this project is defined above as:
basedir="../../../../.." basedir="../../../../.."
in order to be the parent dir of src subdir. in order to be the parent dir of src subdir.
Result of the build will be placed in ${basedir}/build_jmx Result of the build will be placed in ${basedir}/build_jmx
as defined by ${dir.build} property below. as defined by ${dir.build} property below.
--> -->
...@@ -163,14 +163,14 @@ ...@@ -163,14 +163,14 @@
<echo message=" BUILD_DATE = ${BUILD_DATE}" /> <echo message=" BUILD_DATE = ${BUILD_DATE}" />
</target> </target>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- Call classes subtargets and rmic stubs generation --> <!-- Call classes subtargets and rmic stubs generation -->
<target name="classes" depends="init,classes-javac,classes-rmic" <target name="classes" depends="init,classes-javac,classes-rmic"
description="Call classes subtargets and rmic stubs generation" description="Call classes subtargets and rmic stubs generation"
/> />
...@@ -183,13 +183,13 @@ ...@@ -183,13 +183,13 @@
<mkdir dir="${dir.build.classes}" /> <mkdir dir="${dir.build.classes}" />
<javac srcdir="${dir.src}" <javac srcdir="${dir.src}"
destdir="${dir.build.classes}" destdir="${dir.build.classes}"
source="${flag.javac.source}" source="${flag.javac.source}"
debug="${flag.debug}" debug="${flag.debug}"
debuglevel="${flag.debug.level}" debuglevel="${flag.debug.level}"
optimize="${flag.optimize}" optimize="${flag.optimize}"
includeAntRuntime="no" includeAntRuntime="no"
includeJavaRuntime="no" includeJavaRuntime="no"
> >
<include name="javax/management/**"/> <include name="javax/management/**"/>
<include name="com/sun/jmx/**"/> <include name="com/sun/jmx/**"/>
...@@ -253,7 +253,7 @@ ...@@ -253,7 +253,7 @@
<mkdir dir="${dir.build.lib}" /> <mkdir dir="${dir.build.lib}" />
<jar jarfile="${dir.build.lib}/jmx.jar" <jar jarfile="${dir.build.lib}/jmx.jar"
update="true" update="true"
> >
...@@ -269,10 +269,10 @@ ...@@ -269,10 +269,10 @@
<attribute name="Sealed" value="true" /> <attribute name="Sealed" value="true" />
<attribute name="Specification-Title" value="JMX(TM) API" /> <attribute name="Specification-Title" value="JMX(TM) API" />
<attribute name="Specification-Version" value="1.4" /> <attribute name="Specification-Version" value="1.4" />
<attribute name="Specification-Vendor" value="Sun Microsystems, Inc." /> <attribute name="Specification-Vendor" value="Oracle Corporation" />
<attribute name="Implementation-Title" value="JMX(TM) API, Java SE 6 implementation" /> <attribute name="Implementation-Title" value="JMX(TM) API, Java SE 6 implementation" />
<attribute name="Implementation-Version" value="${BUILD_DATE} rebuild of Mustang JMX sources" /> <attribute name="Implementation-Version" value="${BUILD_DATE} rebuild of Java SE JMX sources" />
<attribute name="Implementation-Vendor" value="Source bundle from Sun Microsystems, Inc. - Customer rebuilt" /> <attribute name="Implementation-Vendor" value="Source bundle from Oracle Corporation - Customer rebuilt" />
</section> </section>
</manifest> </manifest>
</jar> </jar>
...@@ -295,16 +295,16 @@ ...@@ -295,16 +295,16 @@
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- Delete build directory and all its contents --> <!-- Delete build directory and all its contents -->
<target name="clean-all" <target name="clean-all"
description="Delete build directory and all its contents" > description="Delete build directory and all its contents" >
<delete dir="${dir.build}" /> <delete dir="${dir.build}" />
</target> </target>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- Clean all and build everything --> <!-- Clean all and build everything -->
<target name="all" depends="clean-all,jar" <target name="all" depends="clean-all,jar"
description="Clean all and build everything" /> description="Clean all and build everything" />
......
...@@ -92,8 +92,6 @@ import javax.management.RuntimeOperationsException; ...@@ -92,8 +92,6 @@ import javax.management.RuntimeOperationsException;
* @since 1.5 * @since 1.5
*/ */
// Sun Microsystems, Sept. 2002: Revisited for JMX 1.2 (DF)
//
@SuppressWarnings("serial") // serialVersionUID is not constant @SuppressWarnings("serial") // serialVersionUID is not constant
public class ModelMBeanNotificationInfo public class ModelMBeanNotificationInfo
extends MBeanNotificationInfo extends MBeanNotificationInfo
......
/*
* Copyright (c) 2010, 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 javax.net.ssl;
/**
* Extends the <code>SSLSession</code> interface to support additional
* session attributes.
*
* @since 1.7
*/
public abstract class ExtendedSSLSession implements SSLSession {
/**
* Obtains an array of supported signature algorithms that the local side
* is willing to use.
* <p>
* Note: this method is used to indicate to the peer which signature
* algorithms may be used for digital signatures in TLS 1.2. It is
* not meaningful for TLS versions prior to 1.2.
* <p>
* The signature algorithm name must be a standard Java Security
* name (such as "SHA1withRSA", "SHA256withECDSA", and so on).
* See Appendix A in the <a href=
* "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture API Specification &amp; Reference </a>
* for information about standard algorithm names.
* <p>
* Note: the local supported signature algorithms should conform to
* the algorithm constraints specified by
* {@link SSLParameters#getAlgorithmConstraints getAlgorithmConstraints()}
* method in <code>SSLParameters</code>.
*
* @return An array of supported signature algorithms, in descending
* order of preference. The return value is an empty array if
* no signature algorithm is supported.
*
* @see SSLParameters#getAlgorithmConstraints
*/
public abstract String[] getLocalSupportedSignatureAlgorithms();
/**
* Obtains an array of supported signature algorithms that the peer is
* able to use.
* <p>
* Note: this method is used to indicate to the local side which signature
* algorithms may be used for digital signatures in TLS 1.2. It is
* not meaningful for TLS versions prior to 1.2.
* <p>
* The signature algorithm name must be a standard Java Security
* name (such as "SHA1withRSA", "SHA256withECDSA", and so on).
* See Appendix A in the <a href=
* "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture API Specification &amp; Reference </a>
* for information about standard algorithm names.
*
* @return An array of supported signature algorithms, in descending
* order of preference. The return value is an empty array if
* the peer has not sent the supported signature algorithms.
*
* @see X509KeyManager
* @see X509ExtendedKeyManager
*/
public abstract String[] getPeerSupportedSignatureAlgorithms();
}
/* /*
* Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -188,19 +188,8 @@ class HttpsURLConnection extends HttpURLConnection ...@@ -188,19 +188,8 @@ class HttpsURLConnection extends HttpURLConnection
* <p> * <p>
* The default implementation will deny such connections. * The default implementation will deny such connections.
*/ */
private static HostnameVerifier defaultHostnameVerifier; private static HostnameVerifier defaultHostnameVerifier =
new DefaultHostnameVerifier();
/**
* Initialize the default <code>HostnameVerifier</code>.
*/
static {
try {
defaultHostnameVerifier =
new sun.net.www.protocol.https.DefaultHostnameVerifier();
} catch (NoClassDefFoundError e) {
defaultHostnameVerifier = new DefaultHostnameVerifier();
}
}
/* /*
* The initial default <code>HostnameVerifier</code>. Should be * The initial default <code>HostnameVerifier</code>. Should be
......
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -967,6 +967,47 @@ public abstract class SSLEngine { ...@@ -967,6 +967,47 @@ public abstract class SSLEngine {
public abstract SSLSession getSession(); public abstract SSLSession getSession();
/**
* Returns the {@code SSLSession} being constructed during a SSL/TLS
* handshake.
* <p>
* TLS protocols may negotiate parameters that are needed when using
* an instance of this class, but before the {@code SSLSession} has
* been completely initialized and made available via {@code getSession}.
* For example, the list of valid signature algorithms may restrict
* the type of certificates that can used during TrustManager
* decisions, or the maximum TLS fragment packet sizes can be
* resized to better support the network environment.
* <p>
* This method provides early access to the {@code SSLSession} being
* constructed. Depending on how far the handshake has progressed,
* some data may not yet be available for use. For example, if a
* remote server will be sending a Certificate chain, but that chain
* has yet not been processed, the {@code getPeerCertificates}
* method of {@code SSLSession} will throw a
* SSLPeerUnverifiedException. Once that chain has been processed,
* {@code getPeerCertificates} will return the proper value.
*
* @see SSLSocket
* @see SSLSession
* @see ExtendedSSLSession
* @see X509ExtendedKeyManager
* @see X509ExtendedTrustManager
*
* @return null if this instance is not currently handshaking, or
* if the current handshake has not progressed far enough to
* create a basic SSLSession. Otherwise, this method returns the
* {@code SSLSession} currently being negotiated.
* @throws UnsupportedOperationException if the underlying provider
* does not implement the operation.
*
* @since 1.7
*/
public SSLSession getHandshakeSession() {
throw new UnsupportedOperationException();
}
/** /**
* Initiates handshaking (initial or renegotiation) on this SSLEngine. * Initiates handshaking (initial or renegotiation) on this SSLEngine.
* <P> * <P>
......
/* /*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -25,24 +25,29 @@ ...@@ -25,24 +25,29 @@
package javax.net.ssl; package javax.net.ssl;
import java.security.AlgorithmConstraints;
/** /**
* Encapsulates parameters for an SSL/TLS connection. The parameters * Encapsulates parameters for an SSL/TLS connection. The parameters
* are the list of ciphersuites to be accepted in an SSL/TLS handshake, * are the list of ciphersuites to be accepted in an SSL/TLS handshake,
* the list of protocols to be allowed, and whether SSL/TLS servers should * the list of protocols to be allowed, the endpoint identification
* request or require client authentication. * algorithm during SSL/TLS handshaking, the algorithm constraints and
* * whether SSL/TLS servers should request or require client authentication.
* <p>SSLParameters can be created via the constructors in this class. * <p>
* SSLParameters can be created via the constructors in this class.
* Objects can also be obtained using the <code>getSSLParameters()</code> * Objects can also be obtained using the <code>getSSLParameters()</code>
* methods in * methods in
* {@link SSLSocket#getSSLParameters SSLSocket} and * {@link SSLSocket#getSSLParameters SSLSocket} and
* {@link SSLServerSocket#getSSLParameters SSLServerSocket} and
* {@link SSLEngine#getSSLParameters SSLEngine} or the * {@link SSLEngine#getSSLParameters SSLEngine} or the
* {@link SSLContext#getDefaultSSLParameters getDefaultSSLParameters()} and * {@link SSLContext#getDefaultSSLParameters getDefaultSSLParameters()} and
* {@link SSLContext#getSupportedSSLParameters getSupportedSSLParameters()} * {@link SSLContext#getSupportedSSLParameters getSupportedSSLParameters()}
* methods in <code>SSLContext</code>. * methods in <code>SSLContext</code>.
* * <p>
* <P>SSLParameters can be applied to a connection via the methods * SSLParameters can be applied to a connection via the methods
* {@link SSLSocket#setSSLParameters SSLSocket.setSSLParameters()} and * {@link SSLSocket#setSSLParameters SSLSocket.setSSLParameters()} and
* {@link SSLEngine#setSSLParameters SSLEngine.getSSLParameters()}. * {@link SSLServerSocket#setSSLParameters SSLServerSocket.setSSLParameters()}
* and {@link SSLEngine#setSSLParameters SSLEngine.getSSLParameters()}.
* *
* @see SSLSocket * @see SSLSocket
* @see SSLEngine * @see SSLEngine
...@@ -56,11 +61,13 @@ public class SSLParameters { ...@@ -56,11 +61,13 @@ public class SSLParameters {
private String[] protocols; private String[] protocols;
private boolean wantClientAuth; private boolean wantClientAuth;
private boolean needClientAuth; private boolean needClientAuth;
private String identificationAlgorithm;
private AlgorithmConstraints algorithmConstraints;
/** /**
* Constructs SSLParameters. * Constructs SSLParameters.
* * <p>
* <p>The cipherSuites and protocols values are set to <code>null</code>, * The cipherSuites and protocols values are set to <code>null</code>,
* wantClientAuth and needClientAuth are set to <code>false</code>. * wantClientAuth and needClientAuth are set to <code>false</code>.
*/ */
public SSLParameters() { public SSLParameters() {
...@@ -69,6 +76,7 @@ public class SSLParameters { ...@@ -69,6 +76,7 @@ public class SSLParameters {
/** /**
* Constructs SSLParameters from the specified array of ciphersuites. * Constructs SSLParameters from the specified array of ciphersuites.
* <p>
* Calling this constructor is equivalent to calling the no-args * Calling this constructor is equivalent to calling the no-args
* constructor followed by * constructor followed by
* <code>setCipherSuites(cipherSuites);</code>. * <code>setCipherSuites(cipherSuites);</code>.
...@@ -82,6 +90,7 @@ public class SSLParameters { ...@@ -82,6 +90,7 @@ public class SSLParameters {
/** /**
* Constructs SSLParameters from the specified array of ciphersuites * Constructs SSLParameters from the specified array of ciphersuites
* and protocols. * and protocols.
* <p>
* Calling this constructor is equivalent to calling the no-args * Calling this constructor is equivalent to calling the no-args
* constructor followed by * constructor followed by
* <code>setCipherSuites(cipherSuites); setProtocols(protocols);</code>. * <code>setCipherSuites(cipherSuites); setProtocols(protocols);</code>.
...@@ -178,4 +187,71 @@ public class SSLParameters { ...@@ -178,4 +187,71 @@ public class SSLParameters {
this.needClientAuth = needClientAuth; this.needClientAuth = needClientAuth;
} }
/**
* Returns the cryptographic algorithm constraints.
*
* @return the cryptographic algorithm constraints, or null if the
* constraints have not been set
*
* @see #setAlgorithmConstraints(AlgorithmConstraints)
*
* @since 1.7
*/
public AlgorithmConstraints getAlgorithmConstraints() {
return algorithmConstraints;
}
/**
* Sets the cryptographic algorithm constraints, which will be used
* in addition to any configured by the runtime environment.
* <p>
* If the <code>constraints</code> parameter is non-null, every
* cryptographic algorithm, key and algorithm parameters used in the
* SSL/TLS handshake must be permitted by the constraints.
*
* @param constraints the algorithm constraints (or null)
*
* @since 1.7
*/
public void setAlgorithmConstraints(AlgorithmConstraints constraints) {
// the constraints object is immutable
this.algorithmConstraints = constraints;
}
/**
* Gets the endpoint identification algorithm.
*
* @return the endpoint identification algorithm, or null if none
* has been set.
*
* @see X509ExtendedTrustManager
* @see #setEndpointIdentificationAlgorithm(String)
*
* @since 1.7
*/
public String getEndpointIdentificationAlgorithm() {
return identificationAlgorithm;
}
/**
* Sets the endpoint identification algorithm.
* <p>
* If the <code>algorithm</code> parameter is non-null or non-empty, the
* endpoint identification/verification procedures must be handled during
* SSL/TLS handshaking. This is to prevent man-in-the-middle attacks.
*
* @param algorithm The standard string name of the endpoint
* identification algorithm (or null). See Appendix A in the <a href=
* "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture API Specification &amp; Reference </a>
* for information about standard algorithm names.
*
* @see X509ExtendedTrustManager
*
* @since 1.7
*/
public void setEndpointIdentificationAlgorithm(String algorithm) {
this.identificationAlgorithm = algorithm;
}
} }
/* /*
* Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -56,8 +56,8 @@ import java.net.*; ...@@ -56,8 +56,8 @@ import java.net.*;
* @since 1.4 * @since 1.4
* @author David Brownell * @author David Brownell
*/ */
public abstract class SSLServerSocket extends ServerSocket public abstract class SSLServerSocket extends ServerSocket {
{
/** /**
* Used only by subclasses. * Used only by subclasses.
* <P> * <P>
...@@ -449,8 +449,79 @@ public abstract class SSLServerSocket extends ServerSocket ...@@ -449,8 +449,79 @@ public abstract class SSLServerSocket extends ServerSocket
* *
* @return true indicates that sessions may be created; this * @return true indicates that sessions may be created; this
* is the default. false indicates that an existing * is the default. false indicates that an existing
* session must be resumed. * session must be resumed
* @see #setEnableSessionCreation(boolean) * @see #setEnableSessionCreation(boolean)
*/ */
public abstract boolean getEnableSessionCreation(); public abstract boolean getEnableSessionCreation();
/**
* Returns the SSLParameters in effect for newly accepted connections.
* The ciphersuites and protocols of the returned SSLParameters
* are always non-null.
*
* @return the SSLParameters in effect for newly accepted connections
*
* @see #setSSLParameters(SSLParameters)
*
* @since 1.7
*/
public SSLParameters getSSLParameters() {
SSLParameters parameters = new SSLParameters();
parameters.setCipherSuites(getEnabledCipherSuites());
parameters.setProtocols(getEnabledProtocols());
if (getNeedClientAuth()) {
parameters.setNeedClientAuth(true);
} else if (getWantClientAuth()) {
parameters.setWantClientAuth(true);
}
return parameters;
}
/**
* Applies SSLParameters to newly accepted connections.
*
* <p>This means:
* <ul>
* <li>if <code>params.getCipherSuites()</code> is non-null,
* <code>setEnabledCipherSuites()</code> is called with that value
* <li>if <code>params.getProtocols()</code> is non-null,
* <code>setEnabledProtocols()</code> is called with that value
* <li>if <code>params.getNeedClientAuth()</code> or
* <code>params.getWantClientAuth()</code> return <code>true</code>,
* <code>setNeedClientAuth(true)</code> and
* <code>setWantClientAuth(true)</code> are called, respectively;
* otherwise <code>setWantClientAuth(false)</code> is called.
* </ul>
*
* @param params the parameters
* @throws IllegalArgumentException if the setEnabledCipherSuites() or
* the setEnabledProtocols() call fails
*
* @see #getSSLParameters()
*
* @since 1.7
*/
public void setSSLParameters(SSLParameters params) {
String[] s;
s = params.getCipherSuites();
if (s != null) {
setEnabledCipherSuites(s);
}
s = params.getProtocols();
if (s != null) {
setEnabledProtocols(s);
}
if (params.getNeedClientAuth()) {
setNeedClientAuth(true);
} else if (params.getWantClientAuth()) {
setWantClientAuth(true);
} else {
setWantClientAuth(false);
}
}
} }
/* /*
* Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -370,6 +370,51 @@ public abstract class SSLSocket extends Socket ...@@ -370,6 +370,51 @@ public abstract class SSLSocket extends Socket
public abstract SSLSession getSession(); public abstract SSLSession getSession();
/**
* Returns the {@code SSLSession} being constructed during a SSL/TLS
* handshake.
* <p>
* TLS protocols may negotiate parameters that are needed when using
* an instance of this class, but before the {@code SSLSession} has
* been completely initialized and made available via {@code getSession}.
* For example, the list of valid signature algorithms may restrict
* the type of certificates that can used during TrustManager
* decisions, or the maximum TLS fragment packet sizes can be
* resized to better support the network environment.
* <p>
* This method provides early access to the {@code SSLSession} being
* constructed. Depending on how far the handshake has progressed,
* some data may not yet be available for use. For example, if a
* remote server will be sending a Certificate chain, but that chain
* has yet not been processed, the {@code getPeerCertificates}
* method of {@code SSLSession} will throw a
* SSLPeerUnverifiedException. Once that chain has been processed,
* {@code getPeerCertificates} will return the proper value.
* <p>
* Unlike {@link #getSession()}, this method does not initiate the
* initial handshake and does not block until handshaking is
* complete.
*
* @see SSLEngine
* @see SSLSession
* @see ExtendedSSLSession
* @see X509ExtendedKeyManager
* @see X509ExtendedTrustManager
*
* @return null if this instance is not currently handshaking, or
* if the current handshake has not progressed far enough to
* create a basic SSLSession. Otherwise, this method returns the
* {@code SSLSession} currently being negotiated.
* @throws UnsupportedOperationException if the underlying provider
* does not implement the operation.
*
* @since 1.7
*/
public SSLSession getHandshakeSession() {
throw new UnsupportedOperationException();
}
/** /**
* Registers an event listener to receive notifications that an * Registers an event listener to receive notifications that an
* SSL handshake has completed on this connection. * SSL handshake has completed on this connection.
......
/* /*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -30,6 +30,7 @@ import java.net.*; ...@@ -30,6 +30,7 @@ import java.net.*;
import javax.net.SocketFactory; import javax.net.SocketFactory;
import java.io.IOException; import java.io.IOException;
import java.security.*; import java.security.*;
import java.util.Locale;
import sun.security.action.GetPropertyAction; import sun.security.action.GetPropertyAction;
...@@ -50,7 +51,8 @@ public abstract class SSLSocketFactory extends SocketFactory ...@@ -50,7 +51,8 @@ public abstract class SSLSocketFactory extends SocketFactory
static { static {
String s = java.security.AccessController.doPrivileged( String s = java.security.AccessController.doPrivileged(
new GetPropertyAction("javax.net.debug", "")).toLowerCase(); new GetPropertyAction("javax.net.debug", "")).toLowerCase(
Locale.ENGLISH);
DEBUG = s.contains("all") || s.contains("ssl"); DEBUG = s.contains("all") || s.contains("ssl");
} }
......
/*
* Copyright (c) 2010, 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 javax.net.ssl;
import java.net.Socket;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
/**
* Extensions to the <code>X509TrustManager</code> interface to support
* SSL/TLS connection sensitive trust management.
* <p>
* To prevent man-in-the-middle attacks, hostname checks can be done
* to verify that the hostname in an end-entity certificate matches the
* targeted hostname. TLS does not require such checks, but some protocols
* over TLS (such as HTTPS) do. In earlier versions of the JDK, the
* certificate chain checks were done at the SSL/TLS layer, and the hostname
* verification checks were done at the layer over TLS. This class allows
* for the checking to be done during a single call to this class.
* <p>
* RFC 2830 defines the server identification specification for the "LDAPS"
* algorithm. RFC 2818 defines both the server identification and the
* client identification specification for the "HTTPS" algorithm.
*
* @see X509TrustManager
* @see HostnameVerifier
*
* @since 1.7
*/
public abstract class X509ExtendedTrustManager implements X509TrustManager {
/**
* Given the partial or complete certificate chain provided by the
* peer, build and validate the certificate path based on the
* authentication type and ssl parameters.
* <p>
* The authentication type is determined by the actual certificate
* used. For instance, if RSAPublicKey is used, the authType
* should be "RSA". Checking is case-sensitive.
* <p>
* If the <code>socket</code> parameter is an instance of
* {@link javax.net.SSLSocket}, and the endpoint identification
* algorithm of the <code>SSLParameters</code> is non-empty, to prevent
* man-in-the-middle attacks, the address that the <code>socket</code>
* connected to should be checked against the peer's identity presented
* in the end-entity X509 certificate, as specified in the endpoint
* identification algorithm.
* <p>
* If the <code>socket</code> parameter is an instance of
* {@link javax.net.SSLSocket}, and the algorithm constraints of the
* <code>SSLParameters</code> is non-null, for every certificate in the
* certification path, fields such as subject public key, the signature
* algorithm, key usage, extended key usage, etc. need to conform to the
* algorithm constraints in place on this socket.
*
* @param chain the peer certificate chain
* @param authType the key exchange algorithm used
* @param socket the socket used for this connection. This parameter
* can be null, which indicates that implementations need not check
* the ssl parameters
* @throws IllegalArgumentException if null or zero-length array is passed
* in for the <code>chain</code> parameter or if null or zero-length
* string is passed in for the <code>authType</code> parameter
* @throws CertificateException if the certificate chain is not trusted
* by this TrustManager
*
* @see SSLParameters#getEndpointIdentificationProtocol
* @see SSLParameters#setEndpointIdentificationProtocol(String)
* @see SSLParameters#getAlgorithmConstraints
* @see SSLParameters#setAlgorithmConstraints(AlgorithmConstraints)
*/
public abstract void checkClientTrusted(X509Certificate[] chain,
String authType, Socket socket) throws CertificateException;
/**
* Given the partial or complete certificate chain provided by the
* peer, build and validate the certificate path based on the
* authentication type and ssl parameters.
* <p>
* The authentication type is the key exchange algorithm portion
* of the cipher suites represented as a String, such as "RSA",
* "DHE_DSS". Note: for some exportable cipher suites, the key
* exchange algorithm is determined at run time during the
* handshake. For instance, for TLS_RSA_EXPORT_WITH_RC4_40_MD5,
* the authType should be RSA_EXPORT when an ephemeral RSA key is
* used for the key exchange, and RSA when the key from the server
* certificate is used. Checking is case-sensitive.
* <p>
* If the <code>socket</code> parameter is an instance of
* {@link javax.net.SSLSocket}, and the endpoint identification
* algorithm of the <code>SSLParameters</code> is non-empty, to prevent
* man-in-the-middle attacks, the address that the <code>socket</code>
* connected to should be checked against the peer's identity presented
* in the end-entity X509 certificate, as specified in the endpoint
* identification algorithm.
* <p>
* If the <code>socket</code> parameter is an instance of
* {@link javax.net.SSLSocket}, and the algorithm constraints of the
* <code>SSLParameters</code> is non-null, for every certificate in the
* certification path, fields such as subject public key, the signature
* algorithm, key usage, extended key usage, etc. need to conform to the
* algorithm constraints in place on this socket.
*
* @param chain the peer certificate chain
* @param authType the key exchange algorithm used
* @param socket the socket used for this connection. This parameter
* can be null, which indicates that implementations need not check
* the ssl parameters
* @throws IllegalArgumentException if null or zero-length array is passed
* in for the <code>chain</code> parameter or if null or zero-length
* string is passed in for the <code>authType</code> parameter
* @throws CertificateException if the certificate chain is not trusted
* by this TrustManager
*
* @see SSLParameters#getEndpointIdentificationProtocol
* @see SSLParameters#setEndpointIdentificationProtocol(String)
* @see SSLParameters#getAlgorithmConstraints
* @see SSLParameters#setAlgorithmConstraints(AlgorithmConstraints)
*/
public abstract void checkServerTrusted(X509Certificate[] chain,
String authType, Socket socket) throws CertificateException;
/**
* Given the partial or complete certificate chain provided by the
* peer, build and validate the certificate path based on the
* authentication type and ssl parameters.
* <p>
* The authentication type is determined by the actual certificate
* used. For instance, if RSAPublicKey is used, the authType
* should be "RSA". Checking is case-sensitive.
* <p>
* If the <code>engine</code> parameter is available, and the endpoint
* identification algorithm of the <code>SSLParameters</code> is
* non-empty, to prevent man-in-the-middle attacks, the address that
* the <code>engine</code> connected to should be checked against
* the peer's identity presented in the end-entity X509 certificate,
* as specified in the endpoint identification algorithm.
* <p>
* If the <code>engine</code> parameter is available, and the algorithm
* constraints of the <code>SSLParameters</code> is non-null, for every
* certificate in the certification path, fields such as subject public
* key, the signature algorithm, key usage, extended key usage, etc.
* need to conform to the algorithm constraints in place on this engine.
*
* @param chain the peer certificate chain
* @param authType the key exchange algorithm used
* @param engine the engine used for this connection. This parameter
* can be null, which indicates that implementations need not check
* the ssl parameters
* @throws IllegalArgumentException if null or zero-length array is passed
* in for the <code>chain</code> parameter or if null or zero-length
* string is passed in for the <code>authType</code> parameter
* @throws CertificateException if the certificate chain is not trusted
* by this TrustManager
*
* @see SSLParameters#getEndpointIdentificationProtocol
* @see SSLParameters#setEndpointIdentificationProtocol(String)
* @see SSLParameters#getAlgorithmConstraints
* @see SSLParameters#setAlgorithmConstraints(AlgorithmConstraints)
*/
public abstract void checkClientTrusted(X509Certificate[] chain,
String authType, SSLEngine engine) throws CertificateException;
/**
* Given the partial or complete certificate chain provided by the
* peer, build and validate the certificate path based on the
* authentication type and ssl parameters.
* <p>
* The authentication type is the key exchange algorithm portion
* of the cipher suites represented as a String, such as "RSA",
* "DHE_DSS". Note: for some exportable cipher suites, the key
* exchange algorithm is determined at run time during the
* handshake. For instance, for TLS_RSA_EXPORT_WITH_RC4_40_MD5,
* the authType should be RSA_EXPORT when an ephemeral RSA key is
* used for the key exchange, and RSA when the key from the server
* certificate is used. Checking is case-sensitive.
* <p>
* If the <code>engine</code> parameter is available, and the endpoint
* identification algorithm of the <code>SSLParameters</code> is
* non-empty, to prevent man-in-the-middle attacks, the address that
* the <code>engine</code> connected to should be checked against
* the peer's identity presented in the end-entity X509 certificate,
* as specified in the endpoint identification algorithm.
* <p>
* If the <code>engine</code> parameter is available, and the algorithm
* constraints of the <code>SSLParameters</code> is non-null, for every
* certificate in the certification path, fields such as subject public
* key, the signature algorithm, key usage, extended key usage, etc.
* need to conform to the algorithm constraints in place on this engine.
*
* @param chain the peer certificate chain
* @param authType the key exchange algorithm used
* @param engine the engine used for this connection. This parameter
* can be null, which indicates that implementations need not check
* the ssl parameters
* @throws IllegalArgumentException if null or zero-length array is passed
* in for the <code>chain</code> parameter or if null or zero-length
* string is passed in for the <code>authType</code> parameter
* @throws CertificateException if the certificate chain is not trusted
* by this TrustManager
*
* @see SSLParameters#getEndpointIdentificationProtocol
* @see SSLParameters#setEndpointIdentificationProtocol(String)
* @see SSLParameters#getAlgorithmConstraints
* @see SSLParameters#setAlgorithmConstraints(AlgorithmConstraints)
*/
public abstract void checkServerTrusted(X509Certificate[] chain,
String authType, SSLEngine engine) throws CertificateException;
}
...@@ -24,8 +24,10 @@ ...@@ -24,8 +24,10 @@
*/ */
package javax.swing; package javax.swing;
import java.awt.BasicStroke;
import java.awt.Color; import java.awt.Color;
import java.awt.Font; import java.awt.Font;
import java.awt.Paint;
import javax.swing.border.*; import javax.swing.border.*;
/** /**
...@@ -636,4 +638,125 @@ public class BorderFactory ...@@ -636,4 +638,125 @@ public class BorderFactory
Icon tileIcon) { Icon tileIcon) {
return new MatteBorder(top, left, bottom, right, tileIcon); return new MatteBorder(top, left, bottom, right, tileIcon);
} }
//// StrokeBorder //////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/**
* Creates a border of the specified {@code stroke}.
* The component's foreground color will be used to render the border.
*
* @param stroke the {@link BasicStroke} object used to stroke a shape
* @return the {@code Border} object
*
* @throws NullPointerException if the specified {@code stroke} is {@code null}
*
* @since 1.7
*/
public static Border createStrokeBorder(BasicStroke stroke) {
return new StrokeBorder(stroke);
}
/**
* Creates a border of the specified {@code stroke} and {@code paint}.
* If the specified {@code paint} is {@code null},
* the component's foreground color will be used to render the border.
*
* @param stroke the {@link BasicStroke} object used to stroke a shape
* @param paint the {@link Paint} object used to generate a color
* @return the {@code Border} object
*
* @throws NullPointerException if the specified {@code stroke} is {@code null}
*
* @since 1.7
*/
public static Border createStrokeBorder(BasicStroke stroke, Paint paint) {
return new StrokeBorder(stroke, paint);
}
//// DashedBorder //////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
private static Border sharedDashedBorder;
/**
* Creates a dashed border of the specified {@code paint}.
* If the specified {@code paint} is {@code null},
* the component's foreground color will be used to render the border.
* The width of a dash line is equal to {@code 1}.
* The relative length of a dash line and
* the relative spacing between dash lines are equal to {@code 1}.
* A dash line is not rounded.
*
* @param paint the {@link Paint} object used to generate a color
* @return the {@code Border} object
*
* @since 1.7
*/
public static Border createDashedBorder(Paint paint) {
return createDashedBorder(paint, 1.0f, 1.0f, 1.0f, false);
}
/**
* Creates a dashed border of the specified {@code paint},
* relative {@code length}, and relative {@code spacing}.
* If the specified {@code paint} is {@code null},
* the component's foreground color will be used to render the border.
* The width of a dash line is equal to {@code 1}.
* A dash line is not rounded.
*
* @param paint the {@link Paint} object used to generate a color
* @param length the relative length of a dash line
* @param spacing the relative spacing between dash lines
* @return the {@code Border} object
*
* @throws IllegalArgumentException if the specified {@code length} is less than {@code 1}, or
* if the specified {@code spacing} is less than {@code 0}
* @since 1.7
*/
public static Border createDashedBorder(Paint paint, float length, float spacing) {
return createDashedBorder(paint, 1.0f, length, spacing, false);
}
/**
* Creates a dashed border of the specified {@code paint}, {@code thickness},
* line shape, relative {@code length}, and relative {@code spacing}.
* If the specified {@code paint} is {@code null},
* the component's foreground color will be used to render the border.
*
* @param paint the {@link Paint} object used to generate a color
* @param thickness the width of a dash line
* @param length the relative length of a dash line
* @param spacing the relative spacing between dash lines
* @param rounded whether or not line ends should be round
* @return the {@code Border} object
*
* @throws IllegalArgumentException if the specified {@code thickness} is less than {@code 1}, or
* if the specified {@code length} is less than {@code 1}, or
* if the specified {@code spacing} is less than {@code 0}
* @since 1.7
*/
public static Border createDashedBorder(Paint paint, float thickness, float length, float spacing, boolean rounded) {
boolean shared = !rounded && (paint == null) && (thickness == 1.0f) && (length == 1.0f) && (spacing == 1.0f);
if (shared && (sharedDashedBorder != null)) {
return sharedDashedBorder;
}
if (thickness < 1.0f) {
throw new IllegalArgumentException("thickness is less than 1");
}
if (length < 1.0f) {
throw new IllegalArgumentException("length is less than 1");
}
if (spacing < 0.0f) {
throw new IllegalArgumentException("spacing is less than 0");
}
int cap = rounded ? BasicStroke.CAP_ROUND : BasicStroke.CAP_SQUARE;
int join = rounded ? BasicStroke.JOIN_ROUND : BasicStroke.JOIN_MITER;
float[] array = { thickness * (length - 1.0f), thickness * (spacing + 1.0f) };
Border border = createStrokeBorder(new BasicStroke(thickness, cap, join, thickness * 2.0f, array, 0.0f), paint);
if (shared) {
sharedDashedBorder = border;
}
return border;
}
} }
...@@ -1322,13 +1322,11 @@ public class DebugGraphics extends Graphics { ...@@ -1322,13 +1322,11 @@ public class DebugGraphics extends Graphics {
} }
String toShortString() { String toShortString() {
StringBuffer buffer = new StringBuffer("Graphics" + (isDrawingBuffer() ? "<B>" : "") + "(" + graphicsID + "-" + debugOptions + ")"); return "Graphics" + (isDrawingBuffer() ? "<B>" : "") + "(" + graphicsID + "-" + debugOptions + ")";
return buffer.toString();
} }
String pointToString(int x, int y) { String pointToString(int x, int y) {
StringBuffer buffer = new StringBuffer("(" + x + ", " + y + ")"); return "(" + x + ", " + y + ")";
return buffer.toString();
} }
/** Enables/disables diagnostic information about every graphics /** Enables/disables diagnostic information about every graphics
......
...@@ -4783,21 +4783,11 @@ public abstract class JComponent extends Container implements Serializable, ...@@ -4783,21 +4783,11 @@ public abstract class JComponent extends Container implements Serializable,
* @param y the y value of the dirty region * @param y the y value of the dirty region
* @param width the width of the dirty region * @param width the width of the dirty region
* @param height the height of the dirty region * @param height the height of the dirty region
* @see #isPaintingOrigin()
* @see java.awt.Component#isShowing * @see java.awt.Component#isShowing
* @see RepaintManager#addDirtyRegion * @see RepaintManager#addDirtyRegion
*/ */
public void repaint(long tm, int x, int y, int width, int height) { public void repaint(long tm, int x, int y, int width, int height) {
Container p = this;
while ((p = p.getParent()) instanceof JComponent) {
JComponent jp = (JComponent) p;
if (jp.isPaintingOrigin()) {
Rectangle rectangle = SwingUtilities.convertRectangle(
this, new Rectangle(x, y, width, height), jp);
jp.repaint(tm,
rectangle.x, rectangle.y, rectangle.width, rectangle.height);
return;
}
}
RepaintManager.currentManager(this).addDirtyRegion(this, x, y, width, height); RepaintManager.currentManager(this).addDirtyRegion(this, x, y, width, height);
} }
...@@ -4808,6 +4798,7 @@ public abstract class JComponent extends Container implements Serializable, ...@@ -4808,6 +4798,7 @@ public abstract class JComponent extends Container implements Serializable,
* currently pending events have been dispatched. * currently pending events have been dispatched.
* *
* @param r a <code>Rectangle</code> containing the dirty region * @param r a <code>Rectangle</code> containing the dirty region
* @see #isPaintingOrigin()
* @see java.awt.Component#isShowing * @see java.awt.Component#isShowing
* @see RepaintManager#addDirtyRegion * @see RepaintManager#addDirtyRegion
*/ */
...@@ -4912,13 +4903,19 @@ public abstract class JComponent extends Container implements Serializable, ...@@ -4912,13 +4903,19 @@ public abstract class JComponent extends Container implements Serializable,
} }
/** /**
* Returns true if a paint triggered on a child component should cause * Returns {@code true} if a paint triggered on a child component should cause
* painting to originate from this Component, or one of its ancestors. * painting to originate from this Component, or one of its ancestors.
* <p/>
* Calling {@link JComponent#repaint} on a Swing component will be delegated to
* the first ancestor which {@code isPaintingOrigin()} returns {@true},
* if there are any.
* <p/>
* {@code JComponent} subclasses that need to be repainted when any of their
* children are repainted should override this method to return {@code true}.
* *
* @return true if painting should originate from this Component or * @return always returns {@code false}
* one of its ancestors.
*/ */
boolean isPaintingOrigin() { protected boolean isPaintingOrigin() {
return false; return false;
} }
......
...@@ -303,10 +303,9 @@ public class JDialog extends Dialog implements WindowConstants, ...@@ -303,10 +303,9 @@ public class JDialog extends Dialog implements WindowConstants,
* @param modal specifies whether dialog blocks user input to other top-level * @param modal specifies whether dialog blocks user input to other top-level
* windows when shown. If {@code true}, the modality type property is set to * windows when shown. If {@code true}, the modality type property is set to
* {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless. * {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless.
* @param gc the {@code GraphicsConfiguration} * @param gc the {@code GraphicsConfiguration} of the target screen device;
* of the target screen device. If {@code gc} is * if {@code null}, the default system {@code GraphicsConfiguration}
* {@code null}, the same * is assumed
* {@code GraphicsConfiguration} as the owning Frame is used.
* @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()} * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
* returns {@code true}. * returns {@code true}.
* @see java.awt.Dialog.ModalityType * @see java.awt.Dialog.ModalityType
...@@ -441,10 +440,9 @@ public class JDialog extends Dialog implements WindowConstants, ...@@ -441,10 +440,9 @@ public class JDialog extends Dialog implements WindowConstants,
* @param modal specifies whether dialog blocks user input to other top-level * @param modal specifies whether dialog blocks user input to other top-level
* windows when shown. If {@code true}, the modality type property is set to * windows when shown. If {@code true}, the modality type property is set to
* {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless * {@code DEFAULT_MODALITY_TYPE}, otherwise the dialog is modeless
* @param gc the {@code GraphicsConfiguration} * @param gc the {@code GraphicsConfiguration} of the target screen device;
* of the target screen device. If {@code gc} is * if {@code null}, the default system {@code GraphicsConfiguration}
* {@code null}, the same * is assumed
* {@code GraphicsConfiguration} as the owning Dialog is used.
* @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()} * @throws HeadlessException if {@code GraphicsEnvironment.isHeadless()}
* returns {@code true}. * returns {@code true}.
* @see java.awt.Dialog.ModalityType * @see java.awt.Dialog.ModalityType
...@@ -612,10 +610,8 @@ public class JDialog extends Dialog implements WindowConstants, ...@@ -612,10 +610,8 @@ public class JDialog extends Dialog implements WindowConstants,
* windows when shown. {@code null} value and unsupported modality * windows when shown. {@code null} value and unsupported modality
* types are equivalent to {@code MODELESS} * types are equivalent to {@code MODELESS}
* @param gc the {@code GraphicsConfiguration} of the target screen device; * @param gc the {@code GraphicsConfiguration} of the target screen device;
* if {@code null}, the {@code GraphicsConfiguration} from the owning * if {@code null}, the default system {@code GraphicsConfiguration}
* window is used; if {@code owner} is also {@code null}, the * is assumed
* system default {@code GraphicsConfiguration} is assumed
*
* @throws IllegalArgumentException * @throws IllegalArgumentException
* if the {@code owner} is not an instance of {@link java.awt.Dialog Dialog} * if the {@code owner} is not an instance of {@link java.awt.Dialog Dialog}
* or {@link java.awt.Frame Frame} * or {@link java.awt.Frame Frame}
......
...@@ -384,7 +384,7 @@ public final class JLayer<V extends Component> ...@@ -384,7 +384,7 @@ public final class JLayer<V extends Component>
* @return true * @return true
* @see JComponent#isPaintingOrigin() * @see JComponent#isPaintingOrigin()
*/ */
boolean isPaintingOrigin() { protected boolean isPaintingOrigin() {
return true; return true;
} }
......
...@@ -637,14 +637,14 @@ public class JViewport extends JComponent implements Accessible ...@@ -637,14 +637,14 @@ public class JViewport extends JComponent implements Accessible
} }
/** /**
* Returns true if scroll mode is a BACKINGSTORE_SCROLL_MODE to cause * Returns true if scroll mode is a {@code BACKINGSTORE_SCROLL_MODE} to cause
* painting to originate from <code>JViewport</code>, or one of its * painting to originate from {@code JViewport}, or one of its
* ancestors. Otherwise returns false. * ancestors. Otherwise returns {@code false}.
* *
* @return true if if scroll mode is a BACKINGSTORE_SCROLL_MODE. * @return true if if scroll mode is a {@code BACKINGSTORE_SCROLL_MODE}.
* @see JComponent#isPaintingOrigin() * @see JComponent#isPaintingOrigin()
*/ */
boolean isPaintingOrigin() { protected boolean isPaintingOrigin() {
return scrollMode == BACKINGSTORE_SCROLL_MODE; return scrollMode == BACKINGSTORE_SCROLL_MODE;
} }
......
...@@ -438,6 +438,7 @@ public class RepaintManager ...@@ -438,6 +438,7 @@ public class RepaintManager
* @param y Y coordinate of the region to repaint * @param y Y coordinate of the region to repaint
* @param w Width of the region to repaint * @param w Width of the region to repaint
* @param h Height of the region to repaint * @param h Height of the region to repaint
* @see JComponent#isPaintingOrigin()
* @see JComponent#repaint * @see JComponent#repaint
*/ */
public void addDirtyRegion(JComponent c, int x, int y, int w, int h) public void addDirtyRegion(JComponent c, int x, int y, int w, int h)
...@@ -447,6 +448,16 @@ public class RepaintManager ...@@ -447,6 +448,16 @@ public class RepaintManager
delegate.addDirtyRegion(c, x, y, w, h); delegate.addDirtyRegion(c, x, y, w, h);
return; return;
} }
Container p = c;
while ((p = p.getParent()) instanceof JComponent) {
JComponent jp = (JComponent) p;
if (jp.isPaintingOrigin()) {
Rectangle rectangle = SwingUtilities.convertRectangle(
c, new Rectangle(x, y, w, h), jp);
jp.repaint(0, rectangle.x, rectangle.y, rectangle.width, rectangle.height);
return;
}
}
addDirtyRegion0(c, x, y, w, h); addDirtyRegion0(c, x, y, w, h);
} }
......
/*
* Copyright (c) 2010, 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 javax.swing.border;
import java.awt.BasicStroke;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.beans.ConstructorProperties;
/**
* A class which implements a border of an arbitrary stroke.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI
* between applications running the same version of Swing.
* As of 1.4, support for long term storage of all JavaBeans&trade;
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Sergey A. Malenkov
*
* @since 1.7
*/
public class StrokeBorder extends AbstractBorder {
private final BasicStroke stroke;
private final Paint paint;
/**
* Creates a border of the specified {@code stroke}.
* The component's foreground color will be used to render the border.
*
* @param stroke the {@link BasicStroke} object used to stroke a shape
*
* @throws NullPointerException if the specified {@code stroke} is {@code null}
*/
public StrokeBorder(BasicStroke stroke) {
this(stroke, null);
}
/**
* Creates a border of the specified {@code stroke} and {@code paint}.
* If the specified {@code paint} is {@code null},
* the component's foreground color will be used to render the border.
*
* @param stroke the {@link BasicStroke} object used to stroke a shape
* @param paint the {@link Paint} object used to generate a color
*
* @throws NullPointerException if the specified {@code stroke} is {@code null}
*/
@ConstructorProperties({ "stroke", "paint" })
public StrokeBorder(BasicStroke stroke, Paint paint) {
if (stroke == null) {
throw new NullPointerException("border's stroke");
}
this.stroke = stroke;
this.paint = paint;
}
/**
* Paints the border for the specified component
* with the specified position and size.
*
* @param c the component for which this border is being painted
* @param g the paint graphics
* @param x the x position of the painted border
* @param y the y position of the painted border
* @param width the width of the painted border
* @param height the height of the painted border
*
* @throws NullPointerException if the specified {@code c} or {@code g} are {@code null}
*/
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
float size = this.stroke.getLineWidth();
if (size > 0.0f) {
g = g.create();
if (g instanceof Graphics2D) {
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(this.stroke);
g2d.setPaint(this.paint != null ? this.paint : c.getForeground());
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.draw(new Rectangle2D.Float(x + size / 2, y + size / 2, width - size, height - size));
}
g.dispose();
}
}
/**
* Reinitializes the {@code insets} parameter
* with this border's current insets.
* All insets are equal to the line width of the stroke.
*
* @param c the component for which this border insets value applies
* @param insets the {@code Insets} object to be reinitialized
* @return the reinitialized {@code insets} parameter
*
* @throws NullPointerException if the specified {@code insets} is {@code null}
*/
@Override
public Insets getBorderInsets(Component c, Insets insets) {
int size = (int) Math.ceil(this.stroke.getLineWidth());
insets.set(size, size, size, size);
return insets;
}
/**
* Returns the {@link BasicStroke} object used to stroke a shape
* during the border rendering.
*
* @return the {@link BasicStroke} object
*/
public BasicStroke getStroke() {
return this.stroke;
}
/**
* Returns the {@link Paint} object used to generate a color
* during the border rendering.
*
* @return the {@link Paint} object or {@code null}
* if the {@code paint} parameter is not set
*/
public Paint getPaint() {
return this.paint;
}
}
...@@ -362,6 +362,14 @@ public class BasicScrollPaneUI ...@@ -362,6 +362,14 @@ public class BasicScrollPaneUI
* @since 1.6 * @since 1.6
*/ */
public int getBaseline(JComponent c, int width, int height) { public int getBaseline(JComponent c, int width, int height) {
if (c == null) {
throw new NullPointerException("Component must be non-null");
}
if (width < 0 || height < 0) {
throw new IllegalArgumentException("Width and height must be >= 0");
}
JViewport viewport = scrollpane.getViewport(); JViewport viewport = scrollpane.getViewport();
Insets spInsets = scrollpane.getInsets(); Insets spInsets = scrollpane.getInsets();
int y = spInsets.top; int y = spInsets.top;
......
...@@ -115,10 +115,7 @@ public class SynthTabbedPaneUI extends BasicTabbedPaneUI ...@@ -115,10 +115,7 @@ public class SynthTabbedPaneUI extends BasicTabbedPaneUI
return new SynthTabbedPaneUI(); return new SynthTabbedPaneUI();
} }
private SynthTabbedPaneUI() { private boolean scrollableTabLayoutEnabled() {
}
private boolean scrollableTabLayoutEnabled() {
return (tabPane.getTabLayoutPolicy() == JTabbedPane.SCROLL_TAB_LAYOUT); return (tabPane.getTabLayoutPolicy() == JTabbedPane.SCROLL_TAB_LAYOUT);
} }
......
...@@ -186,6 +186,9 @@ public class DefaultTableCellRenderer extends JLabel ...@@ -186,6 +186,9 @@ public class DefaultTableCellRenderer extends JLabel
*/ */
public Component getTableCellRendererComponent(JTable table, Object value, public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) { boolean isSelected, boolean hasFocus, int row, int column) {
if (table == null) {
return this;
}
Color fg = null; Color fg = null;
Color bg = null; Color bg = null;
......
...@@ -1334,13 +1334,13 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou ...@@ -1334,13 +1334,13 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou
&& component.getClientProperty("JPasswordField.cutCopyAllowed") != && component.getClientProperty("JPasswordField.cutCopyAllowed") !=
Boolean.TRUE) { Boolean.TRUE) {
//fix for 4793761 //fix for 4793761
StringBuffer txt = null; StringBuilder txt = null;
char echoChar = ((JPasswordField)component).getEchoChar(); char echoChar = ((JPasswordField)component).getEchoChar();
int p0 = Math.min(getDot(), getMark()); int p0 = Math.min(getDot(), getMark());
int p1 = Math.max(getDot(), getMark()); int p1 = Math.max(getDot(), getMark());
for (int i = p0; i < p1; i++) { for (int i = p0; i < p1; i++) {
if (txt == null) { if (txt == null) {
txt = new StringBuffer(); txt = new StringBuilder();
} }
txt.append(echoChar); txt.append(echoChar);
} }
...@@ -1675,7 +1675,6 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou ...@@ -1675,7 +1675,6 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou
} }
return; return;
} }
int adjust = 0;
int offset = e.getOffset(); int offset = e.getOffset();
int length = e.getLength(); int length = e.getLength();
int newDot = dot; int newDot = dot;
...@@ -1759,7 +1758,6 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou ...@@ -1759,7 +1758,6 @@ public class DefaultCaret extends Rectangle implements Caret, FocusListener, Mou
} }
int offs0 = e.getOffset(); int offs0 = e.getOffset();
int offs1 = offs0 + e.getLength(); int offs1 = offs0 + e.getLength();
int adjust = 0;
int newDot = dot; int newDot = dot;
boolean adjustDotBias = false; boolean adjustDotBias = false;
int newMark = mark; int newMark = mark;
......
...@@ -132,7 +132,7 @@ public class DefaultStyledDocument extends AbstractDocument implements StyledDoc ...@@ -132,7 +132,7 @@ public class DefaultStyledDocument extends AbstractDocument implements StyledDoc
// install the content // install the content
Content c = getContent(); Content c = getContent();
int n = data.length; int n = data.length;
StringBuffer sb = new StringBuffer(); StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
ElementSpec es = data[i]; ElementSpec es = data[i];
if (es.getLength() > 0) { if (es.getLength() > 0) {
...@@ -191,7 +191,7 @@ public class DefaultStyledDocument extends AbstractDocument implements StyledDoc ...@@ -191,7 +191,7 @@ public class DefaultStyledDocument extends AbstractDocument implements StyledDoc
// install the content // install the content
Content c = getContent(); Content c = getContent();
int n = data.length; int n = data.length;
StringBuffer sb = new StringBuffer(); StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
ElementSpec es = data[i]; ElementSpec es = data[i];
if (es.getLength() > 0) { if (es.getLength() > 0) {
......
...@@ -30,7 +30,6 @@ import java.text.*; ...@@ -30,7 +30,6 @@ import java.text.*;
import java.text.AttributedCharacterIterator.Attribute; import java.text.AttributedCharacterIterator.Attribute;
import java.util.*; import java.util.*;
import javax.swing.*; import javax.swing.*;
import javax.swing.text.*;
/** /**
* <code>InternationalFormatter</code> extends <code>DefaultFormatter</code>, * <code>InternationalFormatter</code> extends <code>DefaultFormatter</code>,
...@@ -875,7 +874,6 @@ public class InternationalFormatter extends DefaultFormatter { ...@@ -875,7 +874,6 @@ public class InternationalFormatter extends DefaultFormatter {
(f instanceof AttributedCharacterIterator.Attribute)) { (f instanceof AttributedCharacterIterator.Attribute)) {
AttributedCharacterIterator.Attribute field = AttributedCharacterIterator.Attribute field =
(AttributedCharacterIterator.Attribute)f; (AttributedCharacterIterator.Attribute)f;
int index = 0;
iterator.first(); iterator.first();
while (iterator.getIndex() < start) { while (iterator.getIndex() < start) {
......
...@@ -35,10 +35,7 @@ import java.util.HashMap; ...@@ -35,10 +35,7 @@ import java.util.HashMap;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Vector; import java.util.Vector;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.*; import java.util.concurrent.*;
...@@ -4058,7 +4055,7 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A ...@@ -4058,7 +4055,7 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A
private static final Object KEYMAP_TABLE = private static final Object KEYMAP_TABLE =
new StringBuilder("JTextComponent_KeymapTable"); new StringBuilder("JTextComponent_KeymapTable");
private JTextComponent editor;
// //
// member variables used for on-the-spot input method // member variables used for on-the-spot input method
// editing style support // editing style support
...@@ -4748,14 +4745,14 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A ...@@ -4748,14 +4745,14 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A
processKeyEvent(ke); processKeyEvent(ke);
} }
} else { } else {
StringBuffer strBuf = new StringBuffer(); StringBuilder strBuf = new StringBuilder();
for (char c = text.current(); commitCount > 0; for (char c = text.current(); commitCount > 0;
c = text.next(), commitCount--) { c = text.next(), commitCount--) {
strBuf.append(c); strBuf.append(c);
} }
// map it to an ActionEvent // map it to an ActionEvent
mapCommittedTextToAction(new String(strBuf)); mapCommittedTextToAction(strBuf.toString());
} }
// Remember latest committed text end index // Remember latest committed text end index
...@@ -4801,7 +4798,7 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A ...@@ -4801,7 +4798,7 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A
private void createComposedTextAttribute(int composedIndex, private void createComposedTextAttribute(int composedIndex,
AttributedCharacterIterator text) { AttributedCharacterIterator text) {
Document doc = getDocument(); Document doc = getDocument();
StringBuffer strBuf = new StringBuffer(); StringBuilder strBuf = new StringBuilder();
// create attributed string with no attributes // create attributed string with no attributes
for (char c = text.setIndex(composedIndex); for (char c = text.setIndex(composedIndex);
...@@ -4809,7 +4806,7 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A ...@@ -4809,7 +4806,7 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A
strBuf.append(c); strBuf.append(c);
} }
composedTextContent = new String(strBuf); composedTextContent = strBuf.toString();
composedTextAttribute = new SimpleAttributeSet(); composedTextAttribute = new SimpleAttributeSet();
composedTextAttribute.addAttribute(StyleConstants.ComposedTextAttribute, composedTextAttribute.addAttribute(StyleConstants.ComposedTextAttribute,
new AttributedString(text, composedIndex, text.getEndIndex())); new AttributedString(text, composedIndex, text.getEndIndex()));
......
...@@ -29,7 +29,6 @@ import java.io.*; ...@@ -29,7 +29,6 @@ import java.io.*;
import java.text.*; import java.text.*;
import java.util.*; import java.util.*;
import javax.swing.*; import javax.swing.*;
import javax.swing.text.*;
/** /**
* <code>MaskFormatter</code> is used to format and edit strings. The behavior * <code>MaskFormatter</code> is used to format and edit strings. The behavior
...@@ -385,7 +384,7 @@ public class MaskFormatter extends DefaultFormatter { ...@@ -385,7 +384,7 @@ public class MaskFormatter extends DefaultFormatter {
*/ */
public String valueToString(Object value) throws ParseException { public String valueToString(Object value) throws ParseException {
String sValue = (value == null) ? "" : value.toString(); String sValue = (value == null) ? "" : value.toString();
StringBuffer result = new StringBuffer(); StringBuilder result = new StringBuilder();
String placeholder = getPlaceholder(); String placeholder = getPlaceholder();
int[] valueCounter = { 0 }; int[] valueCounter = { 0 };
...@@ -484,7 +483,7 @@ public class MaskFormatter extends DefaultFormatter { ...@@ -484,7 +483,7 @@ public class MaskFormatter extends DefaultFormatter {
* Invokes <code>append</code> on the mask characters in * Invokes <code>append</code> on the mask characters in
* <code>mask</code>. * <code>mask</code>.
*/ */
private void append(StringBuffer result, String value, int[] index, private void append(StringBuilder result, String value, int[] index,
String placeholder, MaskCharacter[] mask) String placeholder, MaskCharacter[] mask)
throws ParseException { throws ParseException {
for (int counter = 0, maxCounter = mask.length; for (int counter = 0, maxCounter = mask.length;
...@@ -611,13 +610,13 @@ public class MaskFormatter extends DefaultFormatter { ...@@ -611,13 +610,13 @@ public class MaskFormatter extends DefaultFormatter {
* Removes the literal characters from the passed in string. * Removes the literal characters from the passed in string.
*/ */
private String stripLiteralChars(String string) { private String stripLiteralChars(String string) {
StringBuffer sb = null; StringBuilder sb = null;
int last = 0; int last = 0;
for (int counter = 0, max = string.length(); counter < max; counter++){ for (int counter = 0, max = string.length(); counter < max; counter++){
if (isLiteral(counter)) { if (isLiteral(counter)) {
if (sb == null) { if (sb == null) {
sb = new StringBuffer(); sb = new StringBuilder();
if (counter > 0) { if (counter > 0) {
sb.append(string.substring(0, counter)); sb.append(string.substring(0, counter));
} }
...@@ -715,10 +714,10 @@ public class MaskFormatter extends DefaultFormatter { ...@@ -715,10 +714,10 @@ public class MaskFormatter extends DefaultFormatter {
*/ */
boolean canReplace(ReplaceHolder rh) { boolean canReplace(ReplaceHolder rh) {
// This method is rather long, but much of the burden is in // This method is rather long, but much of the burden is in
// maintaining a String and swapping to a StringBuffer only if // maintaining a String and swapping to a StringBuilder only if
// absolutely necessary. // absolutely necessary.
if (!getAllowsInvalid()) { if (!getAllowsInvalid()) {
StringBuffer replace = null; StringBuilder replace = null;
String text = rh.text; String text = rh.text;
int tl = (text != null) ? text.length() : 0; int tl = (text != null) ? text.length() : 0;
...@@ -737,7 +736,7 @@ public class MaskFormatter extends DefaultFormatter { ...@@ -737,7 +736,7 @@ public class MaskFormatter extends DefaultFormatter {
char aChar = text.charAt(textIndex); char aChar = text.charAt(textIndex);
if (aChar != getCharacter(rh.offset + counter, aChar)) { if (aChar != getCharacter(rh.offset + counter, aChar)) {
if (replace == null) { if (replace == null) {
replace = new StringBuffer(); replace = new StringBuilder();
if (textIndex > 0) { if (textIndex > 0) {
replace.append(text.substring(0, textIndex)); replace.append(text.substring(0, textIndex));
} }
...@@ -758,7 +757,7 @@ public class MaskFormatter extends DefaultFormatter { ...@@ -758,7 +757,7 @@ public class MaskFormatter extends DefaultFormatter {
} }
} }
else if (textIndex > 0) { else if (textIndex > 0) {
replace = new StringBuffer(max); replace = new StringBuilder(max);
replace.append(text.substring(0, textIndex)); replace.append(text.substring(0, textIndex));
replace.append(getLiteral(rh.offset + counter)); replace.append(getLiteral(rh.offset + counter));
if (textIndex < tl) { if (textIndex < tl) {
...@@ -780,7 +779,7 @@ public class MaskFormatter extends DefaultFormatter { ...@@ -780,7 +779,7 @@ public class MaskFormatter extends DefaultFormatter {
else if (textIndex >= tl) { else if (textIndex >= tl) {
// placeholder // placeholder
if (replace == null) { if (replace == null) {
replace = new StringBuffer(); replace = new StringBuilder();
if (text != null) { if (text != null) {
replace.append(text); replace.append(text);
} }
...@@ -863,7 +862,7 @@ public class MaskFormatter extends DefaultFormatter { ...@@ -863,7 +862,7 @@ public class MaskFormatter extends DefaultFormatter {
* Appends the necessary character in <code>formatting</code> at * Appends the necessary character in <code>formatting</code> at
* <code>index</code> to <code>buff</code>. * <code>index</code> to <code>buff</code>.
*/ */
public void append(StringBuffer buff, String formatting, int[] index, public void append(StringBuilder buff, String formatting, int[] index,
String placeholder) String placeholder)
throws ParseException { throws ParseException {
boolean inString = index[0] < formatting.length(); boolean inString = index[0] < formatting.length();
......
...@@ -27,7 +27,6 @@ package javax.swing.text; ...@@ -27,7 +27,6 @@ package javax.swing.text;
import java.lang.reflect.*; import java.lang.reflect.*;
import java.text.*; import java.text.*;
import java.util.*; import java.util.*;
import javax.swing.text.*;
/** /**
* <code>NumberFormatter</code> subclasses <code>InternationalFormatter</code> * <code>NumberFormatter</code> subclasses <code>InternationalFormatter</code>
...@@ -132,7 +131,7 @@ public class NumberFormatter extends InternationalFormatter { ...@@ -132,7 +131,7 @@ public class NumberFormatter extends InternationalFormatter {
DecimalFormatSymbols dfs = getDecimalFormatSymbols(); DecimalFormatSymbols dfs = getDecimalFormatSymbols();
if (dfs != null) { if (dfs != null) {
StringBuffer sb = new StringBuffer(); StringBuilder sb = new StringBuilder();
sb.append(dfs.getCurrencySymbol()); sb.append(dfs.getCurrencySymbol());
sb.append(dfs.getDecimalSeparator()); sb.append(dfs.getDecimalSeparator());
...@@ -239,13 +238,6 @@ public class NumberFormatter extends InternationalFormatter { ...@@ -239,13 +238,6 @@ public class NumberFormatter extends InternationalFormatter {
return null; return null;
} }
/**
*/
private boolean isValidInsertionCharacter(char aChar) {
return (Character.isDigit(aChar) || specialChars.indexOf(aChar) != -1);
}
/** /**
* Subclassed to return false if <code>text</code> contains in an invalid * Subclassed to return false if <code>text</code> contains in an invalid
* character to insert, that is, it is not a digit * character to insert, that is, it is not a digit
...@@ -402,28 +394,6 @@ public class NumberFormatter extends InternationalFormatter { ...@@ -402,28 +394,6 @@ public class NumberFormatter extends InternationalFormatter {
return false; return false;
} }
/**
* Returns true if the range offset to length identifies the only
* integer field.
*/
private boolean isOnlyIntegerField(int offset, int length) {
if (isValidMask()) {
int start = getAttributeStart(NumberFormat.Field.INTEGER);
if (start != -1) {
AttributedCharacterIterator iterator = getIterator();
iterator.setIndex(start);
if (offset > start || iterator.getRunLimit(
NumberFormat.Field.INTEGER) > (offset + length)) {
return false;
}
return true;
}
}
return false;
}
/** /**
* Invoked to toggle the sign. For this to work the value class * Invoked to toggle the sign. For this to work the value class
* must have a single arg constructor that takes a String. * must have a single arg constructor that takes a String.
......
...@@ -25,7 +25,6 @@ ...@@ -25,7 +25,6 @@
package javax.swing.text; package javax.swing.text;
import java.util.Vector; import java.util.Vector;
import javax.swing.event.*;
/** /**
* A plain document that maintains no character attributes. The * A plain document that maintains no character attributes. The
...@@ -118,7 +117,7 @@ public class PlainDocument extends AbstractDocument { ...@@ -118,7 +117,7 @@ public class PlainDocument extends AbstractDocument {
Object filterNewlines = getProperty("filterNewlines"); Object filterNewlines = getProperty("filterNewlines");
if ((filterNewlines instanceof Boolean) && filterNewlines.equals(Boolean.TRUE)) { if ((filterNewlines instanceof Boolean) && filterNewlines.equals(Boolean.TRUE)) {
if ((str != null) && (str.indexOf('\n') >= 0)) { if ((str != null) && (str.indexOf('\n') >= 0)) {
StringBuffer filtered = new StringBuffer(str); StringBuilder filtered = new StringBuilder(str);
int n = filtered.length(); int n = filtered.length();
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
if (filtered.charAt(i) == '\n') { if (filtered.charAt(i) == '\n') {
...@@ -204,11 +203,9 @@ public class PlainDocument extends AbstractDocument { ...@@ -204,11 +203,9 @@ public class PlainDocument extends AbstractDocument {
} }
} }
if (hasBreaks) { if (hasBreaks) {
int rmCount = 1;
removed.addElement(rmCandidate); removed.addElement(rmCandidate);
if ((offset + length == rmOffs1) && (lastOffset != rmOffs1) && if ((offset + length == rmOffs1) && (lastOffset != rmOffs1) &&
((index+1) < lineMap.getElementCount())) { ((index+1) < lineMap.getElementCount())) {
rmCount += 1;
Element e = lineMap.getElement(index+1); Element e = lineMap.getElement(index+1);
removed.addElement(e); removed.addElement(e);
rmOffs1 = e.getEndOffset(); rmOffs1 = e.getEndOffset();
......
...@@ -199,7 +199,7 @@ public class TabSet implements Serializable ...@@ -199,7 +199,7 @@ public class TabSet implements Serializable
*/ */
public String toString() { public String toString() {
int tabCount = getTabCount(); int tabCount = getTabCount();
StringBuffer buffer = new StringBuffer("[ "); StringBuilder buffer = new StringBuilder("[ ");
for(int counter = 0; counter < tabCount; counter++) { for(int counter = 0; counter < tabCount; counter++) {
if(counter > 0) if(counter > 0)
......
...@@ -362,7 +362,7 @@ public class FormView extends ComponentView implements ActionListener { ...@@ -362,7 +362,7 @@ public class FormView extends ComponentView implements ActionListener {
*/ */
public void actionPerformed(ActionEvent evt) { public void actionPerformed(ActionEvent evt) {
Element element = getElement(); Element element = getElement();
StringBuffer dataBuffer = new StringBuffer(); StringBuilder dataBuffer = new StringBuilder();
HTMLDocument doc = (HTMLDocument)getDocument(); HTMLDocument doc = (HTMLDocument)getDocument();
AttributeSet attr = element.getAttributes(); AttributeSet attr = element.getAttributes();
...@@ -508,7 +508,7 @@ public class FormView extends ComponentView implements ActionListener { ...@@ -508,7 +508,7 @@ public class FormView extends ComponentView implements ActionListener {
*/ */
protected void imageSubmit(String imageData) { protected void imageSubmit(String imageData) {
StringBuffer dataBuffer = new StringBuffer(); StringBuilder dataBuffer = new StringBuilder();
Element elem = getElement(); Element elem = getElement();
HTMLDocument hdoc = (HTMLDocument)elem.getDocument(); HTMLDocument hdoc = (HTMLDocument)elem.getDocument();
getFormData(dataBuffer); getFormData(dataBuffer);
...@@ -589,7 +589,7 @@ public class FormView extends ComponentView implements ActionListener { ...@@ -589,7 +589,7 @@ public class FormView extends ComponentView implements ActionListener {
* @param targetElement the element that triggered the * @param targetElement the element that triggered the
* form submission * form submission
*/ */
void getFormData(StringBuffer buffer) { private void getFormData(StringBuilder buffer) {
Element formE = getFormElement(); Element formE = getFormElement();
if (formE != null) { if (formE != null) {
ElementIterator it = new ElementIterator(formE); ElementIterator it = new ElementIterator(formE);
...@@ -623,7 +623,7 @@ public class FormView extends ComponentView implements ActionListener { ...@@ -623,7 +623,7 @@ public class FormView extends ComponentView implements ActionListener {
* data is loaded in name/value pairs. * data is loaded in name/value pairs.
* *
*/ */
private void loadElementDataIntoBuffer(Element elem, StringBuffer buffer) { private void loadElementDataIntoBuffer(Element elem, StringBuilder buffer) {
AttributeSet attr = elem.getAttributes(); AttributeSet attr = elem.getAttributes();
String name = (String)attr.getAttribute(HTML.Attribute.NAME); String name = (String)attr.getAttribute(HTML.Attribute.NAME);
...@@ -692,29 +692,6 @@ public class FormView extends ComponentView implements ActionListener { ...@@ -692,29 +692,6 @@ public class FormView extends ComponentView implements ActionListener {
} }
if (path != null && path.length() > 0) { if (path != null && path.length() > 0) {
value = path; value = path;
/*
try {
Reader reader = new BufferedReader(new FileReader(path));
StringBuffer buffer = new StringBuffer();
char[] cBuff = new char[1024];
int read;
try {
while ((read = reader.read(cBuff)) != -1) {
buffer.append(cBuff, 0, read);
}
} catch (IOException ioe) {
buffer = null;
}
try {
reader.close();
} catch (IOException ioe) {}
if (buffer != null) {
value = buffer.toString();
}
} catch (IOException ioe) {}
*/
} }
} }
return value; return value;
...@@ -740,7 +717,7 @@ public class FormView extends ComponentView implements ActionListener { ...@@ -740,7 +717,7 @@ public class FormView extends ComponentView implements ActionListener {
* form element. Basically, only items that are selected * form element. Basically, only items that are selected
* and have their name attribute set are added to the buffer. * and have their name attribute set are added to the buffer.
*/ */
private void loadSelectData(AttributeSet attr, StringBuffer buffer) { private void loadSelectData(AttributeSet attr, StringBuilder buffer) {
String name = (String)attr.getAttribute(HTML.Attribute.NAME); String name = (String)attr.getAttribute(HTML.Attribute.NAME);
if (name == null) { if (name == null) {
...@@ -771,7 +748,7 @@ public class FormView extends ComponentView implements ActionListener { ...@@ -771,7 +748,7 @@ public class FormView extends ComponentView implements ActionListener {
* URLEncoder.encode() method before being added to the * URLEncoder.encode() method before being added to the
* buffer. * buffer.
*/ */
private void appendBuffer(StringBuffer buffer, String name, String value) { private void appendBuffer(StringBuilder buffer, String name, String value) {
if (buffer.length() > 0) { if (buffer.length() > 0) {
buffer.append('&'); buffer.append('&');
} }
......
...@@ -691,11 +691,11 @@ public class MinimalHTMLWriter extends AbstractWriter { ...@@ -691,11 +691,11 @@ public class MinimalHTMLWriter extends AbstractWriter {
if (styleNameMapping == null) { if (styleNameMapping == null) {
return style; return style;
} }
StringBuffer sb = null; StringBuilder sb = null;
for (int counter = style.length() - 1; counter >= 0; counter--) { for (int counter = style.length() - 1; counter >= 0; counter--) {
if (!isValidCharacter(style.charAt(counter))) { if (!isValidCharacter(style.charAt(counter))) {
if (sb == null) { if (sb == null) {
sb = new StringBuffer(style); sb = new StringBuilder(style);
} }
sb.setCharAt(counter, 'a'); sb.setCharAt(counter, 'a');
} }
......
...@@ -998,7 +998,7 @@ public class StyleSheet extends StyleContext { ...@@ -998,7 +998,7 @@ public class StyleSheet extends StyleContext {
void addRule(String[] selector, AttributeSet declaration, void addRule(String[] selector, AttributeSet declaration,
boolean isLinked) { boolean isLinked) {
int n = selector.length; int n = selector.length;
StringBuffer sb = new StringBuffer(); StringBuilder sb = new StringBuilder();
sb.append(selector[0]); sb.append(selector[0]);
for (int counter = 1; counter < n; counter++) { for (int counter = 1; counter < n; counter++) {
sb.append(' '); sb.append(' ');
......
...@@ -1470,7 +1470,7 @@ class Parser implements DTDConstants { ...@@ -1470,7 +1470,7 @@ class Parser implements DTDConstants {
*/ */
public String parseDTDMarkup() throws IOException { public String parseDTDMarkup() throws IOException {
StringBuffer strBuff = new StringBuffer(); StringBuilder strBuff = new StringBuilder();
ch = readCh(); ch = readCh();
while(true) { while(true) {
switch (ch) { switch (ch) {
......
...@@ -160,7 +160,7 @@ abstract class AbstractFilter extends OutputStream ...@@ -160,7 +160,7 @@ abstract class AbstractFilter extends OutputStream
public void write(byte[] buf, int off, int len) public void write(byte[] buf, int off, int len)
throws IOException throws IOException
{ {
StringBuffer accumulator = null; StringBuilder accumulator = null;
while (len > 0) { while (len > 0) {
short b = (short)buf[off]; short b = (short)buf[off];
...@@ -178,7 +178,7 @@ abstract class AbstractFilter extends OutputStream ...@@ -178,7 +178,7 @@ abstract class AbstractFilter extends OutputStream
char ch = translationTable[b]; char ch = translationTable[b];
if (ch != (char)0) { if (ch != (char)0) {
if (accumulator == null) if (accumulator == null)
accumulator = new StringBuffer(); accumulator = new StringBuilder();
accumulator.append(ch); accumulator.append(ch);
} }
} }
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册