Mercurial > hg > release > icedtea7-forest-2.6 > jdk
changeset 4804:2c1b789d1803 jdk7u4-b06
Merge
author | lana |
---|---|
date | Fri, 23 Dec 2011 16:08:11 -0800 |
parents | b89c77e529b0 (current diff) 25936ce70254 (diff) |
children | 029394aa3e44 69304428880a |
files | |
diffstat | 34 files changed, 2630 insertions(+), 277 deletions(-) [+] |
line wrap: on
line diff
--- a/make/common/Defs-embedded.gmk Wed Dec 21 20:03:17 2011 -0800 +++ b/make/common/Defs-embedded.gmk Fri Dec 23 16:08:11 2011 -0800 @@ -65,5 +65,12 @@ NIO_PLATFORM_CLASSES_ROOT_DIR = $(CLOSED_PLATFORM_SRC)/classes/ endif +# For ARM sflt we need to link to a library with improved FP accuracy +# and it must be linked after fdlibm - this places it at the end after libc +# -z muldefs avoids linker errors for duplicate symbols. +ifeq ($(CROSS_COMPILE_ARCH), arm) + EXTRA_LIBS += $(EXT_LIBS_PATH)/sflt_glibc_jdk.a -Xlinker -z -Xlinker muldefs +endif + endif # JAVASE_EMBEDDED
--- a/make/common/Release.gmk Wed Dec 21 20:03:17 2011 -0800 +++ b/make/common/Release.gmk Fri Dec 23 16:08:11 2011 -0800 @@ -61,7 +61,8 @@ # EXPORTED_PRIVATE_PKGS = com.sun.servicetag \ com.oracle.net \ - com.oracle.nio + com.oracle.nio \ + com.oracle.util # 64-bit solaris has a few special cases. We define the variable # SOLARIS64 for use in this Makefile to easily test those cases
--- a/make/java/zip/mapfile-vers Wed Dec 21 20:03:17 2011 -0800 +++ b/make/java/zip/mapfile-vers Fri Dec 23 16:08:11 2011 -0800 @@ -30,6 +30,7 @@ Java_java_util_jar_JarFile_getMetaInfEntryNames; Java_java_util_zip_Adler32_update; Java_java_util_zip_Adler32_updateBytes; + Java_java_util_zip_Adler32_updateByteBuffer; Java_java_util_zip_CRC32_update; Java_java_util_zip_CRC32_updateBytes; Java_java_util_zip_Deflater_deflateBytes;
--- a/src/share/classes/java/awt/EventDispatchThread.java Wed Dec 21 20:03:17 2011 -0800 +++ b/src/share/classes/java/awt/EventDispatchThread.java Fri Dec 23 16:08:11 2011 -0800 @@ -34,8 +34,10 @@ import sun.security.action.GetPropertyAction; import sun.awt.AWTAutoShutdown; import sun.awt.SunToolkit; +import sun.awt.AppContext; -import java.util.Vector; +import java.util.ArrayList; +import java.util.List; import sun.util.logging.PlatformLogger; import sun.awt.dnd.SunDragSourceContextPeer; @@ -66,11 +68,11 @@ private EventQueue theQueue; private boolean doDispatch = true; - private boolean threadDeathCaught = false; + private volatile boolean shutdown = false; private static final int ANY_EVENT = -1; - private Vector<EventFilter> eventFilters = new Vector<EventFilter>(); + private ArrayList<EventFilter> eventFilters = new ArrayList<EventFilter>(); EventDispatchThread(ThreadGroup group, String name, EventQueue queue) { super(group, name); @@ -84,6 +86,11 @@ doDispatch = false; } + public void interrupt() { + shutdown = true; + super.interrupt(); + } + public void run() { while (true) { try { @@ -93,8 +100,7 @@ } }); } finally { - EventQueue eq = getEventQueue(); - if (eq.detachDispatchThread(this) || threadDeathCaught) { + if(getEventQueue().detachDispatchThread(this, shutdown)) { break; } } @@ -124,10 +130,9 @@ void pumpEventsForFilter(int id, Conditional cond, EventFilter filter) { addEventFilter(filter); doDispatch = true; - while (doDispatch && cond.evaluate()) { - if (isInterrupted() || !pumpOneEventForFilters(id)) { - doDispatch = false; - } + shutdown |= isInterrupted(); + while (doDispatch && !shutdown && cond.evaluate()) { + pumpOneEventForFilters(id); } removeEventFilter(filter); } @@ -163,7 +168,7 @@ } } - boolean pumpOneEventForFilters(int id) { + void pumpOneEventForFilters(int id) { AWTEvent event = null; boolean eventOK = false; try { @@ -212,24 +217,18 @@ if (delegate != null) { delegate.afterDispatch(event, handle); } - - return true; } catch (ThreadDeath death) { - threadDeathCaught = true; - return false; - + shutdown = true; + throw death; } catch (InterruptedException interruptedException) { - return false; // AppContext.dispose() interrupts all - // Threads in the AppContext - + shutdown = true; // AppContext.dispose() interrupts all + // Threads in the AppContext } catch (Throwable e) { processException(e); } - - return true; } private void processException(Throwable e) {
--- a/src/share/classes/java/awt/EventQueue.java Wed Dec 21 20:03:17 2011 -0800 +++ b/src/share/classes/java/awt/EventQueue.java Fri Dec 23 16:08:11 2011 -0800 @@ -47,6 +47,7 @@ import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; +import java.util.concurrent.atomic.AtomicInteger; import java.security.AccessControlContext; import java.security.ProtectionDomain; @@ -99,12 +100,7 @@ * @since 1.1 */ public class EventQueue { - - // From Thread.java - private static int threadInitNumber; - private static synchronized int nextThreadNum() { - return threadInitNumber++; - } + private static final AtomicInteger threadInitNumber = new AtomicInteger(0); private static final int LOW_PRIORITY = 0; private static final int NORM_PRIORITY = 1; @@ -175,9 +171,9 @@ * Non-zero if a thread is waiting in getNextEvent(int) for an event of * a particular ID to be posted to the queue. */ - private int waitForID; + private volatile int waitForID; - private final String name = "AWT-EventQueue-" + nextThreadNum(); + private final String name = "AWT-EventQueue-" + threadInitNumber.getAndIncrement(); private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.EventQueue"); @@ -1030,7 +1026,7 @@ } } - final boolean detachDispatchThread(EventDispatchThread edt) { + final boolean detachDispatchThread(EventDispatchThread edt, boolean forceDetach) { /* * This synchronized block is to secure that the event dispatch * thread won't die in the middle of posting a new event to the @@ -1049,7 +1045,7 @@ * Fix for 4648733. Check both the associated java event * queue and the PostEventQueue. */ - if ((peekEvent() != null) || !SunToolkit.isPostEventQueueEmpty()) { + if (!forceDetach && (peekEvent() != null) || !SunToolkit.isPostEventQueueEmpty()) { return false; } dispatchThread = null;
--- a/src/share/classes/java/security/Policy.java Wed Dec 21 20:03:17 2011 -0800 +++ b/src/share/classes/java/security/Policy.java Fri Dec 23 16:08:11 2011 -0800 @@ -37,6 +37,7 @@ import java.util.StringTokenizer; import java.util.Vector; import java.util.WeakHashMap; +import java.util.concurrent.atomic.AtomicReference; import sun.security.jca.GetInstance; import sun.security.util.Debug; import sun.security.util.SecurityConstants; @@ -69,8 +70,8 @@ * with a standard type. The default policy type is "JavaPolicy". * * <p> Once a Policy instance has been installed (either by default, or by - * calling <code>setPolicy</code>), - * the Java runtime invokes its <code>implies</code> when it needs to + * calling <code>setPolicy</code>), the Java runtime invokes its + * <code>implies</code> method when it needs to * determine whether executing code (encapsulated in a ProtectionDomain) * can perform SecurityManager-protected operations. How a Policy object * retrieves its policy data is up to the Policy implementation itself. @@ -103,18 +104,33 @@ public static final PermissionCollection UNSUPPORTED_EMPTY_COLLECTION = new UnsupportedEmptyCollection(); - /** the system-wide policy. */ - private static Policy policy; // package private for AccessControlContext + // Information about the system-wide policy. + private static class PolicyInfo { + // the system-wide policy + final Policy policy; + // a flag indicating if the system-wide policy has been initialized + final boolean initialized; + + PolicyInfo(Policy policy, boolean initialized) { + this.policy = policy; + this.initialized = initialized; + } + } + + // PolicyInfo is stored in an AtomicReference + private static AtomicReference<PolicyInfo> policy = + new AtomicReference<>(new PolicyInfo(null, false)); private static final Debug debug = Debug.getInstance("policy"); // Cache mapping ProtectionDomain.Key to PermissionCollection private WeakHashMap<ProtectionDomain.Key, PermissionCollection> pdMapping; - /** package private for AccessControlContext */ + /** package private for AccessControlContext and ProtectionDomain */ static boolean isSet() { - return policy != null; + PolicyInfo pi = policy.get(); + return pi.policy != null && pi.initialized == true; } private static void checkPermission(String type) { @@ -152,80 +168,92 @@ /** * Returns the installed Policy object, skipping the security check. - * Used by SecureClassLoader and getPolicy. + * Used by ProtectionDomain and getPolicy. * * @return the installed Policy. - * */ - static synchronized Policy getPolicyNoCheck() + static Policy getPolicyNoCheck() { - if (policy == null) { - String policy_class = null; - policy_class = AccessController.doPrivileged( - new PrivilegedAction<String>() { - public String run() { - return Security.getProperty("policy.provider"); - } - }); - if (policy_class == null) { - policy_class = "sun.security.provider.PolicyFile"; - } - - try { - policy = (Policy) - Class.forName(policy_class).newInstance(); - } catch (Exception e) { - /* - * The policy_class seems to be an extension - * so we have to bootstrap loading it via a policy - * provider that is on the bootclasspath - * If it loads then shift gears to using the configured - * provider. - */ - - // install the bootstrap provider to avoid recursion - policy = new sun.security.provider.PolicyFile(); - - final String pc = policy_class; - Policy p = AccessController.doPrivileged( - new PrivilegedAction<Policy>() { - public Policy run() { - try { - ClassLoader cl = - ClassLoader.getSystemClassLoader(); - // we want the extension loader - ClassLoader extcl = null; - while (cl != null) { - extcl = cl; - cl = cl.getParent(); - } - return (extcl != null ? (Policy)Class.forName( - pc, true, extcl).newInstance() : null); - } catch (Exception e) { - if (debug != null) { - debug.println("policy provider " + - pc + - " not available"); - e.printStackTrace(); - } - return null; - } + PolicyInfo pi = policy.get(); + // Use double-check idiom to avoid locking if system-wide policy is + // already initialized + if (pi.initialized == false || pi.policy == null) { + synchronized (Policy.class) { + PolicyInfo pinfo = policy.get(); + if (pinfo.policy == null) { + String policy_class = AccessController.doPrivileged( + new PrivilegedAction<String>() { + public String run() { + return Security.getProperty("policy.provider"); } }); - /* - * if it loaded install it as the policy provider. Otherwise - * continue to use the system default implementation - */ - if (p != null) { - policy = p; - } else { - if (debug != null) { - debug.println("using sun.security.provider.PolicyFile"); + if (policy_class == null) { + policy_class = "sun.security.provider.PolicyFile"; } + + try { + pinfo = new PolicyInfo( + (Policy) Class.forName(policy_class).newInstance(), + true); + } catch (Exception e) { + /* + * The policy_class seems to be an extension + * so we have to bootstrap loading it via a policy + * provider that is on the bootclasspath. + * If it loads then shift gears to using the configured + * provider. + */ + + // install the bootstrap provider to avoid recursion + Policy polFile = new sun.security.provider.PolicyFile(); + pinfo = new PolicyInfo(polFile, false); + policy.set(pinfo); + + final String pc = policy_class; + Policy pol = AccessController.doPrivileged( + new PrivilegedAction<Policy>() { + public Policy run() { + try { + ClassLoader cl = + ClassLoader.getSystemClassLoader(); + // we want the extension loader + ClassLoader extcl = null; + while (cl != null) { + extcl = cl; + cl = cl.getParent(); + } + return (extcl != null ? (Policy)Class.forName( + pc, true, extcl).newInstance() : null); + } catch (Exception e) { + if (debug != null) { + debug.println("policy provider " + + pc + + " not available"); + e.printStackTrace(); + } + return null; + } + } + }); + /* + * if it loaded install it as the policy provider. Otherwise + * continue to use the system default implementation + */ + if (pol != null) { + pinfo = new PolicyInfo(pol, true); + } else { + if (debug != null) { + debug.println("using sun.security.provider.PolicyFile"); + } + pinfo = new PolicyInfo(polFile, true); + } + } + policy.set(pinfo); } + return pinfo.policy; } } - return policy; + return pi.policy; } /** @@ -254,7 +282,7 @@ initPolicy(p); } synchronized (Policy.class) { - Policy.policy = p; + policy.set(new PolicyInfo(p, p != null)); } } @@ -301,14 +329,14 @@ PermissionCollection policyPerms = null; synchronized (p) { if (p.pdMapping == null) { - p.pdMapping = - new WeakHashMap<ProtectionDomain.Key, PermissionCollection>(); + p.pdMapping = new WeakHashMap<>(); } } if (policyDomain.getCodeSource() != null) { - if (Policy.isSet()) { - policyPerms = policy.getPermissions(policyDomain); + Policy pol = policy.get().policy; + if (pol != null) { + policyPerms = pol.getPermissions(policyDomain); } if (policyPerms == null) { // assume it has all @@ -443,7 +471,7 @@ type, params); } catch (NoSuchAlgorithmException nsae) { - return handleException (nsae); + return handleException(nsae); } } @@ -503,7 +531,7 @@ type, params); } catch (NoSuchAlgorithmException nsae) { - return handleException (nsae); + return handleException(nsae); } } @@ -815,7 +843,7 @@ * * @param permission the Permission object to compare. * - * @return true if "permission" is implied by the permissions in + * @return true if "permission" is implied by the permissions in * the collection, false if not. */ @Override public boolean implies(Permission permission) {
--- a/src/share/classes/java/util/zip/Adler32.java Wed Dec 21 20:03:17 2011 -0800 +++ b/src/share/classes/java/util/zip/Adler32.java Fri Dec 23 16:08:11 2011 -0800 @@ -25,6 +25,9 @@ package java.util.zip; +import java.nio.ByteBuffer; +import sun.nio.ch.DirectBuffer; + /** * A class that can be used to compute the Adler-32 checksum of a data * stream. An Adler-32 checksum is almost as reliable as a CRC-32 but @@ -76,6 +79,37 @@ } /** + * Updates the checksum with the bytes from the specified buffer. + * + * The checksum is updated using + * buffer.{@link java.nio.Buffer#remaining() remaining()} + * bytes starting at + * buffer.{@link java.nio.Buffer#position() position()} + * Upon return, the buffer's position will be updated to its + * limit; its limit will not have been changed. + * + * @param buffer the ByteBuffer to update the checksum with + */ + private void update(ByteBuffer buffer) { + int pos = buffer.position(); + int limit = buffer.limit(); + assert (pos <= limit); + int rem = limit - pos; + if (rem <= 0) + return; + if (buffer instanceof DirectBuffer) { + adler = updateByteBuffer(adler, ((DirectBuffer)buffer).address(), pos, rem); + } else if (buffer.hasArray()) { + adler = updateBytes(adler, buffer.array(), pos + buffer.arrayOffset(), rem); + } else { + byte[] b = new byte[rem]; + buffer.get(b); + adler = updateBytes(adler, b, 0, b.length); + } + buffer.position(limit); + } + + /** * Resets the checksum to initial value. */ public void reset() { @@ -89,7 +123,18 @@ return (long)adler & 0xffffffffL; } + // Set up JavaUtilZipAccess in SharedSecrets + static { + sun.misc.SharedSecrets.setJavaUtilZipAccess(new sun.misc.JavaUtilZipAccess() { + public void update(Adler32 adler32, ByteBuffer buf) { + adler32.update(buf); + } + }); + } + private native static int update(int adler, int b); private native static int updateBytes(int adler, byte[] b, int off, int len); + private native static int updateByteBuffer(int adler, long addr, + int off, int len); }
--- a/src/share/classes/sun/awt/AppContext.java Wed Dec 21 20:03:17 2011 -0800 +++ b/src/share/classes/sun/awt/AppContext.java Fri Dec 23 16:08:11 2011 -0800 @@ -342,6 +342,16 @@ return appContext; } + /** + * Returns the main ("system") AppContext. + * + * @return the main AppContext + * @since 1.8 + */ + final static AppContext getMainAppContext() { + return mainAppContext; + } + private long DISPOSAL_TIMEOUT = 5000; // Default to 5-second timeout // for disposal of all Frames // (we wait for this time twice,
--- a/src/share/classes/sun/awt/SunToolkit.java Wed Dec 21 20:03:17 2011 -0800 +++ b/src/share/classes/sun/awt/SunToolkit.java Fri Dec 23 16:08:11 2011 -0800 @@ -101,30 +101,28 @@ */ public final static int MAX_BUTTONS_SUPPORTED = 20; - public SunToolkit() { - Runnable initEQ = new Runnable() { - public void run () { - EventQueue eventQueue; + private static void initEQ(AppContext appContext) { + EventQueue eventQueue; - String eqName = System.getProperty("AWT.EventQueueClass", - "java.awt.EventQueue"); + String eqName = System.getProperty("AWT.EventQueueClass", + "java.awt.EventQueue"); - try { - eventQueue = (EventQueue)Class.forName(eqName).newInstance(); - } catch (Exception e) { - e.printStackTrace(); - System.err.println("Failed loading " + eqName + ": " + e); - eventQueue = new EventQueue(); - } - AppContext appContext = AppContext.getAppContext(); - appContext.put(AppContext.EVENT_QUEUE_KEY, eventQueue); + try { + eventQueue = (EventQueue)Class.forName(eqName).newInstance(); + } catch (Exception e) { + e.printStackTrace(); + System.err.println("Failed loading " + eqName + ": " + e); + eventQueue = new EventQueue(); + } + appContext.put(AppContext.EVENT_QUEUE_KEY, eventQueue); - PostEventQueue postEventQueue = new PostEventQueue(eventQueue); - appContext.put(POST_EVENT_QUEUE_KEY, postEventQueue); - } - }; + PostEventQueue postEventQueue = new PostEventQueue(eventQueue); + appContext.put(POST_EVENT_QUEUE_KEY, postEventQueue); + } - initEQ.run(); + public SunToolkit() { + // 7122796: Always create an EQ for the main AppContext + initEQ(AppContext.getMainAppContext()); } public boolean useBufferPerWindow() { @@ -288,19 +286,7 @@ // return correct values AppContext appContext = new AppContext(threadGroup); - EventQueue eventQueue; - String eqName = System.getProperty("AWT.EventQueueClass", - "java.awt.EventQueue"); - try { - eventQueue = (EventQueue)Class.forName(eqName).newInstance(); - } catch (Exception e) { - System.err.println("Failed loading " + eqName + ": " + e); - eventQueue = new EventQueue(); - } - appContext.put(AppContext.EVENT_QUEUE_KEY, eventQueue); - - PostEventQueue postEventQueue = new PostEventQueue(eventQueue); - appContext.put(POST_EVENT_QUEUE_KEY, postEventQueue); + initEQ(appContext); return appContext; }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/share/classes/sun/misc/JavaUtilZipAccess.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.misc; + +import java.util.zip.Adler32; +import java.nio.ByteBuffer; + +public interface JavaUtilZipAccess { + public void update(Adler32 adler32, ByteBuffer buf); +}
--- a/src/share/classes/sun/misc/SharedSecrets.java Wed Dec 21 20:03:17 2011 -0800 +++ b/src/share/classes/sun/misc/SharedSecrets.java Fri Dec 23 16:08:11 2011 -0800 @@ -29,6 +29,7 @@ import java.io.Console; import java.io.FileDescriptor; import java.security.ProtectionDomain; +import java.util.zip.Adler32; import javax.security.auth.kerberos.KeyTab; import java.security.AccessController; @@ -53,6 +54,7 @@ private static JavaSecurityProtectionDomainAccess javaSecurityProtectionDomainAccess; private static JavaSecurityAccess javaSecurityAccess; private static JavaxSecurityAuthKerberosAccess javaxSecurityAuthKerberosAccess; + private static JavaUtilZipAccess javaUtilZipAccess; public static JavaUtilJarAccess javaUtilJarAccess() { if (javaUtilJarAccess == null) { @@ -153,4 +155,15 @@ unsafe.ensureClassInitialized(KeyTab.class); return javaxSecurityAuthKerberosAccess; } + + public static void setJavaUtilZipAccess(JavaUtilZipAccess access) { + javaUtilZipAccess = access; + } + + public static JavaUtilZipAccess getJavaUtilZipAccess() { + if (javaUtilZipAccess == null) { + unsafe.ensureClassInitialized(Adler32.class); + } + return javaUtilZipAccess; + } }
--- a/src/share/classes/sun/security/krb5/internal/KerberosTime.java Wed Dec 21 20:03:17 2011 -0800 +++ b/src/share/classes/sun/security/krb5/internal/KerberosTime.java Fri Dec 23 16:08:11 2011 -0800 @@ -68,8 +68,8 @@ private int microSeconds; // the last three digits of the microsecond value // The time when this class is loaded. Used in setNow() - private static final long initMilli = System.currentTimeMillis(); - private static final long initMicro = System.nanoTime() / 1000; + private static long initMilli = System.currentTimeMillis(); + private static long initMicro = System.nanoTime() / 1000; private static long syncTime; private static boolean DEBUG = Krb5.DEBUG; @@ -212,9 +212,22 @@ } public void setNow() { - long microElapsed = System.nanoTime() / 1000 - initMicro; - setTime(initMilli + microElapsed/1000); - microSeconds = (int)(microElapsed % 1000); + long newMilli = System.currentTimeMillis(); + long newMicro = System.nanoTime() / 1000; + long microElapsed = newMicro - initMicro; + long calcMilli = initMilli + microElapsed/1000; + if (calcMilli - newMilli > 100 || newMilli - calcMilli > 100) { + if (DEBUG) { + System.out.println("System time adjusted"); + } + initMilli = newMilli; + initMicro = newMicro; + setTime(newMilli); + microSeconds = 0; + } else { + setTime(calcMilli); + microSeconds = (int)(microElapsed % 1000); + } } public int getMicroSeconds() {
--- a/src/share/classes/sun/security/ssl/SSLContextImpl.java Wed Dec 21 20:03:17 2011 -0800 +++ b/src/share/classes/sun/security/ssl/SSLContextImpl.java Fri Dec 23 16:08:11 2011 -0800 @@ -767,10 +767,15 @@ final class AbstractTrustManagerWrapper extends X509ExtendedTrustManager implements X509TrustManager { + // the delegated trust manager private final X509TrustManager tm; + // Cache the trusted certificate to optimize the performance. + private final Collection<X509Certificate> trustedCerts = new HashSet<>(); + AbstractTrustManagerWrapper(X509TrustManager tm) { this.tm = tm; + Collections.addAll(trustedCerts, tm.getAcceptedIssuers()); } @Override @@ -859,20 +864,7 @@ constraints = new SSLAlgorithmConstraints(sslSocket, true); } - AlgorithmChecker checker = new AlgorithmChecker(constraints); - try { - checker.init(false); - - // a forward checker, need to check from trust to target - for (int i = chain.length - 1; i >= 0; i--) { - Certificate cert = chain[i]; - // We don't care about the unresolved critical extensions. - checker.check(cert, Collections.<String>emptySet()); - } - } catch (CertPathValidatorException cpve) { - throw new CertificateException( - "Certificates does not conform to algorithm constraints"); - } + checkAlgorithmConstraints(chain, constraints); } } @@ -914,20 +906,33 @@ constraints = new SSLAlgorithmConstraints(engine, true); } - AlgorithmChecker checker = new AlgorithmChecker(constraints); - try { + checkAlgorithmConstraints(chain, constraints); + } + } + + private void checkAlgorithmConstraints(X509Certificate[] chain, + AlgorithmConstraints constraints) throws CertificateException { + + try { + // Does the certificate chain end with a trusted certificate? + int checkedLength = chain.length - 1; + if (trustedCerts.contains(chain[checkedLength])) { + checkedLength--; + } + + // A forward checker, need to check from trust to target + if (checkedLength >= 0) { + AlgorithmChecker checker = new AlgorithmChecker(constraints); checker.init(false); - - // A forward checker, need to check from trust to target - for (int i = chain.length - 1; i >= 0; i--) { + for (int i = checkedLength; i >= 0; i--) { Certificate cert = chain[i]; // We don't care about the unresolved critical extensions. checker.check(cert, Collections.<String>emptySet()); } - } catch (CertPathValidatorException cpve) { - throw new CertificateException( - "Certificates does not conform to algorithm constraints"); } + } catch (CertPathValidatorException cpve) { + throw new CertificateException( + "Certificates does not conform to algorithm constraints"); } } }
--- a/src/share/classes/sun/security/tools/KeyTool.java Wed Dec 21 20:03:17 2011 -0800 +++ b/src/share/classes/sun/security/tools/KeyTool.java Fri Dec 23 16:08:11 2011 -0800 @@ -52,6 +52,7 @@ import java.util.jar.JarFile; import java.lang.reflect.Constructor; import java.math.BigInteger; +import java.net.Socket; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; @@ -84,6 +85,7 @@ import sun.security.x509.*; import static java.security.KeyStore.*; +import javax.net.ssl.*; import static sun.security.tools.KeyTool.Command.*; import static sun.security.tools.KeyTool.Option.*; @@ -2321,18 +2323,31 @@ SSLContext sc = SSLContext.getInstance("SSL"); final boolean[] certPrinted = new boolean[1]; sc.init(null, new TrustManager[] { - new X509TrustManager() { - - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; + new X509ExtendedTrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + @Override + public void checkClientTrusted( + X509Certificate[] certs, String authType) { + throw new UnsupportedOperationException(); } - - public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) { + @Override + public void checkClientTrusted(X509Certificate[] chain, + String authType, Socket socket) + throws CertificateException { + throw new UnsupportedOperationException(); } - + @Override + public void checkClientTrusted(X509Certificate[] chain, + String authType, SSLEngine engine) throws + CertificateException { + throw new UnsupportedOperationException(); + } + @Override public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) { + X509Certificate[] certs, String authType) { for (int i=0; i<certs.length; i++) { X509Certificate cert = certs[i]; try { @@ -2356,6 +2371,18 @@ certPrinted[0] = true; } } + @Override + public void checkServerTrusted(X509Certificate[] chain, + String authType, Socket socket) + throws CertificateException { + checkServerTrusted(chain, authType); + } + @Override + public void checkServerTrusted(X509Certificate[] chain, + String authType, SSLEngine engine) + throws CertificateException { + checkServerTrusted(chain, authType); + } } }, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
--- a/src/share/native/java/util/zip/Adler32.c Wed Dec 21 20:03:17 2011 -0800 +++ b/src/share/native/java/util/zip/Adler32.c Fri Dec 23 16:08:11 2011 -0800 @@ -53,3 +53,14 @@ } return adler; } + +JNIEXPORT jint JNICALL +Java_java_util_zip_Adler32_updateByteBuffer(JNIEnv *env, jclass cls, jint adler, + jlong address, jint off, jint len) +{ + Bytef *buf = (Bytef *)jlong_to_ptr(address); + if (buf) { + adler = adler32(adler, buf + off, len); + } + return adler; +}
--- a/src/solaris/classes/sun/awt/X11/XComponentPeer.java Wed Dec 21 20:03:17 2011 -0800 +++ b/src/solaris/classes/sun/awt/X11/XComponentPeer.java Fri Dec 23 16:08:11 2011 -0800 @@ -475,12 +475,16 @@ if (true) { switch(e.getID()) { case PaintEvent.UPDATE: - log.finer("XCP coalescePaintEvent : UPDATE : add : x = " + + if (log.isLoggable(PlatformLogger.FINER)) { + log.finer("XCP coalescePaintEvent : UPDATE : add : x = " + r.x + ", y = " + r.y + ", width = " + r.width + ",height = " + r.height); + } return; case PaintEvent.PAINT: - log.finer("XCP coalescePaintEvent : PAINT : add : x = " + + if (log.isLoggable(PlatformLogger.FINER)) { + log.finer("XCP coalescePaintEvent : PAINT : add : x = " + r.x + ", y = " + r.y + ", width = " + r.width + ",height = " + r.height); + } return; } } @@ -1257,7 +1261,9 @@ * ButtonPress, ButtonRelease, KeyPress, KeyRelease, EnterNotify, LeaveNotify, MotionNotify */ protected boolean isEventDisabled(XEvent e) { - enableLog.finest("Component is {1}, checking for disabled event {0}", e, (isEnabled()?"enabled":"disable")); + if (enableLog.isLoggable(PlatformLogger.FINEST)) { + enableLog.finest("Component is {1}, checking for disabled event {0}", e, (isEnabled()?"enabled":"disable")); + } if (!isEnabled()) { switch (e.get_type()) { case XConstants.ButtonPress: @@ -1267,7 +1273,9 @@ case XConstants.EnterNotify: case XConstants.LeaveNotify: case XConstants.MotionNotify: - enableLog.finer("Event {0} is disable", e); + if (enableLog.isLoggable(PlatformLogger.FINER)) { + enableLog.finer("Event {0} is disable", e); + } return true; } }
--- a/src/solaris/classes/sun/awt/X11/generator/WrapperGenerator.java Wed Dec 21 20:03:17 2011 -0800 +++ b/src/solaris/classes/sun/awt/X11/generator/WrapperGenerator.java Fri Dec 23 16:08:11 2011 -0800 @@ -678,7 +678,7 @@ public void writeToString(StructType stp, PrintWriter pw) { int type; pw.println("\n\n\tString getName() {\n\t\treturn \"" + stp.getName()+ "\"; \n\t}"); - pw.println("\n\n\tString getFieldsAsString() {\n\t\tString ret=\"\";\n"); + pw.println("\n\n\tString getFieldsAsString() {\n\t\tStringBuilder ret = new StringBuilder(" + stp.getNumFields() * 40 + ");\n"); for (Enumeration e = stp.getMembers() ; e.hasMoreElements() ;) { AtomicType tp = (AtomicType) e.nextElement(); @@ -688,24 +688,24 @@ if ((name != null) && (name.length() > 0)) { if (type == AtomicType.TYPE_ATOM) { - pw.println("\t\tret += \"\"+\"" + name + " = \" + XAtom.get(get_" + name + "()) +\", \";"); + pw.println("\t\tret.append(\"" + name + " = \" ).append( XAtom.get(get_" + name + "()) ).append(\", \");"); } else if (name.equals("type")) { - pw.println("\t\tret += \"\"+\"type = \" + XlibWrapper.eventToString[get_type()] +\", \";"); + pw.println("\t\tret.append(\"type = \").append( XlibWrapper.eventToString[get_type()] ).append(\", \");"); } else if (name.equals("window")){ - pw.println("\t\tret += \"\"+\"window = \" + getWindow(get_window()) + \", \";"); + pw.println("\t\tret.append(\"window = \" ).append( getWindow(get_window()) ).append(\", \");"); } else if (type == AtomicType.TYPE_ARRAY) { - pw.print("\t\tret += \"{\""); + pw.print("\t\tret.append(\"{\")"); for (int i = 0; i < tp.getArrayLength(); i++) { - pw.print(" + get_" + name + "(" + i + ") + \" \""); + pw.print("\n\t\t.append( get_" + name + "(" + i + ") ).append(\" \")"); } - pw.println(" + \"}\";"); + pw.println(".append( \"}\");"); } else { - pw.println("\t\tret += \"\"+\"" + name +" = \" + get_"+ name+"() +\", \";"); + pw.println("\t\tret.append(\"" + name +" = \").append( get_"+ name+"() ).append(\", \");"); } } } - pw.println("\t\treturn ret;\n\t}\n\n"); + pw.println("\t\treturn ret.toString();\n\t}\n\n"); } public void writeStubs(StructType stp, PrintWriter pw) {
--- a/src/windows/lib/tzmappings Wed Dec 21 20:03:17 2011 -0800 +++ b/src/windows/lib/tzmappings Fri Dec 23 16:08:11 2011 -0800 @@ -167,7 +167,7 @@ Argentina Standard Time:900,900::America/Buenos_Aires: Azerbaijan Standard Time:901,901:AZ:Asia/Baku: Bangladesh Standard Time:902,902::Asia/Dhaka: -Central Brazilian Standard Time:903,903:BR:America/Manaus: +Central Brazilian Standard Time:903,903:BR:America/Cuiaba: Central Standard Time (Mexico):904,904::America/Mexico_City: Georgian Standard Time:905,905:GE:Asia/Tbilisi: Jordan Standard Time:906,906:JO:Asia/Amman: @@ -189,5 +189,7 @@ Ulaanbaatar Standard Time:922,922::Asia/Ulaanbaatar: Venezuela Standard Time:923,923::America/Caracas: Magadan Standard Time:924,924::Asia/Magadan: -Western Brazilian Standard Time:925,925:BR:America/Rio_Branco: -Armenian Standard Time:926,926:AM:Asia/Yerevan: +Kaliningrad Standard Time:925,925:RU:Europe/Kaliningrad: +Turkey Standard Time:926,926::Asia/Istanbul: +Western Brazilian Standard Time:927,927:BR:America/Rio_Branco: +Armenian Standard Time:928,928:AM:Asia/Yerevan:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/awt/EventQueue/MainAppContext/MainAppContext.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,36 @@ +/* + * @test + * @bug 7122796 + * @summary Tests 7122796 + * @author anthony.petrov@oracle.com + */ + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import sun.awt.*; + +public class MainAppContext { + + public static void main(String[] args) { + ThreadGroup secondGroup = new ThreadGroup("test"); + new Thread(secondGroup, new Runnable() { + public void run() { + SunToolkit.createNewAppContext(); + test(true); + } + }).start(); + + // Sleep on the main thread so that the AWT Toolkit is initialized + // in a user AppContext first + try { Thread.sleep(2000); } catch (Exception e) {} + + test(false); + } + + private static void test(boolean userAppContext) { + if (Toolkit.getDefaultToolkit().getSystemEventQueue() == null) { + throw new RuntimeException("No EventQueue for the current app context! userAppContext: " + userAppContext); + } + } +}
--- a/test/java/net/URLConnection/Redirect307Test.java Wed Dec 21 20:03:17 2011 -0800 +++ b/test/java/net/URLConnection/Redirect307Test.java Fri Dec 23 16:08:11 2011 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /** * @test - * @bug 4380568 + * @bug 4380568 7095949 * @summary HttpURLConnection does not support 307 redirects */ import java.io.*; @@ -31,10 +31,9 @@ class RedirServer extends Thread { - ServerSocket s; - Socket s1; - InputStream is; - OutputStream os; + static final int TIMEOUT = 10 * 1000; + + ServerSocket ss; int port; String reply1Part1 = "HTTP/1.1 307 Temporary Redirect\r\n" + @@ -46,10 +45,10 @@ "Content-Type: text/html; charset=iso-8859-1\r\n\r\n" + "<html>Hello</html>"; - RedirServer (ServerSocket y) { - s = y; - port = s.getLocalPort(); - System.out.println("Server created listening on " + port); + RedirServer (ServerSocket ss) throws IOException { + this.ss = ss; + this.ss.setSoTimeout(TIMEOUT); + port = this.ss.getLocalPort(); } String reply2 = "HTTP/1.1 200 Ok\r\n" + @@ -59,74 +58,64 @@ "Content-Type: text/html; charset=iso-8859-1\r\n\r\n" + "World"; + static final byte[] requestEnd = new byte[] {'\r', '\n', '\r', '\n' }; + + // Read until the end of a HTTP request + void readOneRequest(InputStream is) throws IOException { + int requestEndCount = 0, r; + while ((r = is.read()) != -1) { + if (r == requestEnd[requestEndCount]) { + requestEndCount++; + if (requestEndCount == 4) { + break; + } + } else { + requestEndCount = 0; + } + } + } + public void run () { try { - s1 = s.accept (); - is = s1.getInputStream (); - os = s1.getOutputStream (); - is.read (); - String reply = reply1Part1 + port + reply1Part2; - os.write (reply.getBytes()); - os.close(); + try (Socket s = ss.accept()) { + s.setSoTimeout(TIMEOUT); + readOneRequest(s.getInputStream()); + String reply = reply1Part1 + port + reply1Part2; + s.getOutputStream().write(reply.getBytes()); + } + /* wait for redirected connection */ - s.setSoTimeout (5000); - s1 = s.accept (); - is = s1.getInputStream (); - os = s1.getOutputStream (); - is.read(); - os.write (reply2.getBytes()); - os.close(); - } - catch (Exception e) { - /* Just need thread to terminate */ - System.out.println("Server: caught " + e); + try (Socket s = ss.accept()) { + s.setSoTimeout(TIMEOUT); + readOneRequest(s.getInputStream()); + s.getOutputStream().write(reply2.getBytes()); + } + } catch (Exception e) { e.printStackTrace(); } finally { - try { s.close(); } catch (IOException unused) {} + try { ss.close(); } catch (IOException unused) {} } } }; public class Redirect307Test { - - public static final int DELAY = 10; - public static void main(String[] args) throws Exception { - int port; - RedirServer server; - ServerSocket sock; + ServerSocket sock = new ServerSocket(0); + int port = sock.getLocalPort(); + RedirServer server = new RedirServer(sock); + server.start(); - try { - sock = new ServerSocket (0); - port = sock.getLocalPort (); - } - catch (Exception e) { - System.out.println ("Exception: " + e); - return; - } - - server = new RedirServer(sock); - server.start (); + URL url = new URL("http://localhost:" + port); + URLConnection conURL = url.openConnection(); + conURL.setDoInput(true); + conURL.setAllowUserInteraction(false); + conURL.setUseCaches(false); - try { - - String s = "http://localhost:" + port; - URL url = new URL(s); - URLConnection conURL = url.openConnection(); - - conURL.setDoInput(true); - conURL.setAllowUserInteraction(false); - conURL.setUseCaches(false); - - InputStream in = conURL.getInputStream(); + try (InputStream in = conURL.getInputStream()) { if ((in.read() != (int)'W') || (in.read()!=(int)'o')) { throw new RuntimeException ("Unexpected string read"); } } - catch(IOException e) { - e.printStackTrace(); - throw new RuntimeException ("Exception caught + " + e); - } } }
--- a/test/java/net/URLConnection/RedirectLimit.java Wed Dec 21 20:03:17 2011 -0800 +++ b/test/java/net/URLConnection/RedirectLimit.java Fri Dec 23 16:08:11 2011 -0800 @@ -23,7 +23,7 @@ /** * @test - * @bug 4458085 + * @bug 4458085 7095949 * @summary Redirects Limited to 5 */ @@ -57,29 +57,43 @@ final ServerSocket ss; final int port; - RedirLimitServer(ServerSocket ss) { + RedirLimitServer(ServerSocket ss) throws IOException { this.ss = ss; - port = ss.getLocalPort(); + port = this.ss.getLocalPort(); + this.ss.setSoTimeout(TIMEOUT); + } + + static final byte[] requestEnd = new byte[] {'\r', '\n', '\r', '\n' }; + + // Read until the end of a HTTP request + void readOneRequest(InputStream is) throws IOException { + int requestEndCount = 0, r; + while ((r = is.read()) != -1) { + if (r == requestEnd[requestEndCount]) { + requestEndCount++; + if (requestEndCount == 4) { + break; + } + } else { + requestEndCount = 0; + } + } } public void run() { try { - ss.setSoTimeout(TIMEOUT); for (int i=0; i<NUM_REDIRECTS; i++) { try (Socket s = ss.accept()) { s.setSoTimeout(TIMEOUT); - InputStream is = s.getInputStream(); - OutputStream os = s.getOutputStream(); - is.read(); + readOneRequest(s.getInputStream()); String reply = reply1 + port + "/redirect" + i + reply2; - os.write(reply.getBytes()); + s.getOutputStream().write(reply.getBytes()); } } try (Socket s = ss.accept()) { - InputStream is = s.getInputStream(); - OutputStream os = s.getOutputStream(); - is.read(); - os.write(reply3.getBytes()); + s.setSoTimeout(TIMEOUT); + readOneRequest(s.getInputStream()); + s.getOutputStream().write(reply3.getBytes()); } } catch (Exception e) { e.printStackTrace(); @@ -96,21 +110,17 @@ RedirLimitServer server = new RedirLimitServer(ss); server.start(); - InputStream in = null; - try { - URL url = new URL("http://localhost:" + port); - URLConnection conURL = url.openConnection(); + URL url = new URL("http://localhost:" + port); + URLConnection conURL = url.openConnection(); - conURL.setDoInput(true); - conURL.setAllowUserInteraction(false); - conURL.setUseCaches(false); + conURL.setDoInput(true); + conURL.setAllowUserInteraction(false); + conURL.setUseCaches(false); - in = conURL.getInputStream(); + try (InputStream in = conURL.getInputStream()) { if ((in.read() != (int)'W') || (in.read()!=(int)'o')) { throw new RuntimeException("Unexpected string read"); } - } finally { - if ( in != null ) { in.close(); } } } }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/javax/swing/JScrollBar/4708809/bug4708809.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4708809 + * @summary JScrollBar functionality slightly different from native scrollbar + * @author Andrey Pikalev + * @run main bug4708809 + */ +import javax.swing.*; +import java.awt.*; +import java.awt.Point; +import java.awt.event.*; +import sun.awt.SunToolkit; + +public class bug4708809 { + + private static volatile boolean do_test = false; + private static volatile boolean passed = true; + private static JScrollPane spane; + private static JScrollBar sbar; + + public static void main(String[] args) throws Exception { + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + Robot robot = new Robot(); + robot.setAutoDelay(350); + + SwingUtilities.invokeAndWait(new Runnable() { + + public void run() { + createAndShowGUI(); + } + }); + + toolkit.realSync(); + + SwingUtilities.invokeAndWait(new Runnable() { + + public void run() { + spane.requestFocus(); + sbar.setValue(sbar.getMaximum()); + } + }); + + toolkit.realSync(); + + Point point = getClickPoint(0.5, 0.5); + robot.mouseMove(point.x, point.y); + robot.mousePress(InputEvent.BUTTON1_MASK); + + toolkit.realSync(); + + SwingUtilities.invokeAndWait(new Runnable() { + + public void run() { + final int oldValue = sbar.getValue(); + sbar.addAdjustmentListener(new AdjustmentListener() { + + public void adjustmentValueChanged(AdjustmentEvent e) { + if (e.getValue() >= oldValue) { + passed = false; + } + do_test = true; + } + }); + + } + }); + + toolkit.realSync(); + + point = getClickPoint(0.5, 0.2); + robot.mouseMove(point.x, point.y); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + toolkit.realSync(); + + if (!do_test || !passed) { + throw new Exception("The scrollbar moved with incorrect direction"); + } + + } + + private static Point getClickPoint(final double scaleX, final double scaleY) throws Exception { + final Point[] result = new Point[1]; + + SwingUtilities.invokeAndWait(new Runnable() { + + @Override + public void run() { + Point p = sbar.getLocationOnScreen(); + Rectangle rect = sbar.getBounds(); + result[0] = new Point((int) (p.x + scaleX * rect.width), + (int) (p.y + scaleY * rect.height)); + } + }); + + return result[0]; + + } + + private static void createAndShowGUI() { + JFrame fr = new JFrame("Test"); + + JLabel label = new JLabel("picture"); + label.setPreferredSize(new Dimension(500, 500)); + spane = new JScrollPane(label); + fr.getContentPane().add(spane); + sbar = spane.getVerticalScrollBar(); + + fr.setSize(200, 200); + fr.setVisible(true); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/javax/swing/JScrollBar/4865918/bug4865918.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4865918 + * @summary REGRESSION:JCK1.4a-runtime api/javax_swing/interactive/JScrollBarTests.html#JScrollBar + * @author Andrey Pikalev + * @run main bug4865918 + */ + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.util.*; +import sun.awt.SunToolkit; + +public class bug4865918 { + + private static TestScrollBar sbar; + + public static void main(String[] argv) throws Exception { + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + + SwingUtilities.invokeAndWait(new Runnable() { + + public void run() { + createAndShowGUI(); + } + }); + + toolkit.realSync(); + + SwingUtilities.invokeAndWait(new Runnable() { + + @Override + public void run() { + sbar.pressMouse(); + } + }); + + toolkit.realSync(); + + int value = getValue(); + + if (value != 9) { + throw new Error("The scrollbar block increment is incorect"); + } + } + + private static int getValue() throws Exception { + final int[] result = new int[1]; + + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + result[0] = sbar.getValue(); + } + }); + + return result[0]; + } + + private static void createAndShowGUI() { + JFrame frame = new JFrame("bug4865918"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + sbar = new TestScrollBar(JScrollBar.HORIZONTAL, -1, 10, -100, 100); + sbar.setPreferredSize(new Dimension(200, 20)); + sbar.setBlockIncrement(10); + + frame.getContentPane().add(sbar); + frame.pack(); + frame.setVisible(true); + + } + + static class TestScrollBar extends JScrollBar { + + public TestScrollBar(int orientation, int value, int extent, + int min, int max) { + super(orientation, value, extent, min, max); + + } + + public void pressMouse() { + MouseEvent me = new MouseEvent(sbar, + MouseEvent.MOUSE_PRESSED, + (new Date()).getTime(), + MouseEvent.BUTTON1_MASK, + 3 * getWidth() / 4, getHeight() / 2, + 1, true); + processMouseEvent(me); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/javax/swing/JSlider/6348946/bug6348946.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6348946 + * @summary Tests that JSlider's thumb moves in the right direction + * when it is used as a JTable cell editor. + * @author Mikhail Lapshin +*/ + +import sun.awt.SunToolkit; + +import java.awt.*; +import java.awt.event.InputEvent; +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.table.*; + +public class bug6348946 { + + private static JFrame frame; + + private static JPanel panel; + + private static volatile boolean passed = false; + + public static void main(String[] args) throws Exception { + String lf = "javax.swing.plaf.metal.MetalLookAndFeel"; + UIManager.setLookAndFeel(lf); + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + setupUI(); + } + }); + toolkit.realSync(); + clickOnSlider(); + toolkit.realSync(); + checkResult(); + } finally { + stopEDT(); + } + } + + private static void setupUI() { + frame = new JFrame(); + + panel = new JPanel(); + panel.setLayout(new BorderLayout()); + panel.add(new ParameterTable(), BorderLayout.CENTER); + frame.getContentPane().add(panel); + + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private static void clickOnSlider() throws Exception { + Robot robot = new Robot(); + robot.setAutoDelay(10); + + Rectangle rect = getPanelRectangle(); + + double clickX = rect.getX() + rect.getWidth() / 4; + double clickY = rect.getY() + rect.getHeight() / 2; + robot.mouseMove((int) clickX, (int) clickY); + + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + } + + private static void checkResult(){ + if (passed) { + System.out.println("Test passed"); + } else { + throw new RuntimeException("The thumb moved " + + "to the right instead of the left!"); + } + } + + private static void stopEDT() { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + frame.dispose(); + } + }); + } + + private static class ParameterTable extends JTable { + public ParameterTable() { + super(new Object[][]{{5}}, new String[]{"Value"}); + getColumnModel().getColumn(0).setCellRenderer(new Renderer()); + getColumnModel().getColumn(0).setCellEditor(new Editor()); + } + } + + private static class Renderer implements TableCellRenderer { + private JSlider slider = new JSlider(0, 10); + + public Component getTableCellRendererComponent(JTable table, + Object value, + boolean isSelected, + boolean hasFocus, + int row, int col) { + int val = (Integer) value; + slider.setValue(val); + return slider; + } + } + + private static class Editor extends AbstractCellEditor implements TableCellEditor { + private JSlider slider = new JSlider(0, 10); + + public Component getTableCellEditorComponent(JTable table, Object value, + boolean isSelected, + int row, int col) { + int val = (Integer) value; + slider.setValue(val); + return slider; + } + + public Editor() { + slider.addChangeListener(new ChangeListener() { + public void stateChanged(ChangeEvent e) { + if (!slider.getValueIsAdjusting()) { + passed = slider.getValue() <= 5; + } + } + }); + } + + public Object getCellEditorValue() { + return slider.getValue(); + } + } + + private static Rectangle getPanelRectangle() throws Exception{ + final Rectangle[] result = new Rectangle[1]; + + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + result[0] = new Rectangle(panel.getLocationOnScreen(), panel.getSize()); + } + }); + + return result[0]; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/javax/swing/JTabbedPane/4624207/bug4624207.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4624207 + * @summary JTabbedPane mnemonics don't work from outside the tabbed pane + * @author Oleg Mokhovikov + * @library ../../regtesthelpers + * @build Util + * @run main bug4624207 + */ +import javax.swing.*; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import java.awt.*; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.awt.event.KeyEvent; +import sun.awt.SunToolkit; + +public class bug4624207 implements ChangeListener, FocusListener { + + private static volatile boolean stateChanged = false; + private static volatile boolean focusGained = false; + private static JTextField txtField; + private static JTabbedPane tab; + private static Object listener; + + public void stateChanged(ChangeEvent e) { + System.out.println("stateChanged called"); + stateChanged = true; + } + + public void focusGained(FocusEvent e) { + System.out.println("focusGained called"); + focusGained = true; + } + + public void focusLost(FocusEvent e) { + System.out.println("focusLost called"); + focusGained = false; + } + + public static void main(String[] args) throws Exception { + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + Robot robot = new Robot(); + robot.setAutoDelay(50); + + SwingUtilities.invokeAndWait(new Runnable() { + + public void run() { + createAndShowGUI(); + } + }); + + toolkit.realSync(); + + SwingUtilities.invokeAndWait(new Runnable() { + + public void run() { + txtField.requestFocus(); + } + }); + + toolkit.realSync(); + + if (!focusGained) { + throw new RuntimeException("Couldn't gain focus for text field"); + } + + SwingUtilities.invokeAndWait(new Runnable() { + + public void run() { + tab.addChangeListener((ChangeListener) listener); + txtField.removeFocusListener((FocusListener) listener); + } + }); + + toolkit.realSync(); + + if ("Aqua".equals(UIManager.getLookAndFeel().getID())) { + Util.hitKeys(robot, KeyEvent.VK_CONTROL, KeyEvent.VK_ALT, KeyEvent.VK_B); + } else { + Util.hitKeys(robot, KeyEvent.VK_ALT, KeyEvent.VK_B); + } + + toolkit.realSync(); + + if (!stateChanged || tab.getSelectedIndex() != 1) { + throw new RuntimeException("JTabbedPane mnemonics don't work from outside the tabbed pane"); + } + } + + private static void createAndShowGUI() { + tab = new JTabbedPane(); + tab.add("Tab1", new JButton("Button1")); + tab.add("Tab2", new JButton("Button2")); + tab.setMnemonicAt(0, KeyEvent.VK_T); + tab.setMnemonicAt(1, KeyEvent.VK_B); + + JFrame frame = new JFrame(); + frame.getContentPane().add(tab, BorderLayout.CENTER); + txtField = new JTextField(); + frame.getContentPane().add(txtField, BorderLayout.NORTH); + listener = new bug4624207(); + txtField.addFocusListener((FocusListener) listener); + frame.pack(); + frame.setVisible(true); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/javax/swing/JTabbedPane/6416920/bug6416920.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6416920 + * @summary Ensures that selected tab is painted properly in the scroll tab layout + * under WindowsLookAndFeel in Windows' "Windows XP" theme. + * @author Mikhail Lapshin + * @run main bug6416920 + */ + +import javax.swing.plaf.basic.BasicTabbedPaneUI; +import javax.swing.JTabbedPane; +import javax.swing.SwingConstants; +import java.awt.Rectangle; +import java.awt.Insets; +import sun.awt.OSInfo; + +public class bug6416920 extends BasicTabbedPaneUI { + public AccessibleTabbedPaneLayout layout = new AccessibleTabbedPaneLayout(); + + public static void main(String[] args) { + + if(OSInfo.getOSType() != OSInfo.OSType.WINDOWS){ + return; + } + + bug6416920 test = new bug6416920(); + test.layout.padSelectedTab(SwingConstants.TOP, 0); + if (test.rects[0].width < 0) { + throw new RuntimeException("A selected tab isn't painted properly " + + "in the scroll tab layout under WindowsLookAndFeel " + + "in Windows' \"Windows XP\" theme."); + } + } + + public bug6416920() { + super(); + + // Set parameters for the padSelectedTab() method + selectedTabPadInsets = new Insets(0, 0, 0, 0); + + tabPane = new JTabbedPane(); + tabPane.setSize(100, 0); + tabPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); + + rects = new Rectangle[1]; + rects[0] = new Rectangle(150, 0, 0, 0); + } + + public class AccessibleTabbedPaneLayout extends BasicTabbedPaneUI.TabbedPaneLayout { + public void padSelectedTab(int tabPlacement, int selectedIndex) { + super.padSelectedTab(tabPlacement, selectedIndex); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/javax/swing/PopupFactory/6276087/NonOpaquePopupMenuTest.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 6276087 + * @author Romain Guy + * @summary Tests opacity of a popup menu. + */ +import java.awt.*; +import java.awt.event.*; + +import javax.swing.*; +import sun.awt.SunToolkit; + +public class NonOpaquePopupMenuTest extends JFrame { + + private static JMenu fileMenu; + + public NonOpaquePopupMenuTest() { + getContentPane().setBackground(java.awt.Color.RED); + JMenuBar menuBar = new JMenuBar(); + fileMenu = new JMenu("File"); + JMenuItem menuItem = new JMenuItem("New"); + menuBar.add(fileMenu); + setJMenuBar(menuBar); + + fileMenu.add(menuItem); + fileMenu.getPopupMenu().setOpaque(false); + + setSize(new Dimension(640, 480)); + setVisible(true); + } + + public static void main(String[] args) throws Throwable { + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + Robot robot = new Robot(); + robot.setAutoDelay(250); + + SwingUtilities.invokeAndWait(new Runnable() { + + @Override + public void run() { + new NonOpaquePopupMenuTest(); + } + }); + + toolkit.realSync(); + + Point p = getMenuClickPoint(); + robot.mouseMove(p.x, p.y); + robot.mousePress(InputEvent.BUTTON1_MASK); + + toolkit.realSync(); + + if (isParentOpaque()) { + throw new RuntimeException("Popup menu parent is opaque"); + } + + } + + private static boolean isParentOpaque() throws Exception { + final boolean result[] = new boolean[1]; + + SwingUtilities.invokeAndWait(new Runnable() { + + @Override + public void run() { + result[0] = fileMenu.getPopupMenu().getParent().isOpaque(); + } + }); + + return result[0]; + } + + private static Point getMenuClickPoint() throws Exception { + final Point[] result = new Point[1]; + + SwingUtilities.invokeAndWait(new Runnable() { + + @Override + public void run() { + Point p = fileMenu.getLocationOnScreen(); + Dimension size = fileMenu.getSize(); + + result[0] = new Point(p.x + size.width / 2, + p.y + size.height / 2); + } + }); + + return result[0]; + + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/javax/swing/plaf/metal/MetalLookAndFeel/5073047/bug5073047.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 5073407 + * @summary Tests 5073407 + * @author Scott Violet + */ + +import javax.swing.*; +import javax.swing.plaf.*; +import javax.swing.plaf.metal.*; + +public class bug5073047 { + + public static void main(String[] args) throws Exception{ + MyTheme theme = new MyTheme(); + MetalLookAndFeel.setCurrentTheme(theme); + UIManager.setLookAndFeel(new MetalLookAndFeel()); + if (UIManager.get("Button.font") != theme.ctf) { + throw new RuntimeException("Unexpected font"); + } + } + + private static class MyTheme extends DefaultMetalTheme { + public final FontUIResource ctf = new FontUIResource( + super.getControlTextFont().deriveFont(40.0f)); + public FontUIResource getControlTextFont() { + return ctf; + } + } +}
--- a/test/javax/swing/regtesthelpers/Util.java Wed Dec 21 20:03:17 2011 -0800 +++ b/test/javax/swing/regtesthelpers/Util.java Fri Dec 23 16:08:11 2011 -0800 @@ -116,4 +116,17 @@ System.out.println("Got OOME"); } + + /** + * Hits keys by robot. + */ + public static void hitKeys(Robot robot, int... keys) { + for (int i = 0; i < keys.length; i++) { + robot.keyPress(keys[i]); + } + + for (int i = keys.length - 1; i >= 0; i--) { + robot.keyRelease(keys[i]); + } + } }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/javax/swing/text/DefaultEditorKit/4278839/bug4278839.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test Jan 16, 2003 + * @bug 4278839 + * @summary Incorrect cursor movement between words at the end of line + * @author Anton Nashatyrev + * @library ../../../regtesthelpers + * @build Util + * @run main bug4278839 + */ + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import sun.awt.SunToolkit; + +public class bug4278839 extends JFrame { + + private static boolean passed = true; + private static JTextArea area; + private static Robot robo; + private static SunToolkit toolkit; + + public static void main(String[] args) { + try { + + toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + robo = new Robot(); + robo.setAutoDelay(100); + + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + createAndShowGUI(); + } + }); + + toolkit.realSync(); + + clickMouse(); + toolkit.realSync(); + + + if ("Aqua".equals(UIManager.getLookAndFeel().getID())) { + Util.hitKeys(robo, KeyEvent.VK_HOME); + } else { + Util.hitKeys(robo, KeyEvent.VK_CONTROL, KeyEvent.VK_HOME); + } + toolkit.realSync(); + + passed &= moveCaret(true) == 1; + passed &= moveCaret(true) == 5; + passed &= moveCaret(true) == 8; + passed &= moveCaret(true) == 9; + passed &= moveCaret(true) == 13; + passed &= moveCaret(true) == 16; + passed &= moveCaret(true) == 17; + passed &= moveCaret(false) == 16; + passed &= moveCaret(false) == 13; + passed &= moveCaret(false) == 9; + passed &= moveCaret(false) == 8; + passed &= moveCaret(false) == 5; + passed &= moveCaret(false) == 1; + passed &= moveCaret(false) == 0; + + } catch (Exception e) { + throw new RuntimeException("Test failed because of an exception:", + e); + } + + if (!passed) { + throw new RuntimeException("Test failed."); + } + } + + private static int moveCaret(boolean right) throws Exception { + Util.hitKeys(robo, getCtrlKey(), + right ? KeyEvent.VK_RIGHT : KeyEvent.VK_LEFT); + toolkit.realSync(); + + final int[] result = new int[1]; + + SwingUtilities.invokeAndWait(new Runnable() { + + @Override + public void run() { + result[0] = area.getCaretPosition(); + } + }); + + int pos = result[0]; + return pos; + } + + private static void clickMouse() throws Exception { + final Rectangle result[] = new Rectangle[1]; + + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + result[0] = new Rectangle(area.getLocationOnScreen(), area.getSize()); + } + }); + + Rectangle rect = result[0]; + + robo.mouseMove(rect.x + rect.width / 2, rect.y + rect.width / 2); + robo.mousePress(InputEvent.BUTTON1_MASK); + } + + /** + * Gets a control key related to the used Look & Feel + * Returns VK_ALT for Aqua and VK_CONTROL for others + */ + public static int getCtrlKey() { + + if ("Aqua".equals(UIManager.getLookAndFeel().getID())) { + return KeyEvent.VK_ALT; + } + + return KeyEvent.VK_CONTROL; + } + + private static void createAndShowGUI() { + JFrame frame = new JFrame(); + frame.setTitle("Bug# 4278839"); + frame.setSize(200, 200); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + area = new JTextArea("\naaa bbb\nccc ddd\n"); + frame.getContentPane().add(new JScrollPane(area)); + frame.setVisible(true); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/javax/swing/text/JTextComponent/5074573/bug5074573.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 5074573 + * @summary tests delte-next-word and delete-prev-word actions for all text compnents and all look&feels + * @author Igor Kushnirskiy + * @run main bug5074573 + */ + +import java.util.*; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.text.*; +import sun.awt.SunToolkit; + +public class bug5074573 { + + private static JTextComponent textComponent; + final static String testString = "123 456 789"; + final static String resultString = "456 "; + final static List<Class<? extends JTextComponent>> textClasses = Arrays.asList( + JTextArea.class, JEditorPane.class, JTextPane.class, + JTextField.class, JFormattedTextField.class, JPasswordField.class); + + public static void main(String[] args) throws Exception { + for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { + UIManager.setLookAndFeel(info.getClassName()); + System.out.println(info); + for (Class<? extends JTextComponent> clazz : textClasses) { + boolean res = test(clazz); + if (!res && clazz != JPasswordField.class) { + throw new RuntimeException("failed"); + } + } + } + } + + static boolean test(final Class<? extends JTextComponent> textComponentClass) throws Exception { + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + Robot robot = new Robot(); + robot.setAutoWaitForIdle(true); + robot.setAutoDelay(50); + + SwingUtilities.invokeAndWait(new Runnable() { + + @Override + public void run() { + initialize(textComponentClass); + } + }); + + toolkit.realSync(); + + // Remove selection from JTextField components for the Aqua Look & Feel + if (textComponent instanceof JTextField && "Aqua".equals(UIManager.getLookAndFeel().getID())) { + SwingUtilities.invokeAndWait(new Runnable() { + + @Override + public void run() { + Caret caret = textComponent.getCaret(); + int dot = caret.getDot(); + textComponent.select(dot, dot); + } + }); + + toolkit.realSync(); + } + + robot.keyPress(getCtrlKey()); + robot.keyPress(KeyEvent.VK_BACK_SPACE); + robot.keyRelease(KeyEvent.VK_BACK_SPACE); + robot.keyRelease(getCtrlKey()); + toolkit.realSync(); + + SwingUtilities.invokeAndWait(new Runnable() { + + @Override + public void run() { + Caret caret = textComponent.getCaret(); + caret.setDot(0); + } + }); + toolkit.realSync(); + + robot.keyPress(getCtrlKey()); + robot.keyPress(KeyEvent.VK_DELETE); + robot.keyRelease(KeyEvent.VK_DELETE); + robot.keyRelease(getCtrlKey()); + toolkit.realSync(); + + return resultString.equals(getText()); + } + + private static String getText() throws Exception { + final String[] result = new String[1]; + + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + result[0] = textComponent.getText(); + } + }); + + return result[0]; + } + + /** + * Gets a control key related to the used Look & Feel + * Returns VK_ALT for Aqua and VK_CONTROL for others + */ + public static int getCtrlKey() { + + if ("Aqua".equals(UIManager.getLookAndFeel().getID())) { + return KeyEvent.VK_ALT; + } + + return KeyEvent.VK_CONTROL; + } + + private static void initialize(Class<? extends JTextComponent> textComponentClass) { + try { + JFrame frame = new JFrame(); + textComponent = textComponentClass.newInstance(); + textComponent.setText(testString); + frame.add(textComponent); + frame.pack(); + frame.setVisible(true); + textComponent.requestFocus(); + Caret caret = textComponent.getCaret(); + caret.setDot(textComponent.getDocument().getLength()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/javax/swing/text/html/HTMLEditorKit/5043626/bug5043626.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 5043626 + * @summary Tests pressing Home or Ctrl+Home set cursor to invisible element <head> + * @author Alexander Potochkin + * @library ../../../../regtesthelpers + * @build Util + * @run main bug5043626 + */ + +import java.awt.Robot; +import java.awt.Toolkit; +import javax.swing.*; +import javax.swing.text.Document; +import javax.swing.text.BadLocationException; +import java.awt.event.KeyEvent; +import sun.awt.SunToolkit; + +public class bug5043626 { + + private static Document doc; + private static Robot robot; + + public static void main(String[] args) throws Exception { + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + robot = new Robot(); + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + createAndShowGUI(); + } + }); + + toolkit.realSync(); + + Util.hitKeys(robot, KeyEvent.VK_HOME); + Util.hitKeys(robot, KeyEvent.VK_1); + + toolkit.realSync(); + + String test = getText(); + + if (!"1test".equals(test)) { + throw new RuntimeException("Begin line action set cursor inside <head> tag"); + } + + Util.hitKeys(robot, KeyEvent.VK_HOME); + Util.hitKeys(robot, KeyEvent.VK_2); + + toolkit.realSync(); + + test = getText(); + + if (!"21test".equals(test)) { + throw new RuntimeException("Begin action set cursor inside <head> tag"); + } + } + + private static String getText() throws Exception { + final String[] result = new String[1]; + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + try { + result[0] = doc.getText(0, doc.getLength()).trim(); + } catch (BadLocationException ex) { + ex.printStackTrace(); + } + } + }); + + return result[0]; + } + + private static void createAndShowGUI() { + JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JEditorPane editorPane = new JEditorPane(); + editorPane.setContentType("text/html"); + editorPane.setText("test"); + editorPane.setEditable(true); + frame.add(editorPane); + frame.pack(); + frame.setVisible(true); + doc = editorPane.getDocument(); + editorPane.setCaretPosition(doc.getLength()); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLContextImpl/MD2InTrustAnchor.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,423 @@ +/* + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 7113275 + * @summary compatibility issue with MD2 trust anchor and old X509TrustManager + * + * SunJSSE does not support dynamic system properties, no way to re-use + * system properties in samevm/agentvm mode. + * @run main/othervm MD2InTrustAnchor PKIX TLSv1.1 + * @run main/othervm MD2InTrustAnchor SunX509 TLSv1.1 + * @run main/othervm MD2InTrustAnchor PKIX TLSv1.2 + * @run main/othervm MD2InTrustAnchor SunX509 TLSv1.2 + */ + +import java.net.*; +import java.util.*; +import java.io.*; +import javax.net.ssl.*; +import java.security.KeyStore; +import java.security.KeyFactory; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.spec.*; +import java.security.interfaces.*; +import sun.misc.BASE64Decoder; + + +public class MD2InTrustAnchor { + + /* + * ============================================================= + * Set the various variables needed for the tests, then + * specify what tests to run on each side. + */ + + /* + * Should we run the client or server in a separate thread? + * Both sides can throw exceptions, but do you have a preference + * as to which side should be the main thread. + */ + static boolean separateServerThread = false; + + /* + * Certificates and key used in the test. + */ + + // It's a trust anchor signed with MD2 hash function. + static String trustedCertStr = + "-----BEGIN CERTIFICATE-----\n" + + "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQIFADA7MQswCQYDVQQGEwJVUzEN\n" + + "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + + "MTExMTE4MTExNDA0WhcNMzIxMDI4MTExNDA0WjA7MQswCQYDVQQGEwJVUzENMAsG\n" + + "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" + + "KoZIhvcNAQEBBQADgY0AMIGJAoGBAPGyB9tugUGgxtdeqe0qJEwf9x1Gy4BOi1yR\n" + + "wzDZY4H5LquvIfQ2V3J9X1MQENVsFvkvp65ZcFcy+ObOucXUUPFcd/iw2DVb5QXA\n" + + "ffyeVqWD56GPi8Qe37wrJO3L6fBhN9oxp/BbdRLgjU81zx8qLEyPODhPMxV4OkcA\n" + + "SDwZTSxxAgMBAAGjgaUwgaIwHQYDVR0OBBYEFLOAtr/YrYj9H04EDLA0fd14jisF\n" + + "MGMGA1UdIwRcMFqAFLOAtr/YrYj9H04EDLA0fd14jisFoT+kPTA7MQswCQYDVQQG\n" + + "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + + "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEC\n" + + "BQADgYEAr8ExpXu/FTIRiMzPm0ubqwME4lniilwQUiEOD/4DbksNjEIcUyS2hIk1\n" + + "qsmjJz3SHBnwhxl9dhJVwk2tZLkPGW86Zn0TPVRsttK4inTgCC9GFGeqQBdrU/uf\n" + + "lipBzXWljrfbg4N/kK8m2LabtKUMMnGysM8rN0Fx2PYm5xxGvtM=\n" + + "-----END CERTIFICATE-----"; + + // The certificate issued by above trust anchor, signed with MD5 + static String targetCertStr = + "-----BEGIN CERTIFICATE-----\n" + + "MIICeDCCAeGgAwIBAgIBAjANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + + "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + + "MTExMTE4MTExNDA2WhcNMzEwODA1MTExNDA2WjBPMQswCQYDVQQGEwJVUzENMAsG\n" + + "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxEjAQBgNV\n" + + "BAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwDnm96mw\n" + + "fXCH4bgXk1US0VcJsQVxUtGMyncAveMuzBzNzOmKZPeqyYX1Fuh4q+cuza03WTJd\n" + + "G9nOkNr364e3Rn1aaHjCMcBmFflObnGnhhufNmIGYogJ9dJPmhUVPEVAXrMG+Ces\n" + + "NKy2E8woGnLMrqu6yiuTClbLBPK8fWzTXrECAwEAAaN4MHYwCwYDVR0PBAQDAgPo\n" + + "MB0GA1UdDgQWBBSdRrpocLPJXyGfDmMWJrcEf29WGDAfBgNVHSMEGDAWgBSzgLa/\n" + + "2K2I/R9OBAywNH3deI4rBTAnBgNVHSUEIDAeBggrBgEFBQcDAQYIKwYBBQUHAwIG\n" + + "CCsGAQUFBwMDMA0GCSqGSIb3DQEBBAUAA4GBAKJ71ZiCUykkJrCLYUxlFlhvUcr9\n" + + "sTcOc67QdroW5f412NI15SXWDiley/JOasIiuIFPjaJBjOKoHOvTjG/snVu9wEgq\n" + + "YNR8dPsO+NM8r79C6jO+Jx5fYAC7os2XxS75h3NX0ElJcbwIXGBJ6xRrsFh/BGYH\n" + + "yvudOlX4BkVR0l1K\n" + + "-----END CERTIFICATE-----"; + + // Private key in the format of PKCS#8. + static String targetPrivateKey = + "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMA55vepsH1wh+G4\n" + + "F5NVEtFXCbEFcVLRjMp3AL3jLswczczpimT3qsmF9RboeKvnLs2tN1kyXRvZzpDa\n" + + "9+uHt0Z9Wmh4wjHAZhX5Tm5xp4YbnzZiBmKICfXST5oVFTxFQF6zBvgnrDSsthPM\n" + + "KBpyzK6rusorkwpWywTyvH1s016xAgMBAAECgYEAn9bF3oRkdDoBU0i/mcww5I+K\n" + + "SH9tFt+WQbiojjz9ac49trkvUfu7MO1Jui2+QbrvaSkyj+HYGFOJd1wMsPXeB7ck\n" + + "5mOIYV4uZK8jfNMSQ8v0tFEeIPp5lKdw1XnrQfSe+abo2eL5Lwso437Y4s3w37+H\n" + + "aY3d76hR5qly+Ys+Ww0CQQDjeOoX89d/xhRqGXKjCx8ImE/dPmsI8O27cwtKrDYJ\n" + + "6t0v/xryVIdvOYcRBvKnqEogOH7T1kI+LnWKUTJ2ehJ7AkEA2FVloPVqCehXcc7e\n" + + "z3TDpU9w1B0JXklcV5HddYsRqp9RukN/VK4szKE7F1yoarIUtfE9Lr9082Jwyp3M\n" + + "L11xwwJBAKsZ+Hur3x0tUY29No2Nf/pnFyvEF57SGwA0uPmiL8Ol9lpz+UDudDEl\n" + + "hIM6Rqv12kwCMuQE9i7vo1o3WU3k5KECQEqhg1L49yD935TqiiFFpe0Ur9btQXse\n" + + "kdXAA4d2d5zGI7q/aGD9SYU6phkUJSHR16VA2RuUfzMrpb+wmm1IrmMCQFtLoKRT\n" + + "A5kokFb+E3Gplu29tJvCUpfwgBFRS+wmkvtiaU/tiyDcVgDO+An5DwedxxdVzqiE\n" + + "njWHoKY3axDQ8OU=\n"; + + + static char passphrase[] = "passphrase".toCharArray(); + + /* + * Is the server ready to serve? + */ + volatile static boolean serverReady = false; + + /* + * Turn on SSL debugging? + */ + static boolean debug = false; + + /* + * Define the server side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + void doServerSide() throws Exception { + SSLContext context = generateSSLContext(trustedCertStr, targetCertStr, + targetPrivateKey); + SSLServerSocketFactory sslssf = context.getServerSocketFactory(); + SSLServerSocket sslServerSocket = + (SSLServerSocket)sslssf.createServerSocket(serverPort); + sslServerSocket.setNeedClientAuth(true); + serverPort = sslServerSocket.getLocalPort(); + + /* + * Signal Client, we're ready for his connect. + */ + serverReady = true; + + SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept(); + InputStream sslIS = sslSocket.getInputStream(); + OutputStream sslOS = sslSocket.getOutputStream(); + + sslIS.read(); + sslOS.write('A'); + sslOS.flush(); + + sslSocket.close(); + } + + /* + * Define the client side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + void doClientSide() throws Exception { + + /* + * Wait for server to get started. + */ + while (!serverReady) { + Thread.sleep(50); + } + + SSLContext context = generateSSLContext(trustedCertStr, targetCertStr, + targetPrivateKey); + SSLSocketFactory sslsf = context.getSocketFactory(); + + SSLSocket sslSocket = + (SSLSocket)sslsf.createSocket("localhost", serverPort); + + // enable the specified TLS protocol + sslSocket.setEnabledProtocols(new String[] {tlsProtocol}); + + InputStream sslIS = sslSocket.getInputStream(); + OutputStream sslOS = sslSocket.getOutputStream(); + + sslOS.write('B'); + sslOS.flush(); + sslIS.read(); + + sslSocket.close(); + } + + /* + * ============================================================= + * The remainder is just support stuff + */ + private static String tmAlgorithm; // trust manager + private static String tlsProtocol; // trust manager + + private static void parseArguments(String[] args) { + tmAlgorithm = args[0]; + tlsProtocol = args[1]; + } + + private static SSLContext generateSSLContext(String trustedCertStr, + String keyCertStr, String keySpecStr) throws Exception { + + // generate certificate from cert string + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + + // create a key store + KeyStore ks = KeyStore.getInstance("JKS"); + ks.load(null, null); + + // import the trused cert + Certificate trusedCert = null; + ByteArrayInputStream is = null; + if (trustedCertStr != null) { + is = new ByteArrayInputStream(trustedCertStr.getBytes()); + trusedCert = cf.generateCertificate(is); + is.close(); + + ks.setCertificateEntry("RSA Export Signer", trusedCert); + } + + if (keyCertStr != null) { + // generate the private key. + PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( + new BASE64Decoder().decodeBuffer(keySpecStr)); + KeyFactory kf = KeyFactory.getInstance("RSA"); + RSAPrivateKey priKey = + (RSAPrivateKey)kf.generatePrivate(priKeySpec); + + // generate certificate chain + is = new ByteArrayInputStream(keyCertStr.getBytes()); + Certificate keyCert = cf.generateCertificate(is); + is.close(); + + // It's not allowed to send MD2 signed certificate to peer, + // even it may be a trusted certificate. Then we will not + // place the trusted certficate in the chain. + Certificate[] chain = new Certificate[1]; + chain[0] = keyCert; + + // import the key entry. + ks.setKeyEntry("Whatever", priKey, passphrase, chain); + } + + // create SSL context + TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); + tmf.init(ks); + + SSLContext ctx = SSLContext.getInstance(tlsProtocol); + if (keyCertStr != null && !keyCertStr.isEmpty()) { + KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); + kmf.init(ks, passphrase); + + ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + ks = null; + } else { + ctx.init(null, tmf.getTrustManagers(), null); + } + + return ctx; + } + + + // use any free port by default + volatile int serverPort = 0; + + volatile Exception serverException = null; + volatile Exception clientException = null; + + public static void main(String[] args) throws Exception { + if (debug) + System.setProperty("javax.net.debug", "all"); + + /* + * Get the customized arguments. + */ + parseArguments(args); + + /* + * Start the tests. + */ + new MD2InTrustAnchor(); + } + + Thread clientThread = null; + Thread serverThread = null; + + /* + * Primary constructor, used to drive remainder of the test. + * + * Fork off the other side, then do your work. + */ + MD2InTrustAnchor() throws Exception { + try { + if (separateServerThread) { + startServer(true); + startClient(false); + } else { + startClient(true); + startServer(false); + } + } catch (Exception e) { + // swallow for now. Show later + } + + /* + * Wait for other side to close down. + */ + if (separateServerThread) { + serverThread.join(); + } else { + clientThread.join(); + } + + /* + * When we get here, the test is pretty much over. + * Which side threw the error? + */ + Exception local; + Exception remote; + String whichRemote; + + if (separateServerThread) { + remote = serverException; + local = clientException; + whichRemote = "server"; + } else { + remote = clientException; + local = serverException; + whichRemote = "client"; + } + + /* + * If both failed, return the curthread's exception, but also + * print the remote side Exception + */ + if ((local != null) && (remote != null)) { + System.out.println(whichRemote + " also threw:"); + remote.printStackTrace(); + System.out.println(); + throw local; + } + + if (remote != null) { + throw remote; + } + + if (local != null) { + throw local; + } + } + + void startServer(boolean newThread) throws Exception { + if (newThread) { + serverThread = new Thread() { + public void run() { + try { + doServerSide(); + } catch (Exception e) { + /* + * Our server thread just died. + * + * Release the client, if not active already... + */ + System.err.println("Server died..."); + serverReady = true; + serverException = e; + } + } + }; + serverThread.start(); + } else { + try { + doServerSide(); + } catch (Exception e) { + serverException = e; + } finally { + serverReady = true; + } + } + } + + void startClient(boolean newThread) throws Exception { + if (newThread) { + clientThread = new Thread() { + public void run() { + try { + doClientSide(); + } catch (Exception e) { + /* + * Our client thread just died. + */ + System.err.println("Client died..."); + clientException = e; + } + } + }; + clientThread.start(); + } else { + try { + doClientSide(); + } catch (Exception e) { + clientException = e; + } + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLContextImpl/TrustTrustedCert.java Fri Dec 23 16:08:11 2011 -0800 @@ -0,0 +1,475 @@ +/* + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 7113275 + * @summary compatibility issue with MD2 trust anchor and old X509TrustManager + * + * SunJSSE does not support dynamic system properties, no way to re-use + * system properties in samevm/agentvm mode. + * @run main/othervm TrustTrustedCert PKIX TLSv1.1 + * @run main/othervm TrustTrustedCert SunX509 TLSv1.1 + * @run main/othervm TrustTrustedCert PKIX TLSv1.2 + * @run main/othervm TrustTrustedCert SunX509 TLSv1.2 + */ + +import java.net.*; +import java.util.*; +import java.io.*; +import javax.net.ssl.*; +import java.security.*; +import java.security.cert.*; +import java.security.spec.*; +import java.security.interfaces.*; +import sun.misc.BASE64Decoder; + + +public class TrustTrustedCert { + + /* + * ============================================================= + * Set the various variables needed for the tests, then + * specify what tests to run on each side. + */ + + /* + * Should we run the client or server in a separate thread? + * Both sides can throw exceptions, but do you have a preference + * as to which side should be the main thread. + */ + static boolean separateServerThread = false; + + /* + * Certificates and key used in the test. + */ + + // It's a trust anchor signed with MD2 hash function. + static String trustedCertStr = + "-----BEGIN CERTIFICATE-----\n" + + "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQIFADA7MQswCQYDVQQGEwJVUzEN\n" + + "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + + "MTExMTE4MTExNDA0WhcNMzIxMDI4MTExNDA0WjA7MQswCQYDVQQGEwJVUzENMAsG\n" + + "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" + + "KoZIhvcNAQEBBQADgY0AMIGJAoGBAPGyB9tugUGgxtdeqe0qJEwf9x1Gy4BOi1yR\n" + + "wzDZY4H5LquvIfQ2V3J9X1MQENVsFvkvp65ZcFcy+ObOucXUUPFcd/iw2DVb5QXA\n" + + "ffyeVqWD56GPi8Qe37wrJO3L6fBhN9oxp/BbdRLgjU81zx8qLEyPODhPMxV4OkcA\n" + + "SDwZTSxxAgMBAAGjgaUwgaIwHQYDVR0OBBYEFLOAtr/YrYj9H04EDLA0fd14jisF\n" + + "MGMGA1UdIwRcMFqAFLOAtr/YrYj9H04EDLA0fd14jisFoT+kPTA7MQswCQYDVQQG\n" + + "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + + "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEC\n" + + "BQADgYEAr8ExpXu/FTIRiMzPm0ubqwME4lniilwQUiEOD/4DbksNjEIcUyS2hIk1\n" + + "qsmjJz3SHBnwhxl9dhJVwk2tZLkPGW86Zn0TPVRsttK4inTgCC9GFGeqQBdrU/uf\n" + + "lipBzXWljrfbg4N/kK8m2LabtKUMMnGysM8rN0Fx2PYm5xxGvtM=\n" + + "-----END CERTIFICATE-----"; + + // The certificate issued by above trust anchor, signed with MD5 + static String targetCertStr = + "-----BEGIN CERTIFICATE-----\n" + + "MIICeDCCAeGgAwIBAgIBAjANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + + "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + + "MTExMTE4MTExNDA2WhcNMzEwODA1MTExNDA2WjBPMQswCQYDVQQGEwJVUzENMAsG\n" + + "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxEjAQBgNV\n" + + "BAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwDnm96mw\n" + + "fXCH4bgXk1US0VcJsQVxUtGMyncAveMuzBzNzOmKZPeqyYX1Fuh4q+cuza03WTJd\n" + + "G9nOkNr364e3Rn1aaHjCMcBmFflObnGnhhufNmIGYogJ9dJPmhUVPEVAXrMG+Ces\n" + + "NKy2E8woGnLMrqu6yiuTClbLBPK8fWzTXrECAwEAAaN4MHYwCwYDVR0PBAQDAgPo\n" + + "MB0GA1UdDgQWBBSdRrpocLPJXyGfDmMWJrcEf29WGDAfBgNVHSMEGDAWgBSzgLa/\n" + + "2K2I/R9OBAywNH3deI4rBTAnBgNVHSUEIDAeBggrBgEFBQcDAQYIKwYBBQUHAwIG\n" + + "CCsGAQUFBwMDMA0GCSqGSIb3DQEBBAUAA4GBAKJ71ZiCUykkJrCLYUxlFlhvUcr9\n" + + "sTcOc67QdroW5f412NI15SXWDiley/JOasIiuIFPjaJBjOKoHOvTjG/snVu9wEgq\n" + + "YNR8dPsO+NM8r79C6jO+Jx5fYAC7os2XxS75h3NX0ElJcbwIXGBJ6xRrsFh/BGYH\n" + + "yvudOlX4BkVR0l1K\n" + + "-----END CERTIFICATE-----"; + + // Private key in the format of PKCS#8. + static String targetPrivateKey = + "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMA55vepsH1wh+G4\n" + + "F5NVEtFXCbEFcVLRjMp3AL3jLswczczpimT3qsmF9RboeKvnLs2tN1kyXRvZzpDa\n" + + "9+uHt0Z9Wmh4wjHAZhX5Tm5xp4YbnzZiBmKICfXST5oVFTxFQF6zBvgnrDSsthPM\n" + + "KBpyzK6rusorkwpWywTyvH1s016xAgMBAAECgYEAn9bF3oRkdDoBU0i/mcww5I+K\n" + + "SH9tFt+WQbiojjz9ac49trkvUfu7MO1Jui2+QbrvaSkyj+HYGFOJd1wMsPXeB7ck\n" + + "5mOIYV4uZK8jfNMSQ8v0tFEeIPp5lKdw1XnrQfSe+abo2eL5Lwso437Y4s3w37+H\n" + + "aY3d76hR5qly+Ys+Ww0CQQDjeOoX89d/xhRqGXKjCx8ImE/dPmsI8O27cwtKrDYJ\n" + + "6t0v/xryVIdvOYcRBvKnqEogOH7T1kI+LnWKUTJ2ehJ7AkEA2FVloPVqCehXcc7e\n" + + "z3TDpU9w1B0JXklcV5HddYsRqp9RukN/VK4szKE7F1yoarIUtfE9Lr9082Jwyp3M\n" + + "L11xwwJBAKsZ+Hur3x0tUY29No2Nf/pnFyvEF57SGwA0uPmiL8Ol9lpz+UDudDEl\n" + + "hIM6Rqv12kwCMuQE9i7vo1o3WU3k5KECQEqhg1L49yD935TqiiFFpe0Ur9btQXse\n" + + "kdXAA4d2d5zGI7q/aGD9SYU6phkUJSHR16VA2RuUfzMrpb+wmm1IrmMCQFtLoKRT\n" + + "A5kokFb+E3Gplu29tJvCUpfwgBFRS+wmkvtiaU/tiyDcVgDO+An5DwedxxdVzqiE\n" + + "njWHoKY3axDQ8OU=\n"; + + + static char passphrase[] = "passphrase".toCharArray(); + + /* + * Is the server ready to serve? + */ + volatile static boolean serverReady = false; + + /* + * Turn on SSL debugging? + */ + static boolean debug = false; + + /* + * Define the server side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + void doServerSide() throws Exception { + SSLContext context = generateSSLContext(); + SSLServerSocketFactory sslssf = context.getServerSocketFactory(); + SSLServerSocket sslServerSocket = + (SSLServerSocket)sslssf.createServerSocket(serverPort); + sslServerSocket.setNeedClientAuth(true); + serverPort = sslServerSocket.getLocalPort(); + + /* + * Signal Client, we're ready for his connect. + */ + serverReady = true; + + SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept(); + InputStream sslIS = sslSocket.getInputStream(); + OutputStream sslOS = sslSocket.getOutputStream(); + + sslIS.read(); + sslOS.write('A'); + sslOS.flush(); + + sslSocket.close(); + } + + /* + * Define the client side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + void doClientSide() throws Exception { + + /* + * Wait for server to get started. + */ + while (!serverReady) { + Thread.sleep(50); + } + + SSLContext context = generateSSLContext(); + SSLSocketFactory sslsf = context.getSocketFactory(); + + SSLSocket sslSocket = + (SSLSocket)sslsf.createSocket("localhost", serverPort); + + // enable the specified TLS protocol + sslSocket.setEnabledProtocols(new String[] {tlsProtocol}); + + InputStream sslIS = sslSocket.getInputStream(); + OutputStream sslOS = sslSocket.getOutputStream(); + + sslOS.write('B'); + sslOS.flush(); + sslIS.read(); + + sslSocket.close(); + } + + /* + * ============================================================= + * The remainder is just support stuff + */ + private static String tmAlgorithm; // trust manager + private static String tlsProtocol; // trust manager + + private static void parseArguments(String[] args) { + tmAlgorithm = args[0]; + tlsProtocol = args[1]; + } + + private static SSLContext generateSSLContext() throws Exception { + + // generate certificate from cert string + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + + // create a key store + KeyStore ks = KeyStore.getInstance("JKS"); + ks.load(null, null); + + // import the trused cert + X509Certificate trusedCert = null; + ByteArrayInputStream is = + new ByteArrayInputStream(trustedCertStr.getBytes()); + trusedCert = (X509Certificate)cf.generateCertificate(is); + is.close(); + + ks.setCertificateEntry("Trusted RSA Signer", trusedCert); + + // generate the private key. + PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( + new BASE64Decoder().decodeBuffer(targetPrivateKey)); + KeyFactory kf = KeyFactory.getInstance("RSA"); + RSAPrivateKey priKey = + (RSAPrivateKey)kf.generatePrivate(priKeySpec); + + // generate certificate chain + is = new ByteArrayInputStream(targetCertStr.getBytes()); + X509Certificate keyCert = (X509Certificate)cf.generateCertificate(is); + is.close(); + + X509Certificate[] chain = new X509Certificate[2]; + chain[0] = keyCert; + chain[1] = trusedCert; + + // import the key entry and the chain + ks.setKeyEntry("TheKey", priKey, passphrase, chain); + + // create SSL context + TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm); + tmf.init(ks); + + // create the customized KM and TM + NoneExtendedX509TM myTM = + new NoneExtendedX509TM(tmf.getTrustManagers()[0]); + NoneExtendedX509KM myKM = + new NoneExtendedX509KM("TheKey", chain, priKey); + + SSLContext ctx = SSLContext.getInstance(tlsProtocol); + // KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509"); + // kmf.init(ks, passphrase); + // ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + ctx.init(new KeyManager[]{myKM}, new TrustManager[]{myTM}, null); + ks = null; + + return ctx; + } + + static class NoneExtendedX509TM implements X509TrustManager { + X509TrustManager tm; + + NoneExtendedX509TM(TrustManager tm) { + this.tm = (X509TrustManager)tm; + } + + public void checkClientTrusted(X509Certificate chain[], String authType) + throws CertificateException { + tm.checkClientTrusted(chain, authType); + } + + public void checkServerTrusted(X509Certificate chain[], String authType) + throws CertificateException { + tm.checkServerTrusted(chain, authType); + } + + public X509Certificate[] getAcceptedIssuers() { + return tm.getAcceptedIssuers(); + } + } + + static class NoneExtendedX509KM implements X509KeyManager { + private String keyAlias; + private X509Certificate[] chain; + private PrivateKey privateKey; + + NoneExtendedX509KM(String keyAlias, X509Certificate[] chain, + PrivateKey privateKey) { + this.keyAlias = keyAlias; + this.chain = chain; + this.privateKey = privateKey; + } + + public String[] getClientAliases(String keyType, Principal[] issuers) { + return new String[] {keyAlias}; + } + + public String chooseClientAlias(String[] keyType, Principal[] issuers, + Socket socket) { + return keyAlias; + } + + public String[] getServerAliases(String keyType, Principal[] issuers) { + return new String[] {keyAlias}; + } + + public String chooseServerAlias(String keyType, Principal[] issuers, + Socket socket) { + return keyAlias; + } + + public X509Certificate[] getCertificateChain(String alias) { + return chain; + } + + public PrivateKey getPrivateKey(String alias) { + return privateKey; + } + } + + + // use any free port by default + volatile int serverPort = 0; + + volatile Exception serverException = null; + volatile Exception clientException = null; + + public static void main(String[] args) throws Exception { + if (debug) + System.setProperty("javax.net.debug", "all"); + + /* + * Get the customized arguments. + */ + parseArguments(args); + + /* + * Start the tests. + */ + new TrustTrustedCert(); + } + + Thread clientThread = null; + Thread serverThread = null; + + /* + * Primary constructor, used to drive remainder of the test. + * + * Fork off the other side, then do your work. + */ + TrustTrustedCert() throws Exception { + try { + if (separateServerThread) { + startServer(true); + startClient(false); + } else { + startClient(true); + startServer(false); + } + } catch (Exception e) { + // swallow for now. Show later + } + + /* + * Wait for other side to close down. + */ + if (separateServerThread) { + serverThread.join(); + } else { + clientThread.join(); + } + + /* + * When we get here, the test is pretty much over. + * Which side threw the error? + */ + Exception local; + Exception remote; + String whichRemote; + + if (separateServerThread) { + remote = serverException; + local = clientException; + whichRemote = "server"; + } else { + remote = clientException; + local = serverException; + whichRemote = "client"; + } + + /* + * If both failed, return the curthread's exception, but also + * print the remote side Exception + */ + if ((local != null) && (remote != null)) { + System.out.println(whichRemote + " also threw:"); + remote.printStackTrace(); + System.out.println(); + throw local; + } + + if (remote != null) { + throw remote; + } + + if (local != null) { + throw local; + } + } + + void startServer(boolean newThread) throws Exception { + if (newThread) { + serverThread = new Thread() { + public void run() { + try { + doServerSide(); + } catch (Exception e) { + /* + * Our server thread just died. + * + * Release the client, if not active already... + */ + System.err.println("Server died..."); + serverReady = true; + serverException = e; + } + } + }; + serverThread.start(); + } else { + try { + doServerSide(); + } catch (Exception e) { + serverException = e; + } finally { + serverReady = true; + } + } + } + + void startClient(boolean newThread) throws Exception { + if (newThread) { + clientThread = new Thread() { + public void run() { + try { + doClientSide(); + } catch (Exception e) { + /* + * Our client thread just died. + */ + System.err.println("Client died..."); + clientException = e; + } + } + }; + clientThread.start(); + } else { + try { + doClientSide(); + } catch (Exception e) { + clientException = e; + } + } + } +}